@iflow-ai/iflow-cli 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bundle/iflow.js
CHANGED
|
@@ -481,9 +481,9 @@ ${c}`.trim()}_serializeSingularDataPoint(e,r,n){let o="";e=R3t(e,r);let{value:s,
|
|
|
481
481
|
${o}
|
|
482
482
|
${s}
|
|
483
483
|
`}};aDe.PrometheusSerializer=O3t});var cDr=T(cDe=>{"use strict";Object.defineProperty(cDe,"__esModule",{value:!0});cDe.PrometheusExporter=void 0;var cpe=(Zt(),vt(ur)),Hno=pi(),B3t=ex(),Vno=ve("http"),Wno=k3t(),zno=ve("url"),P3t=class t extends B3t.MetricReader{static DEFAULT_OPTIONS={host:void 0,port:9464,endpoint:"/metrics",prefix:"",appendTimestamp:!1,withResourceConstantLabels:void 0};_host;_port;_baseUrl;_endpoint;_server;_prefix;_appendTimestamp;_serializer;_startServerPromise;constructor(e={},r=()=>{}){super({aggregationSelector:o=>({type:B3t.AggregationType.DEFAULT}),aggregationTemporalitySelector:o=>B3t.AggregationTemporality.CUMULATIVE,metricProducers:e.metricProducers}),this._host=e.host||process.env.OTEL_EXPORTER_PROMETHEUS_HOST||t.DEFAULT_OPTIONS.host,this._port=e.port||Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT)||t.DEFAULT_OPTIONS.port,this._prefix=e.prefix||t.DEFAULT_OPTIONS.prefix,this._appendTimestamp=typeof e.appendTimestamp=="boolean"?e.appendTimestamp:t.DEFAULT_OPTIONS.appendTimestamp;let n=e.withResourceConstantLabels||t.DEFAULT_OPTIONS.withResourceConstantLabels;this._server=(0,Vno.createServer)(this._requestHandler).unref(),this._serializer=new Wno.PrometheusSerializer(this._prefix,this._appendTimestamp,n),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(e.endpoint||t.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,"/$1"),e.preventServerStart!==!0?this.startServer().then(r,o=>{cpe.diag.error(o),r(o)}):r&&queueMicrotask(r)}async onForceFlush(){}onShutdown(){return this.stopServer()}stopServer(){return this._server?new Promise(e=>{this._server.close(r=>{r?r.code!=="ERR_SERVER_NOT_RUNNING"&&(0,Hno.globalErrorHandler)(r):cpe.diag.debug("Prometheus exporter was stopped"),e()})}):(cpe.diag.debug("Prometheus stopServer() was called but server was never started."),Promise.resolve())}startServer(){return this._startServerPromise??=new Promise((e,r)=>{this._server.once("error",r),this._server.listen({port:this._port,host:this._host},()=>{cpe.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`),e()})}),this._startServerPromise}getMetricsRequestHandler(e,r){this._exportMetrics(r)}_requestHandler=(e,r)=>{e.url!=null&&new zno.URL(e.url,this._baseUrl).pathname===this._endpoint?this._exportMetrics(r):this._notFound(r)};_exportMetrics=e=>{e.statusCode=200,e.setHeader("content-type","text/plain"),this.collect().then(r=>{let{resourceMetrics:n,errors:o}=r;o.length&&cpe.diag.error("PrometheusExporter: metrics collection errors",...o),e.end(this._serializer.serialize(n))},r=>{e.end(`# failed to export metrics: ${r}`)})};_notFound=e=>{e.statusCode=404,e.end()}};cDe.PrometheusExporter=P3t});var lDr=T(qK=>{"use strict";Object.defineProperty(qK,"__esModule",{value:!0});qK.PrometheusSerializer=qK.PrometheusExporter=void 0;var Yno=cDr();Object.defineProperty(qK,"PrometheusExporter",{enumerable:!0,get:function(){return Yno.PrometheusExporter}});var Kno=k3t();Object.defineProperty(qK,"PrometheusSerializer",{enumerable:!0,get:function(){return Kno.PrometheusSerializer}})});var uDr=T(lDe=>{"use strict";Object.defineProperty(lDe,"__esModule",{value:!0});lDe.VERSION=void 0;lDe.VERSION="0.206.0"});var fDr=T(uDe=>{"use strict";Object.defineProperty(uDe,"__esModule",{value:!0});uDe.OTLPTraceExporter=void 0;var Xno=(HS(),vt(qS)),Jno=uDr(),Zno=nx(),dDr=(b9(),vt(aN)),M3t=class extends Xno.OTLPExporterBase{constructor(e={}){super((0,dDr.createOtlpHttpExportDelegate)((0,dDr.convertLegacyHttpOptions)(e,"TRACES","v1/traces",{"User-Agent":`OTel-OTLP-Exporter-JavaScript/${Jno.VERSION}`,"Content-Type":"application/json"}),Zno.JsonTraceSerializer))}};uDe.OTLPTraceExporter=M3t});var pDr=T(dDe=>{"use strict";Object.defineProperty(dDe,"__esModule",{value:!0});dDe.OTLPTraceExporter=void 0;var eio=fDr();Object.defineProperty(dDe,"OTLPTraceExporter",{enumerable:!0,get:function(){return eio.OTLPTraceExporter}})});var hDr=T(fDe=>{"use strict";Object.defineProperty(fDe,"__esModule",{value:!0});fDe.OTLPTraceExporter=void 0;var tio=pDr();Object.defineProperty(fDe,"OTLPTraceExporter",{enumerable:!0,get:function(){return tio.OTLPTraceExporter}})});var mDr=T(pDe=>{"use strict";Object.defineProperty(pDe,"__esModule",{value:!0});pDe.OTLPTraceExporter=void 0;var rio=hDr();Object.defineProperty(pDe,"OTLPTraceExporter",{enumerable:!0,get:function(){return rio.OTLPTraceExporter}})});var ADr=T(hDe=>{"use strict";Object.defineProperty(hDe,"__esModule",{value:!0});hDe.OTLPTraceExporter=void 0;var gDr=YIe(),nio=nx(),iio=(HS(),vt(qS)),F3t=class extends iio.OTLPExporterBase{constructor(e={}){super((0,gDr.createOtlpGrpcExportDelegate)((0,gDr.convertLegacyOtlpGrpcOptions)(e,"TRACES"),nio.ProtobufTraceSerializer,"TraceExportService","/opentelemetry.proto.collector.trace.v1.TraceService/Export"))}};hDe.OTLPTraceExporter=F3t});var yDr=T(mDe=>{"use strict";Object.defineProperty(mDe,"__esModule",{value:!0});mDe.OTLPTraceExporter=void 0;var oio=ADr();Object.defineProperty(mDe,"OTLPTraceExporter",{enumerable:!0,get:function(){return oio.OTLPTraceExporter}})});var _Dr=T(ADe=>{"use strict";Object.defineProperty(ADe,"__esModule",{value:!0});ADe.prepareSend=void 0;var L3t=(Zt(),vt(ur)),gDe=pi(),sio=ve("http"),aio=ve("https");function cio(t,e){let r=new URL(t),n=Object.assign({method:"POST",headers:{"Content-Type":"application/json",...e}});return function(s,a){if(s.length===0)return L3t.diag.debug("Zipkin send with empty spans"),a({code:gDe.ExportResultCode.SUCCESS});let{request:c}=r.protocol==="http:"?sio:aio,u=c(r,n,f=>{let p="";f.on("data",h=>{p+=h}),f.on("end",()=>{let h=f.statusCode||0;return L3t.diag.debug(`Zipkin response status code: ${h}, body: ${p}`),h<400?a({code:gDe.ExportResultCode.SUCCESS}):a({code:gDe.ExportResultCode.FAILED,error:new Error(`Got unexpected status code from zipkin: ${h}`)})})});u.on("error",f=>a({code:gDe.ExportResultCode.FAILED,error:f}));let d=JSON.stringify(s);L3t.diag.debug(`Zipkin request payload: ${d}`),u.write(d,"utf8"),u.end()}}ADe.prepareSend=cio});var EDr=T(yDe=>{"use strict";Object.defineProperty(yDe,"__esModule",{value:!0});yDe.prepareSend=void 0;var lio=_Dr();Object.defineProperty(yDe,"prepareSend",{enumerable:!0,get:function(){return lio.prepareSend}})});var U3t=T(_De=>{"use strict";Object.defineProperty(_De,"__esModule",{value:!0});_De.prepareSend=void 0;var uio=EDr();Object.defineProperty(_De,"prepareSend",{enumerable:!0,get:function(){return uio.prepareSend}})});var vDr=T(lpe=>{"use strict";Object.defineProperty(lpe,"__esModule",{value:!0});lpe.SpanKind=void 0;var dio;(function(t){t.CLIENT="CLIENT",t.SERVER="SERVER",t.CONSUMER="CONSUMER",t.PRODUCER="PRODUCER"})(dio=lpe.SpanKind||(lpe.SpanKind={}))});var SDr=T(ev=>{"use strict";Object.defineProperty(ev,"__esModule",{value:!0});ev._toZipkinAnnotations=ev._toZipkinTags=ev.toZipkinSpan=ev.defaultStatusErrorTagName=ev.defaultStatusCodeTagName=void 0;var DN=(Zt(),vt(ur)),Q3t=pi(),EDe=vDr(),fio={[DN.SpanKind.CLIENT]:EDe.SpanKind.CLIENT,[DN.SpanKind.SERVER]:EDe.SpanKind.SERVER,[DN.SpanKind.CONSUMER]:EDe.SpanKind.CONSUMER,[DN.SpanKind.PRODUCER]:EDe.SpanKind.PRODUCER,[DN.SpanKind.INTERNAL]:void 0};ev.defaultStatusCodeTagName="otel.status_code";ev.defaultStatusErrorTagName="error";function pio(t,e,r,n){return{traceId:t.spanContext().traceId,parentId:t.parentSpanContext?.spanId,name:t.name,id:t.spanContext().spanId,kind:fio[t.kind],timestamp:(0,Q3t.hrTimeToMicroseconds)(t.startTime),duration:Math.round((0,Q3t.hrTimeToMicroseconds)(t.duration)),localEndpoint:{serviceName:e},tags:bDr(t,r,n),annotations:t.events.length?CDr(t.events):void 0}}ev.toZipkinSpan=pio;function bDr({attributes:t,resource:e,status:r,droppedAttributesCount:n,droppedEventsCount:o,droppedLinksCount:s},a,c){let u={};for(let d of Object.keys(t))u[d]=String(t[d]);return r.code!==DN.SpanStatusCode.UNSET&&(u[a]=String(DN.SpanStatusCode[r.code])),r.code===DN.SpanStatusCode.ERROR&&r.message&&(u[c]=r.message),n&&(u["otel.dropped_attributes_count"]=String(n)),o&&(u["otel.dropped_events_count"]=String(o)),s&&(u["otel.dropped_links_count"]=String(s)),Object.keys(e.attributes).forEach(d=>u[d]=String(e.attributes[d])),u}ev._toZipkinTags=bDr;function CDr(t){return t.map(e=>({timestamp:Math.round((0,Q3t.hrTimeToMicroseconds)(e.time)),value:e.name}))}ev._toZipkinAnnotations=CDr});var xDr=T(vDe=>{"use strict";Object.defineProperty(vDe,"__esModule",{value:!0});vDe.prepareGetHeaders=void 0;function hio(t){return function(){return t()}}vDe.prepareGetHeaders=hio});var DDr=T(bDe=>{"use strict";Object.defineProperty(bDe,"__esModule",{value:!0});bDe.ZipkinExporter=void 0;var wDr=(Zt(),vt(ur)),TDr=pi(),IDr=U3t(),j3t=SDr(),G3t=(jh(),vt(gA)),mio=xDr(),$3t=class{DEFAULT_SERVICE_NAME="OpenTelemetry Service";_statusCodeTagName;_statusDescriptionTagName;_urlStr;_send;_getHeaders;_serviceName;_isShutdown;_sendingPromises=[];constructor(e={}){this._urlStr=e.url||((0,TDr.getStringFromEnv)("OTEL_EXPORTER_ZIPKIN_ENDPOINT")??"http://localhost:9411/api/v2/spans"),this._send=(0,IDr.prepareSend)(this._urlStr,e.headers),this._serviceName=e.serviceName,this._statusCodeTagName=e.statusCodeTagName||j3t.defaultStatusCodeTagName,this._statusDescriptionTagName=e.statusDescriptionTagName||j3t.defaultStatusErrorTagName,this._isShutdown=!1,typeof e.getExportRequestHeaders=="function"?this._getHeaders=(0,mio.prepareGetHeaders)(e.getExportRequestHeaders):this._beforeSend=function(){}}export(e,r){let n=String(this._serviceName||e[0].resource.attributes[G3t.ATTR_SERVICE_NAME]||this.DEFAULT_SERVICE_NAME);if(wDr.diag.debug("Zipkin exporter export"),this._isShutdown){setTimeout(()=>r({code:TDr.ExportResultCode.FAILED,error:new Error("Exporter has been shutdown")}));return}let o=new Promise(a=>{this._sendSpans(e,n,c=>{a(),r(c)})});this._sendingPromises.push(o);let s=()=>{let a=this._sendingPromises.indexOf(o);this._sendingPromises.splice(a,1)};o.then(s,s)}shutdown(){return wDr.diag.debug("Zipkin exporter shutdown"),this._isShutdown=!0,this.forceFlush()}forceFlush(){return new Promise((e,r)=>{Promise.all(this._sendingPromises).then(()=>{e()},r)})}_beforeSend(){this._getHeaders&&(this._send=(0,IDr.prepareSend)(this._urlStr,this._getHeaders()))}_sendSpans(e,r,n){let o=e.map(s=>(0,j3t.toZipkinSpan)(s,String(s.attributes[G3t.ATTR_SERVICE_NAME]||s.resource.attributes[G3t.ATTR_SERVICE_NAME]||r),this._statusCodeTagName,this._statusDescriptionTagName));return this._beforeSend(),this._send(o,s=>{if(n)return n(s)})}};bDe.ZipkinExporter=$3t});var RDr=T(HK=>{"use strict";Object.defineProperty(HK,"__esModule",{value:!0});HK.ZipkinExporter=HK.prepareSend=void 0;var gio=U3t();Object.defineProperty(HK,"prepareSend",{enumerable:!0,get:function(){return gio.prepareSend}});var Aio=DDr();Object.defineProperty(HK,"ZipkinExporter",{enumerable:!0,get:function(){return Aio.ZipkinExporter}})});var q3t=T(CDe=>{"use strict";Object.defineProperty(CDe,"__esModule",{value:!0});CDe.B3_DEBUG_FLAG_KEY=void 0;var yio=(Zt(),vt(ur));CDe.B3_DEBUG_FLAG_KEY=(0,yio.createContextKey)("OpenTelemetry Context Key B3 Debug Flag")});var upe=T(R3=>{"use strict";Object.defineProperty(R3,"__esModule",{value:!0});R3.X_B3_FLAGS=R3.X_B3_PARENT_SPAN_ID=R3.X_B3_SAMPLED=R3.X_B3_SPAN_ID=R3.X_B3_TRACE_ID=R3.B3_CONTEXT_HEADER=void 0;R3.B3_CONTEXT_HEADER="b3";R3.X_B3_TRACE_ID="x-b3-traceid";R3.X_B3_SPAN_ID="x-b3-spanid";R3.X_B3_SAMPLED="x-b3-sampled";R3.X_B3_PARENT_SPAN_ID="x-b3-parentspanid";R3.X_B3_FLAGS="x-b3-flags"});var kDr=T(xDe=>{"use strict";Object.defineProperty(xDe,"__esModule",{value:!0});xDe.B3MultiPropagator=void 0;var pC=(Zt(),vt(ur)),_io=pi(),NDr=q3t(),I_=upe(),Eio=new Set([!0,"true","True","1",1]),vio=new Set([!1,"false","False","0",0]);function bio(t){return t===pC.TraceFlags.SAMPLED||t===pC.TraceFlags.NONE}function Cio(t){return Array.isArray(t)?t[0]:t}function SDe(t,e,r){let n=e.get(t,r);return Cio(n)}function Sio(t,e){let r=SDe(t,e,I_.X_B3_TRACE_ID);return typeof r=="string"?r.padStart(32,"0"):""}function xio(t,e){let r=SDe(t,e,I_.X_B3_SPAN_ID);return typeof r=="string"?r:""}function ODr(t,e){return SDe(t,e,I_.X_B3_FLAGS)==="1"?"1":void 0}function wio(t,e){let r=SDe(t,e,I_.X_B3_SAMPLED);if(ODr(t,e)==="1"||Eio.has(r))return pC.TraceFlags.SAMPLED;if(r===void 0||vio.has(r))return pC.TraceFlags.NONE}var H3t=class{inject(e,r,n){let o=pC.trace.getSpanContext(e);if(!o||!(0,pC.isSpanContextValid)(o)||(0,_io.isTracingSuppressed)(e))return;let s=e.getValue(NDr.B3_DEBUG_FLAG_KEY);n.set(r,I_.X_B3_TRACE_ID,o.traceId),n.set(r,I_.X_B3_SPAN_ID,o.spanId),s==="1"?n.set(r,I_.X_B3_FLAGS,s):o.traceFlags!==void 0&&n.set(r,I_.X_B3_SAMPLED,(pC.TraceFlags.SAMPLED&o.traceFlags)===pC.TraceFlags.SAMPLED?"1":"0")}extract(e,r,n){let o=Sio(r,n),s=xio(r,n),a=wio(r,n),c=ODr(r,n);return(0,pC.isValidTraceId)(o)&&(0,pC.isValidSpanId)(s)&&bio(a)?(e=e.setValue(NDr.B3_DEBUG_FLAG_KEY,c),pC.trace.setSpanContext(e,{traceId:o,spanId:s,isRemote:!0,traceFlags:a})):e}fields(){return[I_.X_B3_TRACE_ID,I_.X_B3_SPAN_ID,I_.X_B3_FLAGS,I_.X_B3_SAMPLED,I_.X_B3_PARENT_SPAN_ID]}};xDe.B3MultiPropagator=H3t});var PDr=T(wDe=>{"use strict";Object.defineProperty(wDe,"__esModule",{value:!0});wDe.B3SinglePropagator=void 0;var zL=(Zt(),vt(ur)),Tio=pi(),BDr=q3t(),V3t=upe(),Iio=/((?:[0-9a-f]{16}){1,2})-([0-9a-f]{16})(?:-([01d](?![0-9a-f])))?(?:-([0-9a-f]{16}))?/,Dio="0".repeat(16),Rio=new Set(["d","1"]),Nio="d";function Oio(t){return t.length===32?t:`${Dio}${t}`}function kio(t){return t&&Rio.has(t)?zL.TraceFlags.SAMPLED:zL.TraceFlags.NONE}var W3t=class{inject(e,r,n){let o=zL.trace.getSpanContext(e);if(!o||!(0,zL.isSpanContextValid)(o)||(0,Tio.isTracingSuppressed)(e))return;let s=e.getValue(BDr.B3_DEBUG_FLAG_KEY)||o.traceFlags&1,a=`${o.traceId}-${o.spanId}-${s}`;n.set(r,V3t.B3_CONTEXT_HEADER,a)}extract(e,r,n){let o=n.get(r,V3t.B3_CONTEXT_HEADER),s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let a=s.match(Iio);if(!a)return e;let[,c,u,d]=a,f=Oio(c);if(!(0,zL.isValidTraceId)(f)||!(0,zL.isValidSpanId)(u))return e;let p=kio(d);return d===Nio&&(e=e.setValue(BDr.B3_DEBUG_FLAG_KEY,d)),zL.trace.setSpanContext(e,{traceId:f,spanId:u,isRemote:!0,traceFlags:p})}fields(){return[V3t.B3_CONTEXT_HEADER]}};wDe.B3SinglePropagator=W3t});var z3t=T(dpe=>{"use strict";Object.defineProperty(dpe,"__esModule",{value:!0});dpe.B3InjectEncoding=void 0;var Bio;(function(t){t[t.SINGLE_HEADER=0]="SINGLE_HEADER",t[t.MULTI_HEADER=1]="MULTI_HEADER"})(Bio=dpe.B3InjectEncoding||(dpe.B3InjectEncoding={}))});var MDr=T(TDe=>{"use strict";Object.defineProperty(TDe,"__esModule",{value:!0});TDe.B3Propagator=void 0;var Pio=pi(),Mio=kDr(),Fio=PDr(),Lio=upe(),Uio=z3t(),Y3t=class{_b3MultiPropagator=new Mio.B3MultiPropagator;_b3SinglePropagator=new Fio.B3SinglePropagator;_inject;_fields;constructor(e={}){e.injectEncoding===Uio.B3InjectEncoding.MULTI_HEADER?(this._inject=this._b3MultiPropagator.inject,this._fields=this._b3MultiPropagator.fields()):(this._inject=this._b3SinglePropagator.inject,this._fields=this._b3SinglePropagator.fields())}inject(e,r,n){(0,Pio.isTracingSuppressed)(e)||this._inject(e,r,n)}extract(e,r,n){let o=n.get(r,Lio.B3_CONTEXT_HEADER);return(Array.isArray(o)?o[0]:o)?this._b3SinglePropagator.extract(e,r,n):this._b3MultiPropagator.extract(e,r,n)}fields(){return this._fields}};TDe.B3Propagator=Y3t});var FDr=T(Wm=>{"use strict";Object.defineProperty(Wm,"__esModule",{value:!0});Wm.B3InjectEncoding=Wm.X_B3_TRACE_ID=Wm.X_B3_SPAN_ID=Wm.X_B3_SAMPLED=Wm.X_B3_PARENT_SPAN_ID=Wm.X_B3_FLAGS=Wm.B3_CONTEXT_HEADER=Wm.B3Propagator=void 0;var Qio=MDr();Object.defineProperty(Wm,"B3Propagator",{enumerable:!0,get:function(){return Qio.B3Propagator}});var VK=upe();Object.defineProperty(Wm,"B3_CONTEXT_HEADER",{enumerable:!0,get:function(){return VK.B3_CONTEXT_HEADER}});Object.defineProperty(Wm,"X_B3_FLAGS",{enumerable:!0,get:function(){return VK.X_B3_FLAGS}});Object.defineProperty(Wm,"X_B3_PARENT_SPAN_ID",{enumerable:!0,get:function(){return VK.X_B3_PARENT_SPAN_ID}});Object.defineProperty(Wm,"X_B3_SAMPLED",{enumerable:!0,get:function(){return VK.X_B3_SAMPLED}});Object.defineProperty(Wm,"X_B3_SPAN_ID",{enumerable:!0,get:function(){return VK.X_B3_SPAN_ID}});Object.defineProperty(Wm,"X_B3_TRACE_ID",{enumerable:!0,get:function(){return VK.X_B3_TRACE_ID}});var jio=z3t();Object.defineProperty(Wm,"B3InjectEncoding",{enumerable:!0,get:function(){return jio.B3InjectEncoding}})});var LDr=T(hC=>{"use strict";Object.defineProperty(hC,"__esModule",{value:!0});hC.JaegerPropagator=hC.UBER_BAGGAGE_HEADER_PREFIX=hC.UBER_TRACE_ID_HEADER=void 0;var YL=(Zt(),vt(ur)),Gio=pi();hC.UBER_TRACE_ID_HEADER="uber-trace-id";hC.UBER_BAGGAGE_HEADER_PREFIX="uberctx";var K3t=class{_jaegerTraceHeader;_jaegerBaggageHeaderPrefix;constructor(e){typeof e=="string"?(this._jaegerTraceHeader=e,this._jaegerBaggageHeaderPrefix=hC.UBER_BAGGAGE_HEADER_PREFIX):(this._jaegerTraceHeader=e?.customTraceHeader||hC.UBER_TRACE_ID_HEADER,this._jaegerBaggageHeaderPrefix=e?.customBaggageHeaderPrefix||hC.UBER_BAGGAGE_HEADER_PREFIX)}inject(e,r,n){let o=YL.trace.getSpanContext(e),s=YL.propagation.getBaggage(e);if(o&&(0,Gio.isTracingSuppressed)(e)===!1){let a=`0${(o.traceFlags||YL.TraceFlags.NONE).toString(16)}`;n.set(r,this._jaegerTraceHeader,`${o.traceId}:${o.spanId}:0:${a}`)}if(s)for(let[a,c]of s.getAllEntries())n.set(r,`${this._jaegerBaggageHeaderPrefix}-${a}`,encodeURIComponent(c.value))}extract(e,r,n){let o=n.get(r,this._jaegerTraceHeader),s=Array.isArray(o)?o[0]:o,a=n.keys(r).filter(d=>d.startsWith(`${this._jaegerBaggageHeaderPrefix}-`)).map(d=>{let f=n.get(r,d);return{key:d.substring(this._jaegerBaggageHeaderPrefix.length+1),value:Array.isArray(f)?f[0]:f}}),c=e;if(typeof s=="string"){let d=qio(s);d&&(c=YL.trace.setSpanContext(c,d))}if(a.length===0)return c;let u=YL.propagation.getBaggage(e)??YL.propagation.createBaggage();for(let d of a)d.value!==void 0&&(u=u.setEntry(d.key,{value:decodeURIComponent(d.value)}));return c=YL.propagation.setBaggage(c,u),c}fields(){return[this._jaegerTraceHeader]}};hC.JaegerPropagator=K3t;var $io=/^[0-9a-f]{1,2}$/i;function qio(t){let e=decodeURIComponent(t).split(":");if(e.length!==4)return null;let[r,n,,o]=e,s=r.padStart(32,"0"),a=n.padStart(16,"0"),c=$io.test(o)?parseInt(o,16)&1:1;return{traceId:s,spanId:a,isRemote:!0,traceFlags:c}}});var UDr=T(RN=>{"use strict";Object.defineProperty(RN,"__esModule",{value:!0});RN.UBER_TRACE_ID_HEADER=RN.UBER_BAGGAGE_HEADER_PREFIX=RN.JaegerPropagator=void 0;var X3t=LDr();Object.defineProperty(RN,"JaegerPropagator",{enumerable:!0,get:function(){return X3t.JaegerPropagator}});Object.defineProperty(RN,"UBER_BAGGAGE_HEADER_PREFIX",{enumerable:!0,get:function(){return X3t.UBER_BAGGAGE_HEADER_PREFIX}});Object.defineProperty(RN,"UBER_TRACE_ID_HEADER",{enumerable:!0,get:function(){return X3t.UBER_TRACE_ID_HEADER}})});var $Dr=T(tv=>{"use strict";Object.defineProperty(tv,"__esModule",{value:!0});tv.getPropagatorFromEnv=tv.getSpanProcessorsFromEnv=tv.getOtlpProtocolFromEnv=tv.filterBlanksAndNulls=tv.getResourceDetectorsFromEnv=void 0;var NN=(Zt(),vt(ur)),ON=pi(),QDr=rmt(),Hio=mDr(),Vio=yDr(),Wio=RDr(),fpe=UY(),IDe=R9e(),J3t=FDr(),zio=UDr(),Yio="env",Kio="host",Xio="os",Jio="process",Zio="serviceinstance";function eoo(){let t=new Map([[Yio,fpe.envDetector],[Kio,fpe.hostDetector],[Xio,fpe.osDetector],[Zio,fpe.serviceInstanceIdDetector],[Jio,fpe.processDetector]]),e=(0,ON.getStringListFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")??["all"];return e.includes("all")?[...t.values()].flat():e.includes("none")?[]:e.flatMap(r=>{let n=t.get(r);return n||NN.diag.warn(`Invalid resource detector "${r}" specified in the environment variable OTEL_NODE_RESOURCE_DETECTORS`),n||[]})}tv.getResourceDetectorsFromEnv=eoo;function jDr(t){return t.map(e=>e.trim()).filter(e=>e!=="null"&&e!=="")}tv.filterBlanksAndNulls=jDr;function GDr(){return(0,ON.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")??(0,ON.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL")??"http/protobuf"}tv.getOtlpProtocolFromEnv=GDr;function too(){let t=GDr();switch(t){case"grpc":return new Vio.OTLPTraceExporter;case"http/json":return new Hio.OTLPTraceExporter;case"http/protobuf":return new QDr.OTLPTraceExporter;default:return NN.diag.warn(`Unsupported OTLP traces protocol: ${t}. Using http/protobuf.`),new QDr.OTLPTraceExporter}}function roo(){try{let{JaegerExporter:t}=ve("@opentelemetry/exporter-jaeger");return new t}catch(t){throw new Error(`Could not instantiate JaegerExporter. This could be due to the JaegerExporter's lack of support for bundling. If possible, use @opentelemetry/exporter-trace-otlp-proto instead. Original Error: ${t}`)}}function noo(){let t=new Map([["otlp",()=>too()],["zipkin",()=>new Wio.ZipkinExporter],["console",()=>new IDe.ConsoleSpanExporter],["jaeger",()=>roo()]]),e=[],r=[],n=jDr(Array.from(new Set((0,ON.getStringListFromEnv)("OTEL_TRACES_EXPORTER"))));if(n[0]==="none")return NN.diag.warn('OTEL_TRACES_EXPORTER contains "none". SDK will not be initialized.'),[];n.length===0?(NN.diag.debug("OTEL_TRACES_EXPORTER is empty. Using default otlp exporter."),n=["otlp"]):n.length>1&&n.includes("none")&&(NN.diag.warn('OTEL_TRACES_EXPORTER contains "none" along with other exporters. Using default otlp exporter.'),n=["otlp"]);for(let o of n){let s=t.get(o)?.();s?e.push(s):NN.diag.warn(`Unrecognized OTEL_TRACES_EXPORTER value: ${o}.`)}for(let o of e)o instanceof IDe.ConsoleSpanExporter?r.push(new IDe.SimpleSpanProcessor(o)):r.push(new IDe.BatchSpanProcessor(o));return e.length===0&&NN.diag.warn("Unable to set up trace exporter(s) due to invalid exporter and/or protocol values."),r}tv.getSpanProcessorsFromEnv=noo;function ioo(){let t=(0,ON.getStringListFromEnv)("OTEL_PROPAGATORS");if(t==null)return;let e=new Map([["tracecontext",()=>new ON.W3CTraceContextPropagator],["baggage",()=>new ON.W3CBaggagePropagator],["b3",()=>new J3t.B3Propagator],["b3multi",()=>new J3t.B3Propagator({injectEncoding:J3t.B3InjectEncoding.MULTI_HEADER})],["jaeger",()=>new zio.JaegerPropagator]]),r=Array.from(new Set(t)),o=r.map(s=>{let a=e.get(s)?.();if(!a){NN.diag.warn(`Propagator "${s}" requested through environment variable is unavailable.`);return}return a}).reduce((s,a)=>(a&&s.push(a),s),[]);return o.length===0?null:r.length===1?o[0]:new ON.CompositePropagator({propagators:o})}tv.getPropagatorFromEnv=ioo});var VDr=T(DDe=>{"use strict";Object.defineProperty(DDe,"__esModule",{value:!0});DDe.NodeSDK=void 0;var t1=(Zt(),vt(ur)),ooo=PY(),soo=D8r(),WK=UY(),ppe=jmt(),aoo=umt(),coo=KIr(),Z3t=rDr(),loo=oDr(),qDr=cmt(),uoo=c8e(),doo=lDr(),KL=ex(),foo=R9e(),poo=o9e(),hoo=(jh(),vt(gA)),kN=pi(),eyt=$Dr();function HDr(t,e){return parseInt(process.env[t]||"")||e}function moo(){let t=[],e=(0,kN.getStringListFromEnv)("OTEL_METRICS_EXPORTER");return e?(e.length===0&&t1.diag.debug("OTEL_METRICS_EXPORTER is empty. Using default otlp exporter."),e.includes("none")?(t1.diag.info('OTEL_METRICS_EXPORTER contains "none". Metric provider will not be initialized.'),t):(e.forEach(r=>{if(r==="otlp"){let n=process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),o=HDr("OTEL_METRIC_EXPORT_INTERVAL",6e4),s=HDr("OTEL_METRIC_EXPORT_TIMEOUT",3e4);switch(n){case"grpc":t.push(new KL.PeriodicExportingMetricReader({exporter:new loo.OTLPMetricExporter,exportIntervalMillis:o,exportTimeoutMillis:s}));break;case"http/json":t.push(new KL.PeriodicExportingMetricReader({exporter:new uoo.OTLPMetricExporter,exportIntervalMillis:o,exportTimeoutMillis:s}));break;case"http/protobuf":t.push(new KL.PeriodicExportingMetricReader({exporter:new qDr.OTLPMetricExporter,exportIntervalMillis:o,exportTimeoutMillis:s}));break;default:t1.diag.warn(`Unsupported OTLP metrics protocol: "${n}". Using http/protobuf.`),t.push(new KL.PeriodicExportingMetricReader({exporter:new qDr.OTLPMetricExporter,exportIntervalMillis:o,exportTimeoutMillis:s}))}}else r==="console"?t.push(new KL.PeriodicExportingMetricReader({exporter:new KL.ConsoleMetricExporter})):r==="prometheus"?t.push(new doo.PrometheusExporter):t1.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${r}". Supported values are: otlp, console, prometheus, none.`)}),t)):t}var tyt=class{_tracerProviderConfig;_loggerProviderConfig;_meterProviderConfig;_instrumentations;_resource;_resourceDetectors;_autoDetectResources;_tracerProvider;_loggerProvider;_meterProvider;_serviceName;_configuration;_disabled;constructor(e={}){(0,kN.getBooleanFromEnv)("OTEL_SDK_DISABLED")&&(this._disabled=!0);let r=(0,kN.getStringFromEnv)("OTEL_LOG_LEVEL");if(r!=null&&t1.diag.setLogger(new t1.DiagConsoleLogger,{logLevel:(0,kN.diagLogLevelFromString)(r)}),this._configuration=e,this._resource=e.resource??(0,WK.defaultResource)(),this._autoDetectResources=e.autoDetectResources??!0,this._autoDetectResources?e.resourceDetectors!=null?this._resourceDetectors=e.resourceDetectors:(0,kN.getStringFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")?this._resourceDetectors=(0,eyt.getResourceDetectorsFromEnv)():this._resourceDetectors=[WK.envDetector,WK.processDetector,WK.hostDetector]:this._resourceDetectors=[],this._serviceName=e.serviceName,e.traceExporter||e.spanProcessor||e.spanProcessors){let n={};e.sampler&&(n.sampler=e.sampler),e.spanLimits&&(n.spanLimits=e.spanLimits),e.idGenerator&&(n.idGenerator=e.idGenerator),e.spanProcessor&&t1.diag.warn("The 'spanProcessor' option is deprecated. Please use 'spanProcessors' instead.");let o=e.spanProcessor??new foo.BatchSpanProcessor(e.traceExporter),s=e.spanProcessors??[o];this._tracerProviderConfig={tracerConfig:n,spanProcessors:s,contextManager:e.contextManager,textMapPropagator:e.textMapPropagator}}if(e.logRecordProcessors?this._loggerProviderConfig={logRecordProcessors:e.logRecordProcessors}:e.logRecordProcessor?(this._loggerProviderConfig={logRecordProcessors:[e.logRecordProcessor]},t1.diag.warn("The 'logRecordProcessor' option is deprecated. Please use 'logRecordProcessors' instead.")):this.configureLoggerProviderFromEnv(),e.metricReaders||e.metricReader||e.views){let n={};e.metricReaders?n.readers=e.metricReaders:e.metricReader&&(n.readers=[e.metricReader],t1.diag.warn("The 'metricReader' option is deprecated. Please use 'metricReaders' instead.")),e.views&&(n.views=e.views),this._meterProviderConfig=n}this._instrumentations=e.instrumentations?.flat()??[]}start(){if(this._disabled)return;if((0,soo.registerInstrumentations)({instrumentations:this._instrumentations}),this._autoDetectResources){let n={detectors:this._resourceDetectors};this._resource=this._resource.merge((0,WK.detectResources)(n))}this._resource=this._serviceName===void 0?this._resource:this._resource.merge((0,WK.resourceFromAttributes)({[hoo.ATTR_SERVICE_NAME]:this._serviceName}));let e=this._tracerProviderConfig?this._tracerProviderConfig.spanProcessors:(0,eyt.getSpanProcessorsFromEnv)();if(this._tracerProvider=new poo.NodeTracerProvider({...this._configuration,resource:this._resource,spanProcessors:e}),e.length>0&&this._tracerProvider.register({contextManager:this._tracerProviderConfig?.contextManager??this._configuration?.contextManager,propagator:this._tracerProviderConfig?.textMapPropagator??(0,eyt.getPropagatorFromEnv)()}),this._loggerProviderConfig){let n=new ppe.LoggerProvider({resource:this._resource,processors:this._loggerProviderConfig.logRecordProcessors});this._loggerProvider=n,ooo.logs.setGlobalLoggerProvider(n)}let r=moo();if(this._meterProviderConfig||r.length>0){let n=[];this._meterProviderConfig?.readers&&n.push(...this._meterProviderConfig.readers),n.length===0&&r.forEach(s=>n.push(s));let o=new KL.MeterProvider({resource:this._resource,views:this._meterProviderConfig?.views??[],readers:n});this._meterProvider=o,t1.metrics.setGlobalMeterProvider(o);for(let s of this._instrumentations)s.setMeterProvider(t1.metrics.getMeterProvider())}}shutdown(){let e=[];return this._tracerProvider&&e.push(this._tracerProvider.shutdown()),this._loggerProvider&&e.push(this._loggerProvider.shutdown()),this._meterProvider&&e.push(this._meterProvider.shutdown()),Promise.all(e).then(()=>{})}configureLoggerProviderFromEnv(){let e=(0,kN.getStringListFromEnv)("OTEL_LOGS_EXPORTER")??[];if(e.length===0&&(t1.diag.debug("OTEL_LOGS_EXPORTER is empty. Using default otlp exporter."),e.push("otlp")),e.includes("none")){t1.diag.info('OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.');return}let r=[];e.forEach(n=>{if(n==="otlp"){let o=((0,kN.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL")??(0,kN.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim();switch(o){case"grpc":r.push(new coo.OTLPLogExporter);break;case"http/json":r.push(new aoo.OTLPLogExporter);break;case"http/protobuf":r.push(new Z3t.OTLPLogExporter);break;case void 0:case"":r.push(new Z3t.OTLPLogExporter);break;default:t1.diag.warn(`Unsupported OTLP logs protocol: "${o}". Using http/protobuf.`),r.push(new Z3t.OTLPLogExporter)}}else n==="console"?r.push(new ppe.ConsoleLogRecordExporter):t1.diag.warn(`Unsupported OTEL_LOGS_EXPORTER value: "${n}". Supported values are: otlp, console, none.`)}),r.length>0&&(this._loggerProviderConfig={logRecordProcessors:r.map(n=>n instanceof ppe.ConsoleLogRecordExporter?new ppe.SimpleLogRecordProcessor(n):new ppe.BatchLogRecordProcessor(n))})}};DDe.NodeSDK=tyt});var WDr=T(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});oh.NodeSDK=oh.tracing=oh.resources=oh.node=oh.metrics=oh.logs=oh.core=oh.contextBase=oh.api=void 0;oh.api=(Zt(),vt(ur));oh.contextBase=(Zt(),vt(ur));oh.core=pi();oh.logs=jmt();oh.metrics=ex();oh.node=o9e();oh.resources=UY();oh.tracing=R9e();var goo=VDr();Object.defineProperty(oh,"NodeSDK",{enumerable:!0,get:function(){return goo.NodeSDK}})});function Aoo(t,e){return new Promise((r,n)=>{let o=setTimeout(()=>{n(new Error(`Operation timed out after ${e} ms`))},e);t.then(r).catch(n).finally(()=>clearTimeout(o))})}var zDr,RDe,YDr=te(()=>{"use strict";zDr=Ie(ex(),1);RDe=class extends zDr.PeriodicExportingMetricReader{_alignSeconds=[0,20,40];_intervalSeconds=20;constructor(e){if(super({...e,exportIntervalMillis:e.exportIntervalMillis??2e4}),(e.exportIntervalMillis??2e4)!==2e4)throw new Error("Aligned reader only supports 20-second intervals for 0/20/40 alignment")}onInitialized(){let e=new Date,r=e.getSeconds(),n=e.getMilliseconds(),o=this._alignSeconds.find(c=>c>=r),s;o!==void 0?s=(o-r)*1e3-n:(s=(60-r)*1e3-n,o=0),s=Math.max(0,s);let a=setTimeout(()=>{this._alignedExport(),this._interval=setInterval(()=>{this._alignedExport()},this._intervalSeconds*1e3);let c=this._interval;typeof c!="number"&&c?.unref&&c.unref()},s);typeof a!="number"&&a?.unref&&a.unref()}async _alignedExport(){let e=this._exportTimeout;try{await Aoo(this._doCollectAndExport(),e)}catch{}}async _doCollectAndExport(){let e=this._exportTimeout,{resourceMetrics:r,errors:n}=await this.collect({timeoutMillis:e});if(n.length>0,r.resource.asyncAttributesPending)try{await r.resource.waitForAsyncAttributes?.()}catch{}if(r.scopeMetrics.length===0)return;await this._exporter.export(r)}async onShutdown(){let e=this._interval;e&&clearInterval(e),await super.onShutdown()}}});var hpe=T(BN=>{"use strict";Object.defineProperty(BN,"__esModule",{value:!0});BN.isTracingSuppressed=BN.unsuppressTracing=BN.suppressTracing=void 0;var yoo=(Zt(),vt(ur)),ryt=(0,yoo.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function _oo(t){return t.setValue(ryt,!0)}BN.suppressTracing=_oo;function Eoo(t){return t.deleteValue(ryt)}BN.unsuppressTracing=Eoo;function voo(t){return t.getValue(ryt)===!0}BN.isTracingSuppressed=voo});var nyt=T(vA=>{"use strict";Object.defineProperty(vA,"__esModule",{value:!0});vA.BAGGAGE_MAX_TOTAL_LENGTH=vA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=vA.BAGGAGE_MAX_NAME_VALUE_PAIRS=vA.BAGGAGE_HEADER=vA.BAGGAGE_ITEMS_SEPARATOR=vA.BAGGAGE_PROPERTIES_SEPARATOR=vA.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;vA.BAGGAGE_KEY_PAIR_SEPARATOR="=";vA.BAGGAGE_PROPERTIES_SEPARATOR=";";vA.BAGGAGE_ITEMS_SEPARATOR=",";vA.BAGGAGE_HEADER="baggage";vA.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;vA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;vA.BAGGAGE_MAX_TOTAL_LENGTH=8192});var iyt=T(Ox=>{"use strict";Object.defineProperty(Ox,"__esModule",{value:!0});Ox.parseKeyPairsIntoRecord=Ox.parsePairKeyValue=Ox.getKeyPairs=Ox.serializeKeyPairs=void 0;var boo=(Zt(),vt(ur)),XL=nyt();function Coo(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?XL.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>XL.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}Ox.serializeKeyPairs=Coo;function Soo(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=XL.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}Ox.getKeyPairs=Soo;function KDr(t){let e=t.split(XL.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(XL.BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;let o=decodeURIComponent(r.substring(0,n).trim()),s=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=(0,boo.baggageEntryMetadataFromString)(e.join(XL.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:a}}Ox.parsePairKeyValue=KDr;function xoo(t){let e={};return typeof t=="string"&&t.length>0&&t.split(XL.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=KDr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}Ox.parseKeyPairsIntoRecord=xoo});var XDr=T(NDe=>{"use strict";Object.defineProperty(NDe,"__esModule",{value:!0});NDe.W3CBaggagePropagator=void 0;var oyt=(Zt(),vt(ur)),woo=hpe(),JL=nyt(),syt=iyt(),ayt=class{inject(e,r,n){let o=oyt.propagation.getBaggage(e);if(!o||(0,woo.isTracingSuppressed)(e))return;let s=(0,syt.getKeyPairs)(o).filter(c=>c.length<=JL.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,JL.BAGGAGE_MAX_NAME_VALUE_PAIRS),a=(0,syt.serializeKeyPairs)(s);a.length>0&&n.set(r,JL.BAGGAGE_HEADER,a)}extract(e,r,n){let o=n.get(r,JL.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(JL.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let a={};return s.length===0||(s.split(JL.BAGGAGE_ITEMS_SEPARATOR).forEach(u=>{let d=(0,syt.parsePairKeyValue)(u);if(d){let f={value:d.value};d.metadata&&(f.metadata=d.metadata),a[d.key]=f}}),Object.entries(a).length===0)?e:oyt.propagation.setBaggage(e,oyt.propagation.createBaggage(a))}fields(){return[JL.BAGGAGE_HEADER]}};NDe.W3CBaggagePropagator=ayt});var JDr=T(ODe=>{"use strict";Object.defineProperty(ODe,"__esModule",{value:!0});ODe.AnchoredClock=void 0;var cyt=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,r){this._monotonicClock=r,this._epochMillis=e.now(),this._performanceMillis=r.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}};ODe.AnchoredClock=cyt});var nRr=T(PN=>{"use strict";Object.defineProperty(PN,"__esModule",{value:!0});PN.isAttributeValue=PN.isAttributeKey=PN.sanitizeAttributes=void 0;var ZDr=(Zt(),vt(ur));function Too(t){let e={};if(typeof t!="object"||t==null)return e;for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;if(!eRr(r)){ZDr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!tRr(n)){ZDr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}PN.sanitizeAttributes=Too;function eRr(t){return typeof t=="string"&&t!==""}PN.isAttributeKey=eRr;function tRr(t){return t==null?!0:Array.isArray(t)?Ioo(t):rRr(typeof t)}PN.isAttributeValue=tRr;function Ioo(t){let e;for(let r of t){if(r==null)continue;let n=typeof r;if(n!==e){if(!e){if(rRr(n)){e=n;continue}return!1}return!1}}return!0}function rRr(t){switch(t){case"number":case"boolean":case"string":return!0}return!1}});var lyt=T(kDe=>{"use strict";Object.defineProperty(kDe,"__esModule",{value:!0});kDe.loggingErrorHandler=void 0;var Doo=(Zt(),vt(ur));function Roo(){return t=>{Doo.diag.error(Noo(t))}}kDe.loggingErrorHandler=Roo;function Noo(t){return typeof t=="string"?t:JSON.stringify(Ooo(t))}function Ooo(t){let e={},r=t;for(;r!==null;)Object.getOwnPropertyNames(r).forEach(n=>{if(e[n])return;let o=r[n];o&&(e[n]=String(o))}),r=Object.getPrototypeOf(r);return e}});var oRr=T(zK=>{"use strict";Object.defineProperty(zK,"__esModule",{value:!0});zK.globalErrorHandler=zK.setGlobalErrorHandler=void 0;var koo=lyt(),iRr=(0,koo.loggingErrorHandler)();function Boo(t){iRr=t}zK.setGlobalErrorHandler=Boo;function Poo(t){try{iRr(t)}catch{}}zK.globalErrorHandler=Poo});var lRr=T(kx=>{"use strict";Object.defineProperty(kx,"__esModule",{value:!0});kx.getStringListFromEnv=kx.getBooleanFromEnv=kx.getStringFromEnv=kx.getNumberFromEnv=void 0;var sRr=(Zt(),vt(ur)),aRr=ve("util");function Moo(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){sRr.diag.warn(`Unknown value ${(0,aRr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}kx.getNumberFromEnv=Moo;function cRr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}kx.getStringFromEnv=cRr;function Foo(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||sRr.diag.warn(`Unknown value ${(0,aRr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}kx.getBooleanFromEnv=Foo;function Loo(t){return cRr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}kx.getStringListFromEnv=Loo});var uRr=T(BDe=>{"use strict";Object.defineProperty(BDe,"__esModule",{value:!0});BDe._globalThis=void 0;BDe._globalThis=typeof globalThis=="object"?globalThis:global});var dRr=T(PDe=>{"use strict";Object.defineProperty(PDe,"__esModule",{value:!0});PDe.otperformance=void 0;var Uoo=ve("perf_hooks");PDe.otperformance=Uoo.performance});var fRr=T(MDe=>{"use strict";Object.defineProperty(MDe,"__esModule",{value:!0});MDe.VERSION=void 0;MDe.VERSION="2.2.0"});var pRr=T(FDe=>{"use strict";Object.defineProperty(FDe,"__esModule",{value:!0});FDe.ATTR_PROCESS_RUNTIME_NAME=void 0;FDe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var hRr=T(UDe=>{"use strict";Object.defineProperty(UDe,"__esModule",{value:!0});UDe.SDK_INFO=void 0;var Qoo=fRr(),LDe=(jh(),vt(gA)),joo=pRr();UDe.SDK_INFO={[LDe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[joo.ATTR_PROCESS_RUNTIME_NAME]:"node",[LDe.ATTR_TELEMETRY_SDK_LANGUAGE]:LDe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[LDe.ATTR_TELEMETRY_SDK_VERSION]:Qoo.VERSION}});var mRr=T(bA=>{"use strict";Object.defineProperty(bA,"__esModule",{value:!0});bA.SDK_INFO=bA.otperformance=bA._globalThis=bA.getStringListFromEnv=bA.getNumberFromEnv=bA.getBooleanFromEnv=bA.getStringFromEnv=void 0;var QDe=lRr();Object.defineProperty(bA,"getStringFromEnv",{enumerable:!0,get:function(){return QDe.getStringFromEnv}});Object.defineProperty(bA,"getBooleanFromEnv",{enumerable:!0,get:function(){return QDe.getBooleanFromEnv}});Object.defineProperty(bA,"getNumberFromEnv",{enumerable:!0,get:function(){return QDe.getNumberFromEnv}});Object.defineProperty(bA,"getStringListFromEnv",{enumerable:!0,get:function(){return QDe.getStringListFromEnv}});var Goo=uRr();Object.defineProperty(bA,"_globalThis",{enumerable:!0,get:function(){return Goo._globalThis}});var $oo=dRr();Object.defineProperty(bA,"otperformance",{enumerable:!0,get:function(){return $oo.otperformance}});var qoo=hRr();Object.defineProperty(bA,"SDK_INFO",{enumerable:!0,get:function(){return qoo.SDK_INFO}})});var uyt=T(CA=>{"use strict";Object.defineProperty(CA,"__esModule",{value:!0});CA.getStringListFromEnv=CA.getNumberFromEnv=CA.getStringFromEnv=CA.getBooleanFromEnv=CA.otperformance=CA._globalThis=CA.SDK_INFO=void 0;var ZL=mRr();Object.defineProperty(CA,"SDK_INFO",{enumerable:!0,get:function(){return ZL.SDK_INFO}});Object.defineProperty(CA,"_globalThis",{enumerable:!0,get:function(){return ZL._globalThis}});Object.defineProperty(CA,"otperformance",{enumerable:!0,get:function(){return ZL.otperformance}});Object.defineProperty(CA,"getBooleanFromEnv",{enumerable:!0,get:function(){return ZL.getBooleanFromEnv}});Object.defineProperty(CA,"getStringFromEnv",{enumerable:!0,get:function(){return ZL.getStringFromEnv}});Object.defineProperty(CA,"getNumberFromEnv",{enumerable:!0,get:function(){return ZL.getNumberFromEnv}});Object.defineProperty(CA,"getStringListFromEnv",{enumerable:!0,get:function(){return ZL.getStringListFromEnv}})});var _Rr=T(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});Cu.addHrTimes=Cu.isTimeInput=Cu.isTimeInputHrTime=Cu.hrTimeToMicroseconds=Cu.hrTimeToMilliseconds=Cu.hrTimeToNanoseconds=Cu.hrTimeToTimeStamp=Cu.hrTimeDuration=Cu.timeInputToHrTime=Cu.hrTime=Cu.getTimeOrigin=Cu.millisToHrTime=void 0;var dyt=uyt(),gRr=9,Hoo=6,Voo=Math.pow(10,Hoo),jDe=Math.pow(10,gRr);function mpe(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Voo);return[r,n]}Cu.millisToHrTime=mpe;function fyt(){let t=dyt.otperformance.timeOrigin;if(typeof t!="number"){let e=dyt.otperformance;t=e.timing&&e.timing.fetchStart}return t}Cu.getTimeOrigin=fyt;function ARr(t){let e=mpe(fyt()),r=mpe(typeof t=="number"?t:dyt.otperformance.now());return yRr(e,r)}Cu.hrTime=ARr;function Woo(t){if(pyt(t))return t;if(typeof t=="number")return t<fyt()?ARr(t):mpe(t);if(t instanceof Date)return mpe(t.getTime());throw TypeError("Invalid input type")}Cu.timeInputToHrTime=Woo;function zoo(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=jDe),[r,n]}Cu.hrTimeDuration=zoo;function Yoo(t){let e=gRr,r=`${"0".repeat(e)}${t[1]}Z`,n=r.substring(r.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",n)}Cu.hrTimeToTimeStamp=Yoo;function Koo(t){return t[0]*jDe+t[1]}Cu.hrTimeToNanoseconds=Koo;function Xoo(t){return t[0]*1e3+t[1]/1e6}Cu.hrTimeToMilliseconds=Xoo;function Joo(t){return t[0]*1e6+t[1]/1e3}Cu.hrTimeToMicroseconds=Joo;function pyt(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}Cu.isTimeInputHrTime=pyt;function Zoo(t){return pyt(t)||typeof t=="number"||t instanceof Date}Cu.isTimeInput=Zoo;function yRr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=jDe&&(r[1]-=jDe,r[0]+=1),r}Cu.addHrTimes=yRr});var ERr=T(GDe=>{"use strict";Object.defineProperty(GDe,"__esModule",{value:!0});GDe.unrefTimer=void 0;function eso(t){typeof t!="number"&&t.unref()}GDe.unrefTimer=eso});var vRr=T(gpe=>{"use strict";Object.defineProperty(gpe,"__esModule",{value:!0});gpe.ExportResultCode=void 0;var tso;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(tso=gpe.ExportResultCode||(gpe.ExportResultCode={}))});var CRr=T($De=>{"use strict";Object.defineProperty($De,"__esModule",{value:!0});$De.CompositePropagator=void 0;var bRr=(Zt(),vt(ur)),hyt=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(r=>typeof r.fields=="function"?r.fields():[]).reduce((r,n)=>r.concat(n),[])))}inject(e,r,n){for(let o of this._propagators)try{o.inject(e,r,n)}catch(s){bRr.diag.warn(`Failed to inject with ${o.constructor.name}. Err: ${s.message}`)}}extract(e,r,n){return this._propagators.reduce((o,s)=>{try{return s.extract(o,r,n)}catch(a){bRr.diag.warn(`Failed to extract with ${s.constructor.name}. Err: ${a.message}`)}return o},e)}fields(){return this._fields.slice()}};$De.CompositePropagator=hyt});var SRr=T(YK=>{"use strict";Object.defineProperty(YK,"__esModule",{value:!0});YK.validateValue=YK.validateKey=void 0;var myt="[_0-9a-z-*/]",rso=`[a-z]${myt}{0,255}`,nso=`[a-z0-9]${myt}{0,240}@[a-z]${myt}{0,13}`,iso=new RegExp(`^(?:${rso}|${nso})$`),oso=/^[ -~]{0,255}[!-~]$/,sso=/,|=/;function aso(t){return iso.test(t)}YK.validateKey=aso;function cso(t){return oso.test(t)&&!sso.test(t)}YK.validateValue=cso});var Ayt=T(qDe=>{"use strict";Object.defineProperty(qDe,"__esModule",{value:!0});qDe.TraceState=void 0;var xRr=SRr(),wRr=32,lso=512,TRr=",",IRr="=",gyt=class t{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,r)=>(e.push(r+IRr+this.get(r)),e),[]).join(TRr)}_parse(e){e.length>lso||(this._internalState=e.split(TRr).reverse().reduce((r,n)=>{let o=n.trim(),s=o.indexOf(IRr);if(s!==-1){let a=o.slice(0,s),c=o.slice(s+1,n.length);(0,xRr.validateKey)(a)&&(0,xRr.validateValue)(c)&&r.set(a,c)}return r},new Map),this._internalState.size>wRr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,wRr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};qDe.TraceState=gyt});var RRr=T(SA=>{"use strict";Object.defineProperty(SA,"__esModule",{value:!0});SA.W3CTraceContextPropagator=SA.parseTraceParent=SA.TRACE_STATE_HEADER=SA.TRACE_PARENT_HEADER=void 0;var HDe=(Zt(),vt(ur)),uso=hpe(),dso=Ayt();SA.TRACE_PARENT_HEADER="traceparent";SA.TRACE_STATE_HEADER="tracestate";var fso="00",pso="(?!ff)[\\da-f]{2}",hso="(?![0]{32})[\\da-f]{32}",mso="(?![0]{16})[\\da-f]{16}",gso="[\\da-f]{2}",Aso=new RegExp(`^\\s?(${pso})-(${hso})-(${mso})-(${gso})(-.*)?\\s?$`);function DRr(t){let e=Aso.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}SA.parseTraceParent=DRr;var yyt=class{inject(e,r,n){let o=HDe.trace.getSpanContext(e);if(!o||(0,uso.isTracingSuppressed)(e)||!(0,HDe.isSpanContextValid)(o))return;let s=`${fso}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||HDe.TraceFlags.NONE).toString(16)}`;n.set(r,SA.TRACE_PARENT_HEADER,s),o.traceState&&n.set(r,SA.TRACE_STATE_HEADER,o.traceState.serialize())}extract(e,r,n){let o=n.get(r,SA.TRACE_PARENT_HEADER);if(!o)return e;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let a=DRr(s);if(!a)return e;a.isRemote=!0;let c=n.get(r,SA.TRACE_STATE_HEADER);if(c){let u=Array.isArray(c)?c.join(","):c;a.traceState=new dso.TraceState(typeof u=="string"?u:void 0)}return HDe.trace.setSpanContext(e,a)}fields(){return[SA.TRACE_PARENT_HEADER,SA.TRACE_STATE_HEADER]}};SA.W3CTraceContextPropagator=yyt});var NRr=T(mC=>{"use strict";Object.defineProperty(mC,"__esModule",{value:!0});mC.getRPCMetadata=mC.deleteRPCMetadata=mC.setRPCMetadata=mC.RPCType=void 0;var yso=(Zt(),vt(ur)),_yt=(0,yso.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),_so;(function(t){t.HTTP="http"})(_so=mC.RPCType||(mC.RPCType={}));function Eso(t,e){return t.setValue(_yt,e)}mC.setRPCMetadata=Eso;function vso(t){return t.deleteValue(_yt)}mC.deleteRPCMetadata=vso;function bso(t){return t.getValue(_yt)}mC.getRPCMetadata=bso});var MRr=T(VDe=>{"use strict";Object.defineProperty(VDe,"__esModule",{value:!0});VDe.isPlainObject=void 0;var Cso="[object Object]",Sso="[object Null]",xso="[object Undefined]",wso=Function.prototype,ORr=wso.toString,Tso=ORr.call(Object),Iso=Object.getPrototypeOf,kRr=Object.prototype,BRr=kRr.hasOwnProperty,eU=Symbol?Symbol.toStringTag:void 0,PRr=kRr.toString;function Dso(t){if(!Rso(t)||Nso(t)!==Cso)return!1;let e=Iso(t);if(e===null)return!0;let r=BRr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&ORr.call(r)===Tso}VDe.isPlainObject=Dso;function Rso(t){return t!=null&&typeof t=="object"}function Nso(t){return t==null?t===void 0?xso:Sso:eU&&eU in Object(t)?Oso(t):kso(t)}function Oso(t){let e=BRr.call(t,eU),r=t[eU],n=!1;try{t[eU]=void 0,n=!0}catch{}let o=PRr.call(t);return n&&(e?t[eU]=r:delete t[eU]),o}function kso(t){return PRr.call(t)}});var jRr=T(YDe=>{"use strict";Object.defineProperty(YDe,"__esModule",{value:!0});YDe.merge=void 0;var FRr=MRr(),Bso=20;function Pso(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=URr(e,t.shift(),0,r);return e}YDe.merge=Pso;function Eyt(t){return zDe(t)?t.slice():t}function URr(t,e,r=0,n){let o;if(!(r>Bso)){if(r++,WDe(t)||WDe(e)||QRr(e))o=Eyt(e);else if(zDe(t)){if(o=t.slice(),zDe(e))for(let s=0,a=e.length;s<a;s++)o.push(Eyt(e[s]));else if(Ape(e)){let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a];o[u]=Eyt(e[u])}}}else if(Ape(t))if(Ape(e)){if(!Mso(t,e))return e;o=Object.assign({},t);let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a],d=e[u];if(WDe(d))typeof d>"u"?delete o[u]:o[u]=d;else{let f=o[u],p=d;if(LRr(t,u,n)||LRr(e,u,n))delete o[u];else{if(Ape(f)&&Ape(p)){let h=n.get(f)||[],m=n.get(p)||[];h.push({obj:t,key:u}),m.push({obj:e,key:u}),n.set(f,h),n.set(p,m)}o[u]=URr(o[u],d,r,n)}}}}else o=e;return o}}function LRr(t,e,r){let n=r.get(t[e])||[];for(let o=0,s=n.length;o<s;o++){let a=n[o];if(a.key===e&&a.obj===t)return!0}return!1}function zDe(t){return Array.isArray(t)}function QRr(t){return typeof t=="function"}function Ape(t){return!WDe(t)&&!zDe(t)&&!QRr(t)&&typeof t=="object"}function WDe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function Mso(t,e){return!(!(0,FRr.isPlainObject)(t)||!(0,FRr.isPlainObject)(e))}});var GRr=T(KK=>{"use strict";Object.defineProperty(KK,"__esModule",{value:!0});KK.callWithTimeout=KK.TimeoutError=void 0;var KDe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};KK.TimeoutError=KDe;function Fso(t,e){let r,n=new Promise(function(s,a){r=setTimeout(function(){a(new KDe("Operation timed out."))},e)});return Promise.race([t,n]).then(o=>(clearTimeout(r),o),o=>{throw clearTimeout(r),o})}KK.callWithTimeout=Fso});var qRr=T(XK=>{"use strict";Object.defineProperty(XK,"__esModule",{value:!0});XK.isUrlIgnored=XK.urlMatches=void 0;function $Rr(t,e){return typeof e=="string"?t===e:!!t.match(e)}XK.urlMatches=$Rr;function Lso(t,e){if(!e)return!1;for(let r of e)if($Rr(t,r))return!0;return!1}XK.isUrlIgnored=Lso});var HRr=T(XDe=>{"use strict";Object.defineProperty(XDe,"__esModule",{value:!0});XDe.Deferred=void 0;var vyt=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,r)=>{this._resolve=e,this._reject=r})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}};XDe.Deferred=vyt});var VRr=T(JDe=>{"use strict";Object.defineProperty(JDe,"__esModule",{value:!0});JDe.BindOnceFuture=void 0;var Uso=HRr(),byt=class{_callback;_that;_isCalled=!1;_deferred=new Uso.Deferred;constructor(e,r){this._callback=e,this._that=r}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(r=>this._deferred.resolve(r),r=>this._deferred.reject(r))}catch(r){this._deferred.reject(r)}}return this._deferred.promise}};JDe.BindOnceFuture=byt});var zRr=T(ZDe=>{"use strict";Object.defineProperty(ZDe,"__esModule",{value:!0});ZDe.diagLogLevelFromString=void 0;var F9=(Zt(),vt(ur)),WRr={ALL:F9.DiagLogLevel.ALL,VERBOSE:F9.DiagLogLevel.VERBOSE,DEBUG:F9.DiagLogLevel.DEBUG,INFO:F9.DiagLogLevel.INFO,WARN:F9.DiagLogLevel.WARN,ERROR:F9.DiagLogLevel.ERROR,NONE:F9.DiagLogLevel.NONE};function Qso(t){if(t==null)return;let e=WRr[t.toUpperCase()];return e??(F9.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys(WRr)}, using default`),F9.DiagLogLevel.INFO)}ZDe.diagLogLevelFromString=Qso});var KRr=T(eRe=>{"use strict";Object.defineProperty(eRe,"__esModule",{value:!0});eRe._export=void 0;var YRr=(Zt(),vt(ur)),jso=hpe();function Gso(t,e){return new Promise(r=>{YRr.context.with((0,jso.suppressTracing)(YRr.context.active()),()=>{t.export(e,n=>{r(n)})})})}eRe._export=Gso});var Syt=T(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.internal=jr.diagLogLevelFromString=jr.BindOnceFuture=jr.urlMatches=jr.isUrlIgnored=jr.callWithTimeout=jr.TimeoutError=jr.merge=jr.TraceState=jr.unsuppressTracing=jr.suppressTracing=jr.isTracingSuppressed=jr.setRPCMetadata=jr.getRPCMetadata=jr.deleteRPCMetadata=jr.RPCType=jr.parseTraceParent=jr.W3CTraceContextPropagator=jr.TRACE_STATE_HEADER=jr.TRACE_PARENT_HEADER=jr.CompositePropagator=jr.otperformance=jr.getStringListFromEnv=jr.getNumberFromEnv=jr.getBooleanFromEnv=jr.getStringFromEnv=jr._globalThis=jr.SDK_INFO=jr.parseKeyPairsIntoRecord=jr.ExportResultCode=jr.unrefTimer=jr.timeInputToHrTime=jr.millisToHrTime=jr.isTimeInputHrTime=jr.isTimeInput=jr.hrTimeToTimeStamp=jr.hrTimeToNanoseconds=jr.hrTimeToMilliseconds=jr.hrTimeToMicroseconds=jr.hrTimeDuration=jr.hrTime=jr.getTimeOrigin=jr.addHrTimes=jr.loggingErrorHandler=jr.setGlobalErrorHandler=jr.globalErrorHandler=jr.sanitizeAttributes=jr.isAttributeValue=jr.AnchoredClock=jr.W3CBaggagePropagator=void 0;var $so=XDr();Object.defineProperty(jr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return $so.W3CBaggagePropagator}});var qso=JDr();Object.defineProperty(jr,"AnchoredClock",{enumerable:!0,get:function(){return qso.AnchoredClock}});var XRr=nRr();Object.defineProperty(jr,"isAttributeValue",{enumerable:!0,get:function(){return XRr.isAttributeValue}});Object.defineProperty(jr,"sanitizeAttributes",{enumerable:!0,get:function(){return XRr.sanitizeAttributes}});var JRr=oRr();Object.defineProperty(jr,"globalErrorHandler",{enumerable:!0,get:function(){return JRr.globalErrorHandler}});Object.defineProperty(jr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return JRr.setGlobalErrorHandler}});var Hso=lyt();Object.defineProperty(jr,"loggingErrorHandler",{enumerable:!0,get:function(){return Hso.loggingErrorHandler}});var rv=_Rr();Object.defineProperty(jr,"addHrTimes",{enumerable:!0,get:function(){return rv.addHrTimes}});Object.defineProperty(jr,"getTimeOrigin",{enumerable:!0,get:function(){return rv.getTimeOrigin}});Object.defineProperty(jr,"hrTime",{enumerable:!0,get:function(){return rv.hrTime}});Object.defineProperty(jr,"hrTimeDuration",{enumerable:!0,get:function(){return rv.hrTimeDuration}});Object.defineProperty(jr,"hrTimeToMicroseconds",{enumerable:!0,get:function(){return rv.hrTimeToMicroseconds}});Object.defineProperty(jr,"hrTimeToMilliseconds",{enumerable:!0,get:function(){return rv.hrTimeToMilliseconds}});Object.defineProperty(jr,"hrTimeToNanoseconds",{enumerable:!0,get:function(){return rv.hrTimeToNanoseconds}});Object.defineProperty(jr,"hrTimeToTimeStamp",{enumerable:!0,get:function(){return rv.hrTimeToTimeStamp}});Object.defineProperty(jr,"isTimeInput",{enumerable:!0,get:function(){return rv.isTimeInput}});Object.defineProperty(jr,"isTimeInputHrTime",{enumerable:!0,get:function(){return rv.isTimeInputHrTime}});Object.defineProperty(jr,"millisToHrTime",{enumerable:!0,get:function(){return rv.millisToHrTime}});Object.defineProperty(jr,"timeInputToHrTime",{enumerable:!0,get:function(){return rv.timeInputToHrTime}});var Vso=ERr();Object.defineProperty(jr,"unrefTimer",{enumerable:!0,get:function(){return Vso.unrefTimer}});var Wso=vRr();Object.defineProperty(jr,"ExportResultCode",{enumerable:!0,get:function(){return Wso.ExportResultCode}});var zso=iyt();Object.defineProperty(jr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return zso.parseKeyPairsIntoRecord}});var tU=uyt();Object.defineProperty(jr,"SDK_INFO",{enumerable:!0,get:function(){return tU.SDK_INFO}});Object.defineProperty(jr,"_globalThis",{enumerable:!0,get:function(){return tU._globalThis}});Object.defineProperty(jr,"getStringFromEnv",{enumerable:!0,get:function(){return tU.getStringFromEnv}});Object.defineProperty(jr,"getBooleanFromEnv",{enumerable:!0,get:function(){return tU.getBooleanFromEnv}});Object.defineProperty(jr,"getNumberFromEnv",{enumerable:!0,get:function(){return tU.getNumberFromEnv}});Object.defineProperty(jr,"getStringListFromEnv",{enumerable:!0,get:function(){return tU.getStringListFromEnv}});Object.defineProperty(jr,"otperformance",{enumerable:!0,get:function(){return tU.otperformance}});var Yso=CRr();Object.defineProperty(jr,"CompositePropagator",{enumerable:!0,get:function(){return Yso.CompositePropagator}});var tRe=RRr();Object.defineProperty(jr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return tRe.TRACE_PARENT_HEADER}});Object.defineProperty(jr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return tRe.TRACE_STATE_HEADER}});Object.defineProperty(jr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return tRe.W3CTraceContextPropagator}});Object.defineProperty(jr,"parseTraceParent",{enumerable:!0,get:function(){return tRe.parseTraceParent}});var rRe=NRr();Object.defineProperty(jr,"RPCType",{enumerable:!0,get:function(){return rRe.RPCType}});Object.defineProperty(jr,"deleteRPCMetadata",{enumerable:!0,get:function(){return rRe.deleteRPCMetadata}});Object.defineProperty(jr,"getRPCMetadata",{enumerable:!0,get:function(){return rRe.getRPCMetadata}});Object.defineProperty(jr,"setRPCMetadata",{enumerable:!0,get:function(){return rRe.setRPCMetadata}});var Cyt=hpe();Object.defineProperty(jr,"isTracingSuppressed",{enumerable:!0,get:function(){return Cyt.isTracingSuppressed}});Object.defineProperty(jr,"suppressTracing",{enumerable:!0,get:function(){return Cyt.suppressTracing}});Object.defineProperty(jr,"unsuppressTracing",{enumerable:!0,get:function(){return Cyt.unsuppressTracing}});var Kso=Ayt();Object.defineProperty(jr,"TraceState",{enumerable:!0,get:function(){return Kso.TraceState}});var Xso=jRr();Object.defineProperty(jr,"merge",{enumerable:!0,get:function(){return Xso.merge}});var ZRr=GRr();Object.defineProperty(jr,"TimeoutError",{enumerable:!0,get:function(){return ZRr.TimeoutError}});Object.defineProperty(jr,"callWithTimeout",{enumerable:!0,get:function(){return ZRr.callWithTimeout}});var eNr=qRr();Object.defineProperty(jr,"isUrlIgnored",{enumerable:!0,get:function(){return eNr.isUrlIgnored}});Object.defineProperty(jr,"urlMatches",{enumerable:!0,get:function(){return eNr.urlMatches}});var Jso=VRr();Object.defineProperty(jr,"BindOnceFuture",{enumerable:!0,get:function(){return Jso.BindOnceFuture}});var Zso=zRr();Object.defineProperty(jr,"diagLogLevelFromString",{enumerable:!0,get:function(){return Zso.diagLogLevelFromString}});var eao=KRr();jr.internal={_export:eao._export}});var tNr=T(nRe=>{"use strict";Object.defineProperty(nRe,"__esModule",{value:!0});nRe.defaultServiceName=void 0;function tao(){return`unknown_service:${process.argv0}`}nRe.defaultServiceName=tao});var rNr=T(iRe=>{"use strict";Object.defineProperty(iRe,"__esModule",{value:!0});iRe.defaultServiceName=void 0;var rao=tNr();Object.defineProperty(iRe,"defaultServiceName",{enumerable:!0,get:function(){return rao.defaultServiceName}})});var xyt=T(oRe=>{"use strict";Object.defineProperty(oRe,"__esModule",{value:!0});oRe.defaultServiceName=void 0;var nao=rNr();Object.defineProperty(oRe,"defaultServiceName",{enumerable:!0,get:function(){return nao.defaultServiceName}})});var nNr=T(JK=>{"use strict";Object.defineProperty(JK,"__esModule",{value:!0});JK.identity=JK.isPromiseLike=void 0;var iao=t=>t!==null&&typeof t=="object"&&typeof t.then=="function";JK.isPromiseLike=iao;function oao(t){return t}JK.identity=oao});var Iyt=T(Bx=>{"use strict";Object.defineProperty(Bx,"__esModule",{value:!0});Bx.defaultResource=Bx.emptyResource=Bx.resourceFromDetectedResource=Bx.resourceFromAttributes=void 0;var _pe=(Zt(),vt(ur)),wyt=Syt(),rU=(jh(),vt(gA)),sao=xyt(),ype=nNr(),sRe=class t{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(e,r){let n=new t({},r);return n._rawAttributes=iNr(e),n._asyncAttributesPending=e.filter(([o,s])=>(0,ype.isPromiseLike)(s)).length>0,n}constructor(e,r){let n=e.attributes??{};this._rawAttributes=Object.entries(n).map(([o,s])=>((0,ype.isPromiseLike)(s)&&(this._asyncAttributesPending=!0),[o,s])),this._rawAttributes=iNr(this._rawAttributes),this._schemaUrl=uao(r?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){let[r,n]=this._rawAttributes[e];this._rawAttributes[e]=[r,(0,ype.isPromiseLike)(n)?await n:n]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&_pe.diag.error("Accessing resource attributes before async attributes settled"),this._memoizedAttributes)return this._memoizedAttributes;let e={};for(let[r,n]of this._rawAttributes){if((0,ype.isPromiseLike)(n)){_pe.diag.debug(`Unsettled resource attribute ${r} skipped`);continue}n!=null&&(e[r]??=n)}return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(e){if(e==null)return this;let r=dao(this,e),n=r?{schemaUrl:r}:void 0;return t.FromAttributeList([...e.getRawAttributes(),...this.getRawAttributes()],n)}};function Tyt(t,e){return sRe.FromAttributeList(Object.entries(t),e)}Bx.resourceFromAttributes=Tyt;function aao(t,e){return new sRe(t,e)}Bx.resourceFromDetectedResource=aao;function cao(){return Tyt({})}Bx.emptyResource=cao;function lao(){return Tyt({[rU.ATTR_SERVICE_NAME]:(0,sao.defaultServiceName)(),[rU.ATTR_TELEMETRY_SDK_LANGUAGE]:wyt.SDK_INFO[rU.ATTR_TELEMETRY_SDK_LANGUAGE],[rU.ATTR_TELEMETRY_SDK_NAME]:wyt.SDK_INFO[rU.ATTR_TELEMETRY_SDK_NAME],[rU.ATTR_TELEMETRY_SDK_VERSION]:wyt.SDK_INFO[rU.ATTR_TELEMETRY_SDK_VERSION]})}Bx.defaultResource=lao;function iNr(t){return t.map(([e,r])=>(0,ype.isPromiseLike)(r)?[e,r.catch(n=>{_pe.diag.debug("promise rejection for resource attribute: %s - %s",e,n)})]:[e,r])}function uao(t){if(typeof t=="string"||t===void 0)return t;_pe.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t)}function dao(t,e){let r=t?.schemaUrl,n=e?.schemaUrl,o=r===void 0||r==="",s=n===void 0||n==="";if(o)return n;if(s||r===n)return r;_pe.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',r,n)}});var sNr=T(aRe=>{"use strict";Object.defineProperty(aRe,"__esModule",{value:!0});aRe.detectResources=void 0;var oNr=(Zt(),vt(ur)),Dyt=Iyt(),fao=(t={})=>(t.detectors||[]).map(r=>{try{let n=(0,Dyt.resourceFromDetectedResource)(r.detect(t));return oNr.diag.debug(`${r.constructor.name} found resource.`,n),n}catch(n){return oNr.diag.debug(`${r.constructor.name} failed: ${n.message}`),(0,Dyt.emptyResource)()}}).reduce((r,n)=>r.merge(n),(0,Dyt.emptyResource)());aRe.detectResources=fao});var cNr=T(cRe=>{"use strict";Object.defineProperty(cRe,"__esModule",{value:!0});cRe.envDetector=void 0;var pao=(Zt(),vt(ur)),hao=(jh(),vt(gA)),aNr=Syt(),Ryt=class{_MAX_LENGTH=255;_COMMA_SEPARATOR=",";_LABEL_KEY_VALUE_SPLITTER="=";_ERROR_MESSAGE_INVALID_CHARS="should be a ASCII string with a length greater than 0 and not exceed "+this._MAX_LENGTH+" characters.";_ERROR_MESSAGE_INVALID_VALUE="should be a ASCII string with a length not exceed "+this._MAX_LENGTH+" characters.";detect(e){let r={},n=(0,aNr.getStringFromEnv)("OTEL_RESOURCE_ATTRIBUTES"),o=(0,aNr.getStringFromEnv)("OTEL_SERVICE_NAME");if(n)try{let s=this._parseResourceAttributes(n);Object.assign(r,s)}catch(s){pao.diag.debug(`EnvDetector failed: ${s.message}`)}return o&&(r[hao.ATTR_SERVICE_NAME]=o),{attributes:r}}_parseResourceAttributes(e){if(!e)return{};let r={},n=e.split(this._COMMA_SEPARATOR,-1);for(let o of n){let s=o.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(s.length!==2)continue;let[a,c]=s;if(a=a.trim(),c=c.trim().split(/^"|"$/).join(""),!this._isValidAndNotEmpty(a))throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(c))throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);r[a]=decodeURIComponent(c)}return r}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<33||n===44||n===59||n===92||n>126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}};cRe.envDetector=new Ryt});var Epe=T(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.ATTR_WEBENGINE_VERSION=Fn.ATTR_WEBENGINE_NAME=Fn.ATTR_WEBENGINE_DESCRIPTION=Fn.ATTR_SERVICE_NAMESPACE=Fn.ATTR_SERVICE_INSTANCE_ID=Fn.ATTR_PROCESS_RUNTIME_VERSION=Fn.ATTR_PROCESS_RUNTIME_NAME=Fn.ATTR_PROCESS_RUNTIME_DESCRIPTION=Fn.ATTR_PROCESS_PID=Fn.ATTR_PROCESS_OWNER=Fn.ATTR_PROCESS_EXECUTABLE_PATH=Fn.ATTR_PROCESS_EXECUTABLE_NAME=Fn.ATTR_PROCESS_COMMAND_ARGS=Fn.ATTR_PROCESS_COMMAND=Fn.ATTR_OS_VERSION=Fn.ATTR_OS_TYPE=Fn.ATTR_K8S_POD_NAME=Fn.ATTR_K8S_NAMESPACE_NAME=Fn.ATTR_K8S_DEPLOYMENT_NAME=Fn.ATTR_K8S_CLUSTER_NAME=Fn.ATTR_HOST_TYPE=Fn.ATTR_HOST_NAME=Fn.ATTR_HOST_IMAGE_VERSION=Fn.ATTR_HOST_IMAGE_NAME=Fn.ATTR_HOST_IMAGE_ID=Fn.ATTR_HOST_ID=Fn.ATTR_HOST_ARCH=Fn.ATTR_CONTAINER_NAME=Fn.ATTR_CONTAINER_IMAGE_TAGS=Fn.ATTR_CONTAINER_IMAGE_NAME=Fn.ATTR_CONTAINER_ID=Fn.ATTR_CLOUD_REGION=Fn.ATTR_CLOUD_PROVIDER=Fn.ATTR_CLOUD_AVAILABILITY_ZONE=Fn.ATTR_CLOUD_ACCOUNT_ID=void 0;Fn.ATTR_CLOUD_ACCOUNT_ID="cloud.account.id";Fn.ATTR_CLOUD_AVAILABILITY_ZONE="cloud.availability_zone";Fn.ATTR_CLOUD_PROVIDER="cloud.provider";Fn.ATTR_CLOUD_REGION="cloud.region";Fn.ATTR_CONTAINER_ID="container.id";Fn.ATTR_CONTAINER_IMAGE_NAME="container.image.name";Fn.ATTR_CONTAINER_IMAGE_TAGS="container.image.tags";Fn.ATTR_CONTAINER_NAME="container.name";Fn.ATTR_HOST_ARCH="host.arch";Fn.ATTR_HOST_ID="host.id";Fn.ATTR_HOST_IMAGE_ID="host.image.id";Fn.ATTR_HOST_IMAGE_NAME="host.image.name";Fn.ATTR_HOST_IMAGE_VERSION="host.image.version";Fn.ATTR_HOST_NAME="host.name";Fn.ATTR_HOST_TYPE="host.type";Fn.ATTR_K8S_CLUSTER_NAME="k8s.cluster.name";Fn.ATTR_K8S_DEPLOYMENT_NAME="k8s.deployment.name";Fn.ATTR_K8S_NAMESPACE_NAME="k8s.namespace.name";Fn.ATTR_K8S_POD_NAME="k8s.pod.name";Fn.ATTR_OS_TYPE="os.type";Fn.ATTR_OS_VERSION="os.version";Fn.ATTR_PROCESS_COMMAND="process.command";Fn.ATTR_PROCESS_COMMAND_ARGS="process.command_args";Fn.ATTR_PROCESS_EXECUTABLE_NAME="process.executable.name";Fn.ATTR_PROCESS_EXECUTABLE_PATH="process.executable.path";Fn.ATTR_PROCESS_OWNER="process.owner";Fn.ATTR_PROCESS_PID="process.pid";Fn.ATTR_PROCESS_RUNTIME_DESCRIPTION="process.runtime.description";Fn.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name";Fn.ATTR_PROCESS_RUNTIME_VERSION="process.runtime.version";Fn.ATTR_SERVICE_INSTANCE_ID="service.instance.id";Fn.ATTR_SERVICE_NAMESPACE="service.namespace";Fn.ATTR_WEBENGINE_DESCRIPTION="webengine.description";Fn.ATTR_WEBENGINE_NAME="webengine.name";Fn.ATTR_WEBENGINE_VERSION="webengine.version"});var uRe=T(lRe=>{"use strict";Object.defineProperty(lRe,"__esModule",{value:!0});lRe.execAsync=void 0;var mao=ve("child_process"),gao=ve("util");lRe.execAsync=gao.promisify(mao.exec)});var lNr=T(dRe=>{"use strict";Object.defineProperty(dRe,"__esModule",{value:!0});dRe.getMachineId=void 0;var Aao=uRe(),yao=(Zt(),vt(ur));async function _ao(){try{let e=(await(0,Aao.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split(`
|
|
484
|
-
`).find(n=>n.includes("IOPlatformUUID"));if(!e)return;let r=e.split('" = "');if(r.length===2)return r[1].slice(0,-1)}catch(t){yao.diag.debug(`error reading machine id: ${t}`)}}dRe.getMachineId=_ao});var uNr=T(fRe=>{"use strict";Object.defineProperty(fRe,"__esModule",{value:!0});fRe.getMachineId=void 0;var Eao=ve("fs"),vao=(Zt(),vt(ur));async function bao(){let t=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let e of t)try{return(await Eao.promises.readFile(e,{encoding:"utf8"})).trim()}catch(r){vao.diag.debug(`error reading machine id: ${r}`)}}fRe.getMachineId=bao});var fNr=T(pRe=>{"use strict";Object.defineProperty(pRe,"__esModule",{value:!0});pRe.getMachineId=void 0;var Cao=ve("fs"),Sao=uRe(),dNr=(Zt(),vt(ur));async function xao(){try{return(await Cao.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(t){dNr.diag.debug(`error reading machine id: ${t}`)}try{return(await(0,Sao.execAsync)("kenv -q smbios.system.uuid")).stdout.trim()}catch(t){dNr.diag.debug(`error reading machine id: ${t}`)}}pRe.getMachineId=xao});var hNr=T(hRe=>{"use strict";Object.defineProperty(hRe,"__esModule",{value:!0});hRe.getMachineId=void 0;var pNr=ve("process"),wao=uRe(),Tao=(Zt(),vt(ur));async function Iao(){let t="QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",e="%windir%\\System32\\REG.exe";pNr.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in pNr.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{let n=(await(0,wao.execAsync)(`${e} ${t}`)).stdout.split("REG_SZ");if(n.length===2)return n[1].trim()}catch(r){Tao.diag.debug(`error reading machine id: ${r}`)}}hRe.getMachineId=Iao});var mNr=T(mRe=>{"use strict";Object.defineProperty(mRe,"__esModule",{value:!0});mRe.getMachineId=void 0;var Dao=(Zt(),vt(ur));async function Rao(){Dao.diag.debug("could not read machine-id: unsupported platform")}mRe.getMachineId=Rao});var gNr=T(gRe=>{"use strict";Object.defineProperty(gRe,"__esModule",{value:!0});gRe.getMachineId=void 0;var Nao=ve("process"),nU;async function Oao(){if(!nU)switch(Nao.platform){case"darwin":nU=(await Promise.resolve().then(()=>Ie(lNr()))).getMachineId;break;case"linux":nU=(await Promise.resolve().then(()=>Ie(uNr()))).getMachineId;break;case"freebsd":nU=(await Promise.resolve().then(()=>Ie(fNr()))).getMachineId;break;case"win32":nU=(await Promise.resolve().then(()=>Ie(hNr()))).getMachineId;break;default:nU=(await Promise.resolve().then(()=>Ie(mNr()))).getMachineId;break}return nU()}gRe.getMachineId=Oao});var Nyt=T(ZK=>{"use strict";Object.defineProperty(ZK,"__esModule",{value:!0});ZK.normalizeType=ZK.normalizeArch=void 0;var kao=t=>{switch(t){case"arm":return"arm32";case"ppc":return"ppc32";case"x64":return"amd64";default:return t}};ZK.normalizeArch=kao;var Bao=t=>{switch(t){case"sunos":return"solaris";case"win32":return"windows";default:return t}};ZK.normalizeType=Bao});var yNr=T(ARe=>{"use strict";Object.defineProperty(ARe,"__esModule",{value:!0});ARe.hostDetector=void 0;var Oyt=Epe(),ANr=ve("os"),Pao=gNr(),Mao=Nyt(),kyt=class{detect(e){return{attributes:{[Oyt.ATTR_HOST_NAME]:(0,ANr.hostname)(),[Oyt.ATTR_HOST_ARCH]:(0,Mao.normalizeArch)((0,ANr.arch)()),[Oyt.ATTR_HOST_ID]:(0,Pao.getMachineId)()}}}};ARe.hostDetector=new kyt});var vNr=T(yRe=>{"use strict";Object.defineProperty(yRe,"__esModule",{value:!0});yRe.osDetector=void 0;var _Nr=Epe(),ENr=ve("os"),Fao=Nyt(),Byt=class{detect(e){return{attributes:{[_Nr.ATTR_OS_TYPE]:(0,Fao.normalizeType)((0,ENr.platform)()),[_Nr.ATTR_OS_VERSION]:(0,ENr.release)()}}}};yRe.osDetector=new Byt});var bNr=T(_Re=>{"use strict";Object.defineProperty(_Re,"__esModule",{value:!0});_Re.processDetector=void 0;var Lao=(Zt(),vt(ur)),L9=Epe(),Uao=ve("os"),Pyt=class{detect(e){let r={[L9.ATTR_PROCESS_PID]:process.pid,[L9.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[L9.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[L9.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[L9.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[L9.ATTR_PROCESS_RUNTIME_NAME]:"nodejs",[L9.ATTR_PROCESS_RUNTIME_DESCRIPTION]:"Node.js"};process.argv.length>1&&(r[L9.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let n=Uao.userInfo();r[L9.ATTR_PROCESS_OWNER]=n.username}catch(n){Lao.diag.debug(`error obtaining process owner: ${n}`)}return{attributes:r}}};_Re.processDetector=new Pyt});var CNr=T(ERe=>{"use strict";Object.defineProperty(ERe,"__esModule",{value:!0});ERe.serviceInstanceIdDetector=void 0;var Qao=Epe(),jao=ve("crypto"),Myt=class{detect(e){return{attributes:{[Qao.ATTR_SERVICE_INSTANCE_ID]:(0,jao.randomUUID)()}}}};ERe.serviceInstanceIdDetector=new Myt});var SNr=T(Px=>{"use strict";Object.defineProperty(Px,"__esModule",{value:!0});Px.serviceInstanceIdDetector=Px.processDetector=Px.osDetector=Px.hostDetector=void 0;var Gao=yNr();Object.defineProperty(Px,"hostDetector",{enumerable:!0,get:function(){return Gao.hostDetector}});var $ao=vNr();Object.defineProperty(Px,"osDetector",{enumerable:!0,get:function(){return $ao.osDetector}});var qao=bNr();Object.defineProperty(Px,"processDetector",{enumerable:!0,get:function(){return qao.processDetector}});var Hao=CNr();Object.defineProperty(Px,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return Hao.serviceInstanceIdDetector}})});var xNr=T(Mx=>{"use strict";Object.defineProperty(Mx,"__esModule",{value:!0});Mx.serviceInstanceIdDetector=Mx.processDetector=Mx.osDetector=Mx.hostDetector=void 0;var vRe=SNr();Object.defineProperty(Mx,"hostDetector",{enumerable:!0,get:function(){return vRe.hostDetector}});Object.defineProperty(Mx,"osDetector",{enumerable:!0,get:function(){return vRe.osDetector}});Object.defineProperty(Mx,"processDetector",{enumerable:!0,get:function(){return vRe.processDetector}});Object.defineProperty(Mx,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return vRe.serviceInstanceIdDetector}})});var wNr=T(eX=>{"use strict";Object.defineProperty(eX,"__esModule",{value:!0});eX.noopDetector=eX.NoopDetector=void 0;var bRe=class{detect(){return{attributes:{}}}};eX.NoopDetector=bRe;eX.noopDetector=new bRe});var TNr=T(N3=>{"use strict";Object.defineProperty(N3,"__esModule",{value:!0});N3.noopDetector=N3.serviceInstanceIdDetector=N3.processDetector=N3.osDetector=N3.hostDetector=N3.envDetector=void 0;var Vao=cNr();Object.defineProperty(N3,"envDetector",{enumerable:!0,get:function(){return Vao.envDetector}});var CRe=xNr();Object.defineProperty(N3,"hostDetector",{enumerable:!0,get:function(){return CRe.hostDetector}});Object.defineProperty(N3,"osDetector",{enumerable:!0,get:function(){return CRe.osDetector}});Object.defineProperty(N3,"processDetector",{enumerable:!0,get:function(){return CRe.processDetector}});Object.defineProperty(N3,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return CRe.serviceInstanceIdDetector}});var Wao=wNr();Object.defineProperty(N3,"noopDetector",{enumerable:!0,get:function(){return Wao.noopDetector}})});var Lyt=T(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});Ff.defaultServiceName=Ff.emptyResource=Ff.defaultResource=Ff.resourceFromAttributes=Ff.serviceInstanceIdDetector=Ff.processDetector=Ff.osDetector=Ff.hostDetector=Ff.envDetector=Ff.detectResources=void 0;var zao=sNr();Object.defineProperty(Ff,"detectResources",{enumerable:!0,get:function(){return zao.detectResources}});var vpe=TNr();Object.defineProperty(Ff,"envDetector",{enumerable:!0,get:function(){return vpe.envDetector}});Object.defineProperty(Ff,"hostDetector",{enumerable:!0,get:function(){return vpe.hostDetector}});Object.defineProperty(Ff,"osDetector",{enumerable:!0,get:function(){return vpe.osDetector}});Object.defineProperty(Ff,"processDetector",{enumerable:!0,get:function(){return vpe.processDetector}});Object.defineProperty(Ff,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return vpe.serviceInstanceIdDetector}});var Fyt=Iyt();Object.defineProperty(Ff,"resourceFromAttributes",{enumerable:!0,get:function(){return Fyt.resourceFromAttributes}});Object.defineProperty(Ff,"defaultResource",{enumerable:!0,get:function(){return Fyt.defaultResource}});Object.defineProperty(Ff,"emptyResource",{enumerable:!0,get:function(){return Fyt.emptyResource}});var Yao=xyt();Object.defineProperty(Ff,"defaultServiceName",{enumerable:!0,get:function(){return Yao.defaultServiceName}})});var INr=T(bpe=>{"use strict";Object.defineProperty(bpe,"__esModule",{value:!0});bpe.SeverityNumber=void 0;var Kao;(function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.TRACE=1]="TRACE",t[t.TRACE2=2]="TRACE2",t[t.TRACE3=3]="TRACE3",t[t.TRACE4=4]="TRACE4",t[t.DEBUG=5]="DEBUG",t[t.DEBUG2=6]="DEBUG2",t[t.DEBUG3=7]="DEBUG3",t[t.DEBUG4=8]="DEBUG4",t[t.INFO=9]="INFO",t[t.INFO2=10]="INFO2",t[t.INFO3=11]="INFO3",t[t.INFO4=12]="INFO4",t[t.WARN=13]="WARN",t[t.WARN2=14]="WARN2",t[t.WARN3=15]="WARN3",t[t.WARN4=16]="WARN4",t[t.ERROR=17]="ERROR",t[t.ERROR2=18]="ERROR2",t[t.ERROR3=19]="ERROR3",t[t.ERROR4=20]="ERROR4",t[t.FATAL=21]="FATAL",t[t.FATAL2=22]="FATAL2",t[t.FATAL3=23]="FATAL3",t[t.FATAL4=24]="FATAL4"})(Kao=bpe.SeverityNumber||(bpe.SeverityNumber={}))});var xRe=T(tX=>{"use strict";Object.defineProperty(tX,"__esModule",{value:!0});tX.NOOP_LOGGER=tX.NoopLogger=void 0;var SRe=class{emit(e){}};tX.NoopLogger=SRe;tX.NOOP_LOGGER=new SRe});var TRe=T(rX=>{"use strict";Object.defineProperty(rX,"__esModule",{value:!0});rX.NOOP_LOGGER_PROVIDER=rX.NoopLoggerProvider=void 0;var Xao=xRe(),wRe=class{getLogger(e,r,n){return new Xao.NoopLogger}};rX.NoopLoggerProvider=wRe;rX.NOOP_LOGGER_PROVIDER=new wRe});var Qyt=T(IRe=>{"use strict";Object.defineProperty(IRe,"__esModule",{value:!0});IRe.ProxyLogger=void 0;var Jao=xRe(),Uyt=class{constructor(e,r,n,o){this._provider=e,this.name=r,this.version=n,this.options=o}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;let e=this._provider._getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Jao.NOOP_LOGGER}};IRe.ProxyLogger=Uyt});var Gyt=T(DRe=>{"use strict";Object.defineProperty(DRe,"__esModule",{value:!0});DRe.ProxyLoggerProvider=void 0;var Zao=TRe(),eco=Qyt(),jyt=class{getLogger(e,r,n){var o;return(o=this._getDelegateLogger(e,r,n))!==null&&o!==void 0?o:new eco.ProxyLogger(this,e,r,n)}_getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Zao.NOOP_LOGGER_PROVIDER}_setDelegate(e){this._delegate=e}_getDelegateLogger(e,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getLogger(e,r,n)}};DRe.ProxyLoggerProvider=jyt});var DNr=T(RRe=>{"use strict";Object.defineProperty(RRe,"__esModule",{value:!0});RRe._globalThis=void 0;RRe._globalThis=typeof globalThis=="object"?globalThis:global});var RNr=T(NRe=>{"use strict";Object.defineProperty(NRe,"__esModule",{value:!0});NRe._globalThis=void 0;var tco=DNr();Object.defineProperty(NRe,"_globalThis",{enumerable:!0,get:function(){return tco._globalThis}})});var NNr=T(ORe=>{"use strict";Object.defineProperty(ORe,"__esModule",{value:!0});ORe._globalThis=void 0;var rco=RNr();Object.defineProperty(ORe,"_globalThis",{enumerable:!0,get:function(){return rco._globalThis}})});var ONr=T(Fx=>{"use strict";Object.defineProperty(Fx,"__esModule",{value:!0});Fx.API_BACKWARDS_COMPATIBILITY_VERSION=Fx.makeGetter=Fx._global=Fx.GLOBAL_LOGS_API_KEY=void 0;var nco=NNr();Fx.GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs");Fx._global=nco._globalThis;function ico(t,e,r){return n=>n===t?e:r}Fx.makeGetter=ico;Fx.API_BACKWARDS_COMPATIBILITY_VERSION=1});var BNr=T(kRe=>{"use strict";Object.defineProperty(kRe,"__esModule",{value:!0});kRe.LogsAPI=void 0;var nv=ONr(),oco=TRe(),kNr=Gyt(),$yt=class t{constructor(){this._proxyLoggerProvider=new kNr.ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalLoggerProvider(e){return nv._global[nv.GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(nv._global[nv.GLOBAL_LOGS_API_KEY]=(0,nv.makeGetter)(nv.API_BACKWARDS_COMPATIBILITY_VERSION,e,oco.NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider._setDelegate(e),e)}getLoggerProvider(){var e,r;return(r=(e=nv._global[nv.GLOBAL_LOGS_API_KEY])===null||e===void 0?void 0:e.call(nv._global,nv.API_BACKWARDS_COMPATIBILITY_VERSION))!==null&&r!==void 0?r:this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){delete nv._global[nv.GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new kNr.ProxyLoggerProvider}};kRe.LogsAPI=$yt});var FNr=T(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});zm.logs=zm.ProxyLoggerProvider=zm.ProxyLogger=zm.NoopLoggerProvider=zm.NOOP_LOGGER_PROVIDER=zm.NoopLogger=zm.NOOP_LOGGER=zm.SeverityNumber=void 0;var sco=INr();Object.defineProperty(zm,"SeverityNumber",{enumerable:!0,get:function(){return sco.SeverityNumber}});var PNr=xRe();Object.defineProperty(zm,"NOOP_LOGGER",{enumerable:!0,get:function(){return PNr.NOOP_LOGGER}});Object.defineProperty(zm,"NoopLogger",{enumerable:!0,get:function(){return PNr.NoopLogger}});var MNr=TRe();Object.defineProperty(zm,"NOOP_LOGGER_PROVIDER",{enumerable:!0,get:function(){return MNr.NOOP_LOGGER_PROVIDER}});Object.defineProperty(zm,"NoopLoggerProvider",{enumerable:!0,get:function(){return MNr.NoopLoggerProvider}});var aco=Qyt();Object.defineProperty(zm,"ProxyLogger",{enumerable:!0,get:function(){return aco.ProxyLogger}});var cco=Gyt();Object.defineProperty(zm,"ProxyLoggerProvider",{enumerable:!0,get:function(){return cco.ProxyLoggerProvider}});var lco=BNr();zm.logs=lco.LogsAPI.getInstance()});var Cpe=T(MN=>{"use strict";Object.defineProperty(MN,"__esModule",{value:!0});MN.isTracingSuppressed=MN.unsuppressTracing=MN.suppressTracing=void 0;var uco=(Zt(),vt(ur)),qyt=(0,uco.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function dco(t){return t.setValue(qyt,!0)}MN.suppressTracing=dco;function fco(t){return t.deleteValue(qyt)}MN.unsuppressTracing=fco;function pco(t){return t.getValue(qyt)===!0}MN.isTracingSuppressed=pco});var Hyt=T(xA=>{"use strict";Object.defineProperty(xA,"__esModule",{value:!0});xA.BAGGAGE_MAX_TOTAL_LENGTH=xA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=xA.BAGGAGE_MAX_NAME_VALUE_PAIRS=xA.BAGGAGE_HEADER=xA.BAGGAGE_ITEMS_SEPARATOR=xA.BAGGAGE_PROPERTIES_SEPARATOR=xA.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;xA.BAGGAGE_KEY_PAIR_SEPARATOR="=";xA.BAGGAGE_PROPERTIES_SEPARATOR=";";xA.BAGGAGE_ITEMS_SEPARATOR=",";xA.BAGGAGE_HEADER="baggage";xA.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;xA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;xA.BAGGAGE_MAX_TOTAL_LENGTH=8192});var Vyt=T(Lx=>{"use strict";Object.defineProperty(Lx,"__esModule",{value:!0});Lx.parseKeyPairsIntoRecord=Lx.parsePairKeyValue=Lx.getKeyPairs=Lx.serializeKeyPairs=void 0;var hco=(Zt(),vt(ur)),iU=Hyt();function mco(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?iU.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>iU.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}Lx.serializeKeyPairs=mco;function gco(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=iU.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}Lx.getKeyPairs=gco;function LNr(t){let e=t.split(iU.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(iU.BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;let o=decodeURIComponent(r.substring(0,n).trim()),s=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=(0,hco.baggageEntryMetadataFromString)(e.join(iU.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:a}}Lx.parsePairKeyValue=LNr;function Aco(t){let e={};return typeof t=="string"&&t.length>0&&t.split(iU.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=LNr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}Lx.parseKeyPairsIntoRecord=Aco});var UNr=T(BRe=>{"use strict";Object.defineProperty(BRe,"__esModule",{value:!0});BRe.W3CBaggagePropagator=void 0;var Wyt=(Zt(),vt(ur)),yco=Cpe(),oU=Hyt(),zyt=Vyt(),Yyt=class{inject(e,r,n){let o=Wyt.propagation.getBaggage(e);if(!o||(0,yco.isTracingSuppressed)(e))return;let s=(0,zyt.getKeyPairs)(o).filter(c=>c.length<=oU.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,oU.BAGGAGE_MAX_NAME_VALUE_PAIRS),a=(0,zyt.serializeKeyPairs)(s);a.length>0&&n.set(r,oU.BAGGAGE_HEADER,a)}extract(e,r,n){let o=n.get(r,oU.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(oU.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let a={};return s.length===0||(s.split(oU.BAGGAGE_ITEMS_SEPARATOR).forEach(u=>{let d=(0,zyt.parsePairKeyValue)(u);if(d){let f={value:d.value};d.metadata&&(f.metadata=d.metadata),a[d.key]=f}}),Object.entries(a).length===0)?e:Wyt.propagation.setBaggage(e,Wyt.propagation.createBaggage(a))}fields(){return[oU.BAGGAGE_HEADER]}};BRe.W3CBaggagePropagator=Yyt});var QNr=T(PRe=>{"use strict";Object.defineProperty(PRe,"__esModule",{value:!0});PRe.AnchoredClock=void 0;var Kyt=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,r){this._monotonicClock=r,this._epochMillis=e.now(),this._performanceMillis=r.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}};PRe.AnchoredClock=Kyt});var HNr=T(FN=>{"use strict";Object.defineProperty(FN,"__esModule",{value:!0});FN.isAttributeValue=FN.isAttributeKey=FN.sanitizeAttributes=void 0;var jNr=(Zt(),vt(ur));function _co(t){let e={};if(typeof t!="object"||t==null)return e;for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;if(!GNr(r)){jNr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!$Nr(n)){jNr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}FN.sanitizeAttributes=_co;function GNr(t){return typeof t=="string"&&t!==""}FN.isAttributeKey=GNr;function $Nr(t){return t==null?!0:Array.isArray(t)?Eco(t):qNr(typeof t)}FN.isAttributeValue=$Nr;function Eco(t){let e;for(let r of t){if(r==null)continue;let n=typeof r;if(n!==e){if(!e){if(qNr(n)){e=n;continue}return!1}return!1}}return!0}function qNr(t){switch(t){case"number":case"boolean":case"string":return!0}return!1}});var Xyt=T(MRe=>{"use strict";Object.defineProperty(MRe,"__esModule",{value:!0});MRe.loggingErrorHandler=void 0;var vco=(Zt(),vt(ur));function bco(){return t=>{vco.diag.error(Cco(t))}}MRe.loggingErrorHandler=bco;function Cco(t){return typeof t=="string"?t:JSON.stringify(Sco(t))}function Sco(t){let e={},r=t;for(;r!==null;)Object.getOwnPropertyNames(r).forEach(n=>{if(e[n])return;let o=r[n];o&&(e[n]=String(o))}),r=Object.getPrototypeOf(r);return e}});var WNr=T(nX=>{"use strict";Object.defineProperty(nX,"__esModule",{value:!0});nX.globalErrorHandler=nX.setGlobalErrorHandler=void 0;var xco=Xyt(),VNr=(0,xco.loggingErrorHandler)();function wco(t){VNr=t}nX.setGlobalErrorHandler=wco;function Tco(t){try{VNr(t)}catch{}}nX.globalErrorHandler=Tco});var XNr=T(Ux=>{"use strict";Object.defineProperty(Ux,"__esModule",{value:!0});Ux.getStringListFromEnv=Ux.getBooleanFromEnv=Ux.getStringFromEnv=Ux.getNumberFromEnv=void 0;var zNr=(Zt(),vt(ur)),YNr=ve("util");function Ico(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){zNr.diag.warn(`Unknown value ${(0,YNr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}Ux.getNumberFromEnv=Ico;function KNr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}Ux.getStringFromEnv=KNr;function Dco(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||zNr.diag.warn(`Unknown value ${(0,YNr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}Ux.getBooleanFromEnv=Dco;function Rco(t){return KNr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}Ux.getStringListFromEnv=Rco});var JNr=T(FRe=>{"use strict";Object.defineProperty(FRe,"__esModule",{value:!0});FRe._globalThis=void 0;FRe._globalThis=typeof globalThis=="object"?globalThis:global});var ZNr=T(LRe=>{"use strict";Object.defineProperty(LRe,"__esModule",{value:!0});LRe.otperformance=void 0;var Nco=ve("perf_hooks");LRe.otperformance=Nco.performance});var eOr=T(URe=>{"use strict";Object.defineProperty(URe,"__esModule",{value:!0});URe.VERSION=void 0;URe.VERSION="2.2.0"});var tOr=T(QRe=>{"use strict";Object.defineProperty(QRe,"__esModule",{value:!0});QRe.ATTR_PROCESS_RUNTIME_NAME=void 0;QRe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var rOr=T(GRe=>{"use strict";Object.defineProperty(GRe,"__esModule",{value:!0});GRe.SDK_INFO=void 0;var Oco=eOr(),jRe=(jh(),vt(gA)),kco=tOr();GRe.SDK_INFO={[jRe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[kco.ATTR_PROCESS_RUNTIME_NAME]:"node",[jRe.ATTR_TELEMETRY_SDK_LANGUAGE]:jRe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[jRe.ATTR_TELEMETRY_SDK_VERSION]:Oco.VERSION}});var nOr=T(wA=>{"use strict";Object.defineProperty(wA,"__esModule",{value:!0});wA.SDK_INFO=wA.otperformance=wA._globalThis=wA.getStringListFromEnv=wA.getNumberFromEnv=wA.getBooleanFromEnv=wA.getStringFromEnv=void 0;var $Re=XNr();Object.defineProperty(wA,"getStringFromEnv",{enumerable:!0,get:function(){return $Re.getStringFromEnv}});Object.defineProperty(wA,"getBooleanFromEnv",{enumerable:!0,get:function(){return $Re.getBooleanFromEnv}});Object.defineProperty(wA,"getNumberFromEnv",{enumerable:!0,get:function(){return $Re.getNumberFromEnv}});Object.defineProperty(wA,"getStringListFromEnv",{enumerable:!0,get:function(){return $Re.getStringListFromEnv}});var Bco=JNr();Object.defineProperty(wA,"_globalThis",{enumerable:!0,get:function(){return Bco._globalThis}});var Pco=ZNr();Object.defineProperty(wA,"otperformance",{enumerable:!0,get:function(){return Pco.otperformance}});var Mco=rOr();Object.defineProperty(wA,"SDK_INFO",{enumerable:!0,get:function(){return Mco.SDK_INFO}})});var Jyt=T(TA=>{"use strict";Object.defineProperty(TA,"__esModule",{value:!0});TA.getStringListFromEnv=TA.getNumberFromEnv=TA.getStringFromEnv=TA.getBooleanFromEnv=TA.otperformance=TA._globalThis=TA.SDK_INFO=void 0;var sU=nOr();Object.defineProperty(TA,"SDK_INFO",{enumerable:!0,get:function(){return sU.SDK_INFO}});Object.defineProperty(TA,"_globalThis",{enumerable:!0,get:function(){return sU._globalThis}});Object.defineProperty(TA,"otperformance",{enumerable:!0,get:function(){return sU.otperformance}});Object.defineProperty(TA,"getBooleanFromEnv",{enumerable:!0,get:function(){return sU.getBooleanFromEnv}});Object.defineProperty(TA,"getStringFromEnv",{enumerable:!0,get:function(){return sU.getStringFromEnv}});Object.defineProperty(TA,"getNumberFromEnv",{enumerable:!0,get:function(){return sU.getNumberFromEnv}});Object.defineProperty(TA,"getStringListFromEnv",{enumerable:!0,get:function(){return sU.getStringListFromEnv}})});var aOr=T(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.addHrTimes=Su.isTimeInput=Su.isTimeInputHrTime=Su.hrTimeToMicroseconds=Su.hrTimeToMilliseconds=Su.hrTimeToNanoseconds=Su.hrTimeToTimeStamp=Su.hrTimeDuration=Su.timeInputToHrTime=Su.hrTime=Su.getTimeOrigin=Su.millisToHrTime=void 0;var Zyt=Jyt(),iOr=9,Fco=6,Lco=Math.pow(10,Fco),qRe=Math.pow(10,iOr);function Spe(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Lco);return[r,n]}Su.millisToHrTime=Spe;function e_t(){let t=Zyt.otperformance.timeOrigin;if(typeof t!="number"){let e=Zyt.otperformance;t=e.timing&&e.timing.fetchStart}return t}Su.getTimeOrigin=e_t;function oOr(t){let e=Spe(e_t()),r=Spe(typeof t=="number"?t:Zyt.otperformance.now());return sOr(e,r)}Su.hrTime=oOr;function Uco(t){if(t_t(t))return t;if(typeof t=="number")return t<e_t()?oOr(t):Spe(t);if(t instanceof Date)return Spe(t.getTime());throw TypeError("Invalid input type")}Su.timeInputToHrTime=Uco;function Qco(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=qRe),[r,n]}Su.hrTimeDuration=Qco;function jco(t){let e=iOr,r=`${"0".repeat(e)}${t[1]}Z`,n=r.substring(r.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",n)}Su.hrTimeToTimeStamp=jco;function Gco(t){return t[0]*qRe+t[1]}Su.hrTimeToNanoseconds=Gco;function $co(t){return t[0]*1e3+t[1]/1e6}Su.hrTimeToMilliseconds=$co;function qco(t){return t[0]*1e6+t[1]/1e3}Su.hrTimeToMicroseconds=qco;function t_t(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}Su.isTimeInputHrTime=t_t;function Hco(t){return t_t(t)||typeof t=="number"||t instanceof Date}Su.isTimeInput=Hco;function sOr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=qRe&&(r[1]-=qRe,r[0]+=1),r}Su.addHrTimes=sOr});var cOr=T(HRe=>{"use strict";Object.defineProperty(HRe,"__esModule",{value:!0});HRe.unrefTimer=void 0;function Vco(t){typeof t!="number"&&t.unref()}HRe.unrefTimer=Vco});var lOr=T(xpe=>{"use strict";Object.defineProperty(xpe,"__esModule",{value:!0});xpe.ExportResultCode=void 0;var Wco;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Wco=xpe.ExportResultCode||(xpe.ExportResultCode={}))});var dOr=T(VRe=>{"use strict";Object.defineProperty(VRe,"__esModule",{value:!0});VRe.CompositePropagator=void 0;var uOr=(Zt(),vt(ur)),r_t=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(r=>typeof r.fields=="function"?r.fields():[]).reduce((r,n)=>r.concat(n),[])))}inject(e,r,n){for(let o of this._propagators)try{o.inject(e,r,n)}catch(s){uOr.diag.warn(`Failed to inject with ${o.constructor.name}. Err: ${s.message}`)}}extract(e,r,n){return this._propagators.reduce((o,s)=>{try{return s.extract(o,r,n)}catch(a){uOr.diag.warn(`Failed to extract with ${s.constructor.name}. Err: ${a.message}`)}return o},e)}fields(){return this._fields.slice()}};VRe.CompositePropagator=r_t});var fOr=T(iX=>{"use strict";Object.defineProperty(iX,"__esModule",{value:!0});iX.validateValue=iX.validateKey=void 0;var n_t="[_0-9a-z-*/]",zco=`[a-z]${n_t}{0,255}`,Yco=`[a-z0-9]${n_t}{0,240}@[a-z]${n_t}{0,13}`,Kco=new RegExp(`^(?:${zco}|${Yco})$`),Xco=/^[ -~]{0,255}[!-~]$/,Jco=/,|=/;function Zco(t){return Kco.test(t)}iX.validateKey=Zco;function elo(t){return Xco.test(t)&&!Jco.test(t)}iX.validateValue=elo});var o_t=T(WRe=>{"use strict";Object.defineProperty(WRe,"__esModule",{value:!0});WRe.TraceState=void 0;var pOr=fOr(),hOr=32,tlo=512,mOr=",",gOr="=",i_t=class t{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,r)=>(e.push(r+gOr+this.get(r)),e),[]).join(mOr)}_parse(e){e.length>tlo||(this._internalState=e.split(mOr).reverse().reduce((r,n)=>{let o=n.trim(),s=o.indexOf(gOr);if(s!==-1){let a=o.slice(0,s),c=o.slice(s+1,n.length);(0,pOr.validateKey)(a)&&(0,pOr.validateValue)(c)&&r.set(a,c)}return r},new Map),this._internalState.size>hOr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,hOr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};WRe.TraceState=i_t});var yOr=T(IA=>{"use strict";Object.defineProperty(IA,"__esModule",{value:!0});IA.W3CTraceContextPropagator=IA.parseTraceParent=IA.TRACE_STATE_HEADER=IA.TRACE_PARENT_HEADER=void 0;var zRe=(Zt(),vt(ur)),rlo=Cpe(),nlo=o_t();IA.TRACE_PARENT_HEADER="traceparent";IA.TRACE_STATE_HEADER="tracestate";var ilo="00",olo="(?!ff)[\\da-f]{2}",slo="(?![0]{32})[\\da-f]{32}",alo="(?![0]{16})[\\da-f]{16}",clo="[\\da-f]{2}",llo=new RegExp(`^\\s?(${olo})-(${slo})-(${alo})-(${clo})(-.*)?\\s?$`);function AOr(t){let e=llo.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}IA.parseTraceParent=AOr;var s_t=class{inject(e,r,n){let o=zRe.trace.getSpanContext(e);if(!o||(0,rlo.isTracingSuppressed)(e)||!(0,zRe.isSpanContextValid)(o))return;let s=`${ilo}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||zRe.TraceFlags.NONE).toString(16)}`;n.set(r,IA.TRACE_PARENT_HEADER,s),o.traceState&&n.set(r,IA.TRACE_STATE_HEADER,o.traceState.serialize())}extract(e,r,n){let o=n.get(r,IA.TRACE_PARENT_HEADER);if(!o)return e;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let a=AOr(s);if(!a)return e;a.isRemote=!0;let c=n.get(r,IA.TRACE_STATE_HEADER);if(c){let u=Array.isArray(c)?c.join(","):c;a.traceState=new nlo.TraceState(typeof u=="string"?u:void 0)}return zRe.trace.setSpanContext(e,a)}fields(){return[IA.TRACE_PARENT_HEADER,IA.TRACE_STATE_HEADER]}};IA.W3CTraceContextPropagator=s_t});var _Or=T(gC=>{"use strict";Object.defineProperty(gC,"__esModule",{value:!0});gC.getRPCMetadata=gC.deleteRPCMetadata=gC.setRPCMetadata=gC.RPCType=void 0;var ulo=(Zt(),vt(ur)),a_t=(0,ulo.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),dlo;(function(t){t.HTTP="http"})(dlo=gC.RPCType||(gC.RPCType={}));function flo(t,e){return t.setValue(a_t,e)}gC.setRPCMetadata=flo;function plo(t){return t.deleteValue(a_t)}gC.deleteRPCMetadata=plo;function hlo(t){return t.getValue(a_t)}gC.getRPCMetadata=hlo});var SOr=T(YRe=>{"use strict";Object.defineProperty(YRe,"__esModule",{value:!0});YRe.isPlainObject=void 0;var mlo="[object Object]",glo="[object Null]",Alo="[object Undefined]",ylo=Function.prototype,EOr=ylo.toString,_lo=EOr.call(Object),Elo=Object.getPrototypeOf,vOr=Object.prototype,bOr=vOr.hasOwnProperty,aU=Symbol?Symbol.toStringTag:void 0,COr=vOr.toString;function vlo(t){if(!blo(t)||Clo(t)!==mlo)return!1;let e=Elo(t);if(e===null)return!0;let r=bOr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&EOr.call(r)===_lo}YRe.isPlainObject=vlo;function blo(t){return t!=null&&typeof t=="object"}function Clo(t){return t==null?t===void 0?Alo:glo:aU&&aU in Object(t)?Slo(t):xlo(t)}function Slo(t){let e=bOr.call(t,aU),r=t[aU],n=!1;try{t[aU]=void 0,n=!0}catch{}let o=COr.call(t);return n&&(e?t[aU]=r:delete t[aU]),o}function xlo(t){return COr.call(t)}});var DOr=T(JRe=>{"use strict";Object.defineProperty(JRe,"__esModule",{value:!0});JRe.merge=void 0;var xOr=SOr(),wlo=20;function Tlo(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=TOr(e,t.shift(),0,r);return e}JRe.merge=Tlo;function c_t(t){return XRe(t)?t.slice():t}function TOr(t,e,r=0,n){let o;if(!(r>wlo)){if(r++,KRe(t)||KRe(e)||IOr(e))o=c_t(e);else if(XRe(t)){if(o=t.slice(),XRe(e))for(let s=0,a=e.length;s<a;s++)o.push(c_t(e[s]));else if(wpe(e)){let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a];o[u]=c_t(e[u])}}}else if(wpe(t))if(wpe(e)){if(!Ilo(t,e))return e;o=Object.assign({},t);let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a],d=e[u];if(KRe(d))typeof d>"u"?delete o[u]:o[u]=d;else{let f=o[u],p=d;if(wOr(t,u,n)||wOr(e,u,n))delete o[u];else{if(wpe(f)&&wpe(p)){let h=n.get(f)||[],m=n.get(p)||[];h.push({obj:t,key:u}),m.push({obj:e,key:u}),n.set(f,h),n.set(p,m)}o[u]=TOr(o[u],d,r,n)}}}}else o=e;return o}}function wOr(t,e,r){let n=r.get(t[e])||[];for(let o=0,s=n.length;o<s;o++){let a=n[o];if(a.key===e&&a.obj===t)return!0}return!1}function XRe(t){return Array.isArray(t)}function IOr(t){return typeof t=="function"}function wpe(t){return!KRe(t)&&!XRe(t)&&!IOr(t)&&typeof t=="object"}function KRe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function Ilo(t,e){return!(!(0,xOr.isPlainObject)(t)||!(0,xOr.isPlainObject)(e))}});var ROr=T(oX=>{"use strict";Object.defineProperty(oX,"__esModule",{value:!0});oX.callWithTimeout=oX.TimeoutError=void 0;var ZRe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};oX.TimeoutError=ZRe;function Dlo(t,e){let r,n=new Promise(function(s,a){r=setTimeout(function(){a(new ZRe("Operation timed out."))},e)});return Promise.race([t,n]).then(o=>(clearTimeout(r),o),o=>{throw clearTimeout(r),o})}oX.callWithTimeout=Dlo});var OOr=T(sX=>{"use strict";Object.defineProperty(sX,"__esModule",{value:!0});sX.isUrlIgnored=sX.urlMatches=void 0;function NOr(t,e){return typeof e=="string"?t===e:!!t.match(e)}sX.urlMatches=NOr;function Rlo(t,e){if(!e)return!1;for(let r of e)if(NOr(t,r))return!0;return!1}sX.isUrlIgnored=Rlo});var kOr=T(eNe=>{"use strict";Object.defineProperty(eNe,"__esModule",{value:!0});eNe.Deferred=void 0;var l_t=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,r)=>{this._resolve=e,this._reject=r})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}};eNe.Deferred=l_t});var BOr=T(tNe=>{"use strict";Object.defineProperty(tNe,"__esModule",{value:!0});tNe.BindOnceFuture=void 0;var Nlo=kOr(),u_t=class{_callback;_that;_isCalled=!1;_deferred=new Nlo.Deferred;constructor(e,r){this._callback=e,this._that=r}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(r=>this._deferred.resolve(r),r=>this._deferred.reject(r))}catch(r){this._deferred.reject(r)}}return this._deferred.promise}};tNe.BindOnceFuture=u_t});var MOr=T(rNe=>{"use strict";Object.defineProperty(rNe,"__esModule",{value:!0});rNe.diagLogLevelFromString=void 0;var U9=(Zt(),vt(ur)),POr={ALL:U9.DiagLogLevel.ALL,VERBOSE:U9.DiagLogLevel.VERBOSE,DEBUG:U9.DiagLogLevel.DEBUG,INFO:U9.DiagLogLevel.INFO,WARN:U9.DiagLogLevel.WARN,ERROR:U9.DiagLogLevel.ERROR,NONE:U9.DiagLogLevel.NONE};function Olo(t){if(t==null)return;let e=POr[t.toUpperCase()];return e??(U9.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys(POr)}, using default`),U9.DiagLogLevel.INFO)}rNe.diagLogLevelFromString=Olo});var LOr=T(nNe=>{"use strict";Object.defineProperty(nNe,"__esModule",{value:!0});nNe._export=void 0;var FOr=(Zt(),vt(ur)),klo=Cpe();function Blo(t,e){return new Promise(r=>{FOr.context.with((0,klo.suppressTracing)(FOr.context.active()),()=>{t.export(e,n=>{r(n)})})})}nNe._export=Blo});var Q9=T(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.internal=Gr.diagLogLevelFromString=Gr.BindOnceFuture=Gr.urlMatches=Gr.isUrlIgnored=Gr.callWithTimeout=Gr.TimeoutError=Gr.merge=Gr.TraceState=Gr.unsuppressTracing=Gr.suppressTracing=Gr.isTracingSuppressed=Gr.setRPCMetadata=Gr.getRPCMetadata=Gr.deleteRPCMetadata=Gr.RPCType=Gr.parseTraceParent=Gr.W3CTraceContextPropagator=Gr.TRACE_STATE_HEADER=Gr.TRACE_PARENT_HEADER=Gr.CompositePropagator=Gr.otperformance=Gr.getStringListFromEnv=Gr.getNumberFromEnv=Gr.getBooleanFromEnv=Gr.getStringFromEnv=Gr._globalThis=Gr.SDK_INFO=Gr.parseKeyPairsIntoRecord=Gr.ExportResultCode=Gr.unrefTimer=Gr.timeInputToHrTime=Gr.millisToHrTime=Gr.isTimeInputHrTime=Gr.isTimeInput=Gr.hrTimeToTimeStamp=Gr.hrTimeToNanoseconds=Gr.hrTimeToMilliseconds=Gr.hrTimeToMicroseconds=Gr.hrTimeDuration=Gr.hrTime=Gr.getTimeOrigin=Gr.addHrTimes=Gr.loggingErrorHandler=Gr.setGlobalErrorHandler=Gr.globalErrorHandler=Gr.sanitizeAttributes=Gr.isAttributeValue=Gr.AnchoredClock=Gr.W3CBaggagePropagator=void 0;var Plo=UNr();Object.defineProperty(Gr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return Plo.W3CBaggagePropagator}});var Mlo=QNr();Object.defineProperty(Gr,"AnchoredClock",{enumerable:!0,get:function(){return Mlo.AnchoredClock}});var UOr=HNr();Object.defineProperty(Gr,"isAttributeValue",{enumerable:!0,get:function(){return UOr.isAttributeValue}});Object.defineProperty(Gr,"sanitizeAttributes",{enumerable:!0,get:function(){return UOr.sanitizeAttributes}});var QOr=WNr();Object.defineProperty(Gr,"globalErrorHandler",{enumerable:!0,get:function(){return QOr.globalErrorHandler}});Object.defineProperty(Gr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return QOr.setGlobalErrorHandler}});var Flo=Xyt();Object.defineProperty(Gr,"loggingErrorHandler",{enumerable:!0,get:function(){return Flo.loggingErrorHandler}});var iv=aOr();Object.defineProperty(Gr,"addHrTimes",{enumerable:!0,get:function(){return iv.addHrTimes}});Object.defineProperty(Gr,"getTimeOrigin",{enumerable:!0,get:function(){return iv.getTimeOrigin}});Object.defineProperty(Gr,"hrTime",{enumerable:!0,get:function(){return iv.hrTime}});Object.defineProperty(Gr,"hrTimeDuration",{enumerable:!0,get:function(){return iv.hrTimeDuration}});Object.defineProperty(Gr,"hrTimeToMicroseconds",{enumerable:!0,get:function(){return iv.hrTimeToMicroseconds}});Object.defineProperty(Gr,"hrTimeToMilliseconds",{enumerable:!0,get:function(){return iv.hrTimeToMilliseconds}});Object.defineProperty(Gr,"hrTimeToNanoseconds",{enumerable:!0,get:function(){return iv.hrTimeToNanoseconds}});Object.defineProperty(Gr,"hrTimeToTimeStamp",{enumerable:!0,get:function(){return iv.hrTimeToTimeStamp}});Object.defineProperty(Gr,"isTimeInput",{enumerable:!0,get:function(){return iv.isTimeInput}});Object.defineProperty(Gr,"isTimeInputHrTime",{enumerable:!0,get:function(){return iv.isTimeInputHrTime}});Object.defineProperty(Gr,"millisToHrTime",{enumerable:!0,get:function(){return iv.millisToHrTime}});Object.defineProperty(Gr,"timeInputToHrTime",{enumerable:!0,get:function(){return iv.timeInputToHrTime}});var Llo=cOr();Object.defineProperty(Gr,"unrefTimer",{enumerable:!0,get:function(){return Llo.unrefTimer}});var Ulo=lOr();Object.defineProperty(Gr,"ExportResultCode",{enumerable:!0,get:function(){return Ulo.ExportResultCode}});var Qlo=Vyt();Object.defineProperty(Gr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return Qlo.parseKeyPairsIntoRecord}});var cU=Jyt();Object.defineProperty(Gr,"SDK_INFO",{enumerable:!0,get:function(){return cU.SDK_INFO}});Object.defineProperty(Gr,"_globalThis",{enumerable:!0,get:function(){return cU._globalThis}});Object.defineProperty(Gr,"getStringFromEnv",{enumerable:!0,get:function(){return cU.getStringFromEnv}});Object.defineProperty(Gr,"getBooleanFromEnv",{enumerable:!0,get:function(){return cU.getBooleanFromEnv}});Object.defineProperty(Gr,"getNumberFromEnv",{enumerable:!0,get:function(){return cU.getNumberFromEnv}});Object.defineProperty(Gr,"getStringListFromEnv",{enumerable:!0,get:function(){return cU.getStringListFromEnv}});Object.defineProperty(Gr,"otperformance",{enumerable:!0,get:function(){return cU.otperformance}});var jlo=dOr();Object.defineProperty(Gr,"CompositePropagator",{enumerable:!0,get:function(){return jlo.CompositePropagator}});var iNe=yOr();Object.defineProperty(Gr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return iNe.TRACE_PARENT_HEADER}});Object.defineProperty(Gr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return iNe.TRACE_STATE_HEADER}});Object.defineProperty(Gr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return iNe.W3CTraceContextPropagator}});Object.defineProperty(Gr,"parseTraceParent",{enumerable:!0,get:function(){return iNe.parseTraceParent}});var oNe=_Or();Object.defineProperty(Gr,"RPCType",{enumerable:!0,get:function(){return oNe.RPCType}});Object.defineProperty(Gr,"deleteRPCMetadata",{enumerable:!0,get:function(){return oNe.deleteRPCMetadata}});Object.defineProperty(Gr,"getRPCMetadata",{enumerable:!0,get:function(){return oNe.getRPCMetadata}});Object.defineProperty(Gr,"setRPCMetadata",{enumerable:!0,get:function(){return oNe.setRPCMetadata}});var d_t=Cpe();Object.defineProperty(Gr,"isTracingSuppressed",{enumerable:!0,get:function(){return d_t.isTracingSuppressed}});Object.defineProperty(Gr,"suppressTracing",{enumerable:!0,get:function(){return d_t.suppressTracing}});Object.defineProperty(Gr,"unsuppressTracing",{enumerable:!0,get:function(){return d_t.unsuppressTracing}});var Glo=o_t();Object.defineProperty(Gr,"TraceState",{enumerable:!0,get:function(){return Glo.TraceState}});var $lo=DOr();Object.defineProperty(Gr,"merge",{enumerable:!0,get:function(){return $lo.merge}});var jOr=ROr();Object.defineProperty(Gr,"TimeoutError",{enumerable:!0,get:function(){return jOr.TimeoutError}});Object.defineProperty(Gr,"callWithTimeout",{enumerable:!0,get:function(){return jOr.callWithTimeout}});var GOr=OOr();Object.defineProperty(Gr,"isUrlIgnored",{enumerable:!0,get:function(){return GOr.isUrlIgnored}});Object.defineProperty(Gr,"urlMatches",{enumerable:!0,get:function(){return GOr.urlMatches}});var qlo=BOr();Object.defineProperty(Gr,"BindOnceFuture",{enumerable:!0,get:function(){return qlo.BindOnceFuture}});var Hlo=MOr();Object.defineProperty(Gr,"diagLogLevelFromString",{enumerable:!0,get:function(){return Hlo.diagLogLevelFromString}});var Vlo=LOr();Gr.internal={_export:Vlo._export}});var $Or=T(aNe=>{"use strict";Object.defineProperty(aNe,"__esModule",{value:!0});aNe.LogRecordImpl=void 0;var lU=(Zt(),vt(ur)),sNe=Q9(),f_t=class{hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;_eventName;totalAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get eventName(){return this._eventName}set eventName(e){this._isLogRecordReadonly()||(this._eventName=e)}get droppedAttributesCount(){return this.totalAttributesCount-Object.keys(this.attributes).length}constructor(e,r,n){let{timestamp:o,observedTimestamp:s,eventName:a,severityNumber:c,severityText:u,body:d,attributes:f={},context:p}=n,h=Date.now();if(this.hrTime=(0,sNe.timeInputToHrTime)(o??h),this.hrTimeObserved=(0,sNe.timeInputToHrTime)(s??h),p){let m=lU.trace.getSpanContext(p);m&&lU.isSpanContextValid(m)&&(this.spanContext=m)}this.severityNumber=c,this.severityText=u,this.body=d,this.resource=e.resource,this.instrumentationScope=r,this._logRecordLimits=e.logRecordLimits,this._eventName=a,this.setAttributes(f)}setAttribute(e,r){return this._isLogRecordReadonly()?this:r===null?this:e.length===0?(lU.diag.warn(`Invalid attribute key: ${e}`),this):!(0,sNe.isAttributeValue)(r)&&!(typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length>0)?(lU.diag.warn(`Invalid attribute value set for key: ${e}`),this):(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this.droppedAttributesCount===1&&lU.diag.warn("Dropping extra attributes."),this):((0,sNe.isAttributeValue)(r)?this.attributes[e]=this._truncateToSize(r):this.attributes[e]=r,this))}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}setBody(e){return this.body=e,this}setEventName(e){return this.eventName=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){let r=this._logRecordLimits.attributeValueLengthLimit;return r<=0?(lU.diag.warn(`Attribute value limit must be positive, got ${r}`),e):typeof e=="string"?this._truncateToLimitUtil(e,r):Array.isArray(e)?e.map(n=>typeof n=="string"?this._truncateToLimitUtil(n,r):n):e}_truncateToLimitUtil(e,r){return e.length<=r?e:e.substring(0,r)}_isLogRecordReadonly(){return this._isReadonly&&lU.diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}};aNe.LogRecordImpl=f_t});var qOr=T(cNe=>{"use strict";Object.defineProperty(cNe,"__esModule",{value:!0});cNe.Logger=void 0;var Wlo=(Zt(),vt(ur)),zlo=$Or(),p_t=class{instrumentationScope;_sharedState;constructor(e,r){this.instrumentationScope=e,this._sharedState=r}emit(e){let r=e.context||Wlo.context.active(),n=new zlo.LogRecordImpl(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(n,r),n._makeReadonly()}};cNe.Logger=p_t});var HOr=T(cX=>{"use strict";Object.defineProperty(cX,"__esModule",{value:!0});cX.reconfigureLimits=cX.loadDefaultConfig=void 0;var aX=Q9();function Ylo(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:(0,aX.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:(0,aX.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??128},includeTraceContext:!0}}cX.loadDefaultConfig=Ylo;function Klo(t){return{attributeCountLimit:t.attributeCountLimit??(0,aX.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??(0,aX.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT")??128,attributeValueLengthLimit:t.attributeValueLengthLimit??(0,aX.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??(0,aX.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0}}cX.reconfigureLimits=Klo});var m_t=T(lNe=>{"use strict";Object.defineProperty(lNe,"__esModule",{value:!0});lNe.NoopLogRecordProcessor=void 0;var h_t=class{forceFlush(){return Promise.resolve()}onEmit(e,r){}shutdown(){return Promise.resolve()}};lNe.NoopLogRecordProcessor=h_t});var VOr=T(uNe=>{"use strict";Object.defineProperty(uNe,"__esModule",{value:!0});uNe.MultiLogRecordProcessor=void 0;var Xlo=Q9(),g_t=class{processors;forceFlushTimeoutMillis;constructor(e,r){this.processors=e,this.forceFlushTimeoutMillis=r}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(r=>(0,Xlo.callWithTimeout)(r.forceFlush(),e)))}onEmit(e,r){this.processors.forEach(n=>n.onEmit(e,r))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}};uNe.MultiLogRecordProcessor=g_t});var WOr=T(dNe=>{"use strict";Object.defineProperty(dNe,"__esModule",{value:!0});dNe.LoggerProviderSharedState=void 0;var Jlo=m_t(),Zlo=VOr(),A_t=class{resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,r,n,o){this.resource=e,this.forceFlushTimeoutMillis=r,this.logRecordLimits=n,this.processors=o,o.length>0?(this.registeredLogRecordProcessors=o,this.activeProcessor=new Zlo.MultiLogRecordProcessor(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new Jlo.NoopLogRecordProcessor}};dNe.LoggerProviderSharedState=A_t});var KOr=T(uU=>{"use strict";Object.defineProperty(uU,"__esModule",{value:!0});uU.LoggerProvider=uU.DEFAULT_LOGGER_NAME=void 0;var fNe=(Zt(),vt(ur)),euo=FNr(),tuo=Lyt(),zOr=Q9(),ruo=qOr(),YOr=HOr(),nuo=WOr();uU.DEFAULT_LOGGER_NAME="unknown";var y_t=class{_shutdownOnce;_sharedState;constructor(e={}){let r=(0,zOr.merge)({},(0,YOr.loadDefaultConfig)(),e),n=e.resource??(0,tuo.defaultResource)();this._sharedState=new nuo.LoggerProviderSharedState(n,r.forceFlushTimeoutMillis,(0,YOr.reconfigureLimits)(r.logRecordLimits),e?.processors??[]),this._shutdownOnce=new zOr.BindOnceFuture(this._shutdown,this)}getLogger(e,r,n){if(this._shutdownOnce.isCalled)return fNe.diag.warn("A shutdown LoggerProvider cannot provide a Logger"),euo.NOOP_LOGGER;e||fNe.diag.warn("Logger requested without instrumentation scope name.");let o=e||uU.DEFAULT_LOGGER_NAME,s=`${o}@${r||""}:${n?.schemaUrl||""}`;return this._sharedState.loggers.has(s)||this._sharedState.loggers.set(s,new ruo.Logger({name:o,version:r,schemaUrl:n?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(s)}forceFlush(){return this._shutdownOnce.isCalled?(fNe.diag.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(fNe.diag.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}};uU.LoggerProvider=y_t});var JOr=T(pNe=>{"use strict";Object.defineProperty(pNe,"__esModule",{value:!0});pNe.ConsoleLogRecordExporter=void 0;var XOr=Q9(),__t=class{export(e,r){this._sendLogRecords(e,r)}shutdown(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:(0,XOr.hrTimeToMicroseconds)(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,body:e.body,attributes:e.attributes}}_sendLogRecords(e,r){for(let n of e)console.dir(this._exportInfo(n),{depth:3});r?.({code:XOr.ExportResultCode.SUCCESS})}};pNe.ConsoleLogRecordExporter=__t});var ZOr=T(hNe=>{"use strict";Object.defineProperty(hNe,"__esModule",{value:!0});hNe.SimpleLogRecordProcessor=void 0;var lX=Q9(),E_t=class{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new lX.BindOnceFuture(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e){if(this._shutdownOnce.isCalled)return;let r=()=>lX.internal._export(this._exporter,[e]).then(n=>{n.code!==lX.ExportResultCode.SUCCESS&&(0,lX.globalErrorHandler)(n.error??new Error(`SimpleLogRecordProcessor: log record export failed (status ${n})`))}).catch(lX.globalErrorHandler);if(e.resource.asyncAttributesPending){let n=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(n),r()),lX.globalErrorHandler);n!=null&&this._unresolvedExports.add(n)}else r()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}};hNe.SimpleLogRecordProcessor=E_t});var tkr=T(mNe=>{"use strict";Object.defineProperty(mNe,"__esModule",{value:!0});mNe.InMemoryLogRecordExporter=void 0;var ekr=Q9(),v_t=class{_finishedLogRecords=[];_stopped=!1;export(e,r){if(this._stopped)return r({code:ekr.ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),r({code:ekr.ExportResultCode.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}};mNe.InMemoryLogRecordExporter=v_t});var rkr=T(gNe=>{"use strict";Object.defineProperty(gNe,"__esModule",{value:!0});gNe.BatchLogRecordProcessorBase=void 0;var iuo=(Zt(),vt(ur)),ov=Q9(),b_t=class{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,r){this._exporter=e,this._maxExportBatchSize=r?.maxExportBatchSize??(0,ov.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=r?.maxQueueSize??(0,ov.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=r?.scheduledDelayMillis??(0,ov.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY")??5e3,this._exportTimeoutMillis=r?.exportTimeoutMillis??(0,ov.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT")??3e4,this._shutdownOnce=new ov.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(iuo.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,r)=>{let n=[],o=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let s=0;s<o;s++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(r)})}_flushOneBatch(){return this._clearTimer(),this._finishedLogRecords.length===0?Promise.resolve():new Promise((e,r)=>{(0,ov.callWithTimeout)(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis).then(()=>e()).catch(r)})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().then(()=>{this._isExporting=!1,this._finishedLogRecords.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(r=>{this._isExporting=!1,(0,ov.globalErrorHandler)(r)})};if(this._finishedLogRecords.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!="number"&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}_export(e){let r=()=>ov.internal._export(this._exporter,e).then(o=>{o.code!==ov.ExportResultCode.SUCCESS&&(0,ov.globalErrorHandler)(o.error??new Error(`BatchLogRecordProcessor: log record export failed (status ${o})`))}).catch(ov.globalErrorHandler),n=e.map(o=>o.resource).filter(o=>o.asyncAttributesPending);return n.length===0?r():Promise.all(n.map(o=>o.waitForAsyncAttributes?.())).then(r,ov.globalErrorHandler)}};gNe.BatchLogRecordProcessorBase=b_t});var nkr=T(ANe=>{"use strict";Object.defineProperty(ANe,"__esModule",{value:!0});ANe.BatchLogRecordProcessor=void 0;var ouo=rkr(),C_t=class extends ouo.BatchLogRecordProcessorBase{onShutdown(){}};ANe.BatchLogRecordProcessor=C_t});var ikr=T(yNe=>{"use strict";Object.defineProperty(yNe,"__esModule",{value:!0});yNe.BatchLogRecordProcessor=void 0;var suo=nkr();Object.defineProperty(yNe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return suo.BatchLogRecordProcessor}})});var okr=T(_Ne=>{"use strict";Object.defineProperty(_Ne,"__esModule",{value:!0});_Ne.BatchLogRecordProcessor=void 0;var auo=ikr();Object.defineProperty(_Ne,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return auo.BatchLogRecordProcessor}})});var skr=T(O3=>{"use strict";Object.defineProperty(O3,"__esModule",{value:!0});O3.BatchLogRecordProcessor=O3.InMemoryLogRecordExporter=O3.SimpleLogRecordProcessor=O3.ConsoleLogRecordExporter=O3.NoopLogRecordProcessor=O3.LoggerProvider=void 0;var cuo=KOr();Object.defineProperty(O3,"LoggerProvider",{enumerable:!0,get:function(){return cuo.LoggerProvider}});var luo=m_t();Object.defineProperty(O3,"NoopLogRecordProcessor",{enumerable:!0,get:function(){return luo.NoopLogRecordProcessor}});var uuo=JOr();Object.defineProperty(O3,"ConsoleLogRecordExporter",{enumerable:!0,get:function(){return uuo.ConsoleLogRecordExporter}});var duo=ZOr();Object.defineProperty(O3,"SimpleLogRecordProcessor",{enumerable:!0,get:function(){return duo.SimpleLogRecordProcessor}});var fuo=tkr();Object.defineProperty(O3,"InMemoryLogRecordExporter",{enumerable:!0,get:function(){return fuo.InMemoryLogRecordExporter}});var puo=okr();Object.defineProperty(O3,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return puo.BatchLogRecordProcessor}})});var sh,akr,Tpe,ckr,Ipe,Dpe,lkr,ukr,dkr,fkr,pkr,hkr,mkr,gkr,Akr,ykr,_kr,Ekr,vkr,bkr,Ckr,Skr,xkr,wkr,Tkr,Ikr,Dkr,Rkr,Nkr,Okr,kkr,Bkr,Pkr,Mkr,Fkr,Lkr,uX=te(()=>{"use strict";sh="iflow-cli",akr="iflow_cli.user_prompt",Tpe="iflow_cli.tool_call",ckr="iflow_cli.api_request",Ipe="iflow_cli.api_error",Dpe="iflow_cli.api_response",lkr="iflow_cli.config",ukr="iflow_cli.flash_fallback",dkr="iflow_cli.next_speaker_check",fkr="iflow_cli.slash_command",pkr="iflow_cli.cli_response",hkr="iflow_cli.tool.call.count",mkr="iflow_cli.tool.call.latency",gkr="iflow_cli.mcp.tool.call.count",Akr="iflow_cli.mcp.tool.call.latency",ykr="iflow_cli.builtin.tool.call.count",_kr="iflow_cli.builtin.tool.call.latency",Ekr="gen_ai.client.operation",vkr="gen_ai.client.operation.duration",bkr="gen_ai.client.token.usage",Ckr="iflow_cli.session.count",Skr="iflow_cli.file.operation.count",xkr="iflow_cli.user_request.count",wkr="iflow_cli.user_request.latency",Tkr="iflow_cli.user_experience.success",Ikr="iflow_cli.user.identity",Dkr="iflow_cli.scheduler.lock.error",Rkr="iflow_cli.mcp.connect.count",Nkr="iflow_cli.loop.detection.count",Okr="iflow_cli.paste.operation.count",kkr="iflow_cli.paste.operation.latency",Bkr="iflow_cli.xinliu.web.search.count",Pkr="iflow_cli.xinliu.web.search.latency",Mkr="iflow_cli.web.fetch.count",Fkr="iflow_cli.web.fetch.latency",Lkr="iflow_cli.approval.mode.count"});var dX,fX,pX,hX,mX,gX,AX,yX,_X,EX,AC,yC,Ukr=te(()=>{"use strict";dX="iflow_cli.cpu.usage_percentage",fX="iflow_cli.cpu.user_percentage",pX="iflow_cli.cpu.system_percentage",hX="iflow_cli.cpu.cores",mX="iflow_cli.memory.heap_used",gX="iflow_cli.memory.heap_total",AX="iflow_cli.memory.rss",yX="iflow_cli.memory.external",_X="iflow_cli.memory.system_usage_percentage",EX="iflow_cli.memory.process_usage_percentage",AC={[dX]:"CPU usage percentage",[fX]:"CPU user time percentage",[pX]:"CPU system time percentage",[hX]:"Number of CPU cores",[mX]:"Heap memory used in bytes",[gX]:"Heap memory total in bytes",[AX]:"Resident Set Size in bytes",[yX]:"External memory in bytes",[_X]:"System memory usage percentage",[EX]:"Process memory usage percentage relative to Node.js limits"},yC={[dX]:"percent",[fX]:"percent",[pX]:"percent",[hX]:"cores",[mX]:"bytes",[gX]:"bytes",[AX]:"bytes",[yX]:"bytes",[_X]:"percent",[EX]:"percent"}});import*as _C from"os";var ENe,Qkr=te(()=>{"use strict";Ukr();ENe=class{meter;options;lastCpuMeasurement;lastMeasureTime;cpuCores;totalSystemMemory;nodeJSMemoryLimit;cpuUsageGauge;cpuUserGauge;cpuSystemGauge;cpuCoresGauge;memoryHeapUsedGauge;memoryHeapTotalGauge;memoryRssGauge;memoryExternalGauge;memorySystemUsageGauge;memoryProcessUsageGauge;constructor(e,r={}){this.meter=e,this.options={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...r},this.lastCpuMeasurement=process.cpuUsage(),this.lastMeasureTime=Date.now(),this.cpuCores=_C.cpus().length,this.totalSystemMemory=_C.totalmem(),this.nodeJSMemoryLimit=this.getNodeJSMemoryLimit(),this.initializeMetrics()}getCurrentCpuMetrics(){try{let e=process.cpuUsage(this.lastCpuMeasurement),r=Date.now(),n=r-this.lastMeasureTime;if(this.lastCpuMeasurement=process.cpuUsage(),this.lastMeasureTime=r,n<=0)return{usage:0,user:0,system:0,cores:this.cpuCores};let o=Math.max(0,e.user+e.system),s=Math.max(0,e.user),a=Math.max(0,e.system),c=o/(n*1e3)*100,u=s/(n*1e3)*100,d=a/(n*1e3)*100,f=Number.isFinite(c)?Math.min(100,Math.max(0,c)):0,p=Number.isFinite(u)?Math.min(100,Math.max(0,u)):0,h=Number.isFinite(d)?Math.min(100,Math.max(0,d)):0;return{usage:f,user:p,system:h,cores:this.cpuCores}}catch{return{usage:0,user:0,system:0,cores:this.cpuCores}}}getCurrentMemoryMetrics(){try{let e=process.memoryUsage(),r=_C.freemem(),o=(this.totalSystemMemory-r)/this.totalSystemMemory*100,s=e.rss/this.nodeJSMemoryLimit*100;return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,external:e.external,systemUsage:Math.min(100,Math.max(0,o)),processUsage:Math.min(100,Math.max(0,s))}}catch{return{heapUsed:0,heapTotal:0,rss:0,external:0,systemUsage:0,processUsage:0}}}initializeMetrics(){let e=_C.platform(),r=_C.arch(),n=process.version;this.options.enableCpuMetrics&&(this.cpuUsageGauge=this.meter.createObservableGauge(dX,{description:AC[dX],unit:yC[dX]}),this.cpuUserGauge=this.meter.createObservableGauge(fX,{description:AC[fX],unit:yC[fX]}),this.cpuSystemGauge=this.meter.createObservableGauge(pX,{description:AC[pX],unit:yC[pX]}),this.cpuCoresGauge=this.meter.createObservableGauge(hX,{description:AC[hX],unit:yC[hX]}),this.cpuUsageGauge.addCallback(o=>{let s=this.getCurrentCpuMetrics();o.observe(s.usage,{platform:e,arch:r,node_version:n})}),this.cpuUserGauge.addCallback(o=>{let s=this.getCurrentCpuMetrics();o.observe(s.user,{platform:e,arch:r,node_version:n})}),this.cpuSystemGauge.addCallback(o=>{let s=this.getCurrentCpuMetrics();o.observe(s.system,{platform:e,arch:r,node_version:n})}),this.cpuCoresGauge?.addCallback(o=>{o.observe(this.cpuCores,{platform:e,arch:r})})),this.options.enableMemoryMetrics&&(this.memoryHeapUsedGauge=this.meter.createObservableGauge(mX,{description:AC[mX],unit:yC[mX]}),this.memoryHeapTotalGauge=this.meter.createObservableGauge(gX,{description:AC[gX],unit:yC[gX]}),this.memoryRssGauge=this.meter.createObservableGauge(AX,{description:AC[AX],unit:yC[AX]}),this.memoryExternalGauge=this.meter.createObservableGauge(yX,{description:AC[yX],unit:yC[yX]}),this.memorySystemUsageGauge=this.meter.createObservableGauge(_X,{description:AC[_X],unit:yC[_X]}),this.memoryProcessUsageGauge=this.meter.createObservableGauge(EX,{description:AC[EX],unit:yC[EX]}),this.memoryHeapUsedGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.heapUsed,{platform:e,arch:r,node_version:n})}),this.memoryHeapTotalGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.heapTotal,{platform:e,arch:r,node_version:n})}),this.memoryRssGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.rss,{platform:e,arch:r,node_version:n})}),this.memoryExternalGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.external,{platform:e,arch:r,node_version:n})}),this.memorySystemUsageGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.systemUsage,{platform:e,arch:r,node_version:n})}),this.memoryProcessUsageGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.processUsage,{platform:e,arch:r,node_version:n,memory_limit_mb:Math.round(this.nodeJSMemoryLimit/(1024*1024)).toString()})}))}getNodeJSMemoryLimit(){let e=process.execArgv.find(o=>o.startsWith("--max-old-space-size="))?.split("=")[1];if(e){let o=parseInt(e,10);if(!isNaN(o)&&o>0)return o*1024*1024}let r=process.execArgv.find(o=>o.startsWith("--max_old_space_size="))?.split("=")[1];if(r){let o=parseInt(r,10);if(!isNaN(o)&&o>0)return o*1024*1024}let n=_C.arch();return n==="x64"||n==="arm64"?1400*1024*1024:700*1024*1024}}});function jkr(t,e={}){if(vNe)return vNe;let r={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...e};return vNe=new ENe(t,r),vNe}var vNe,Gkr=te(()=>{"use strict";Qkr();vNe=null});import huo from"os";function $kr(){try{let t=huo.networkInterfaces();for(let e of Object.keys(t)){let r=t[e];if(r){for(let n of r)if(n.family==="IPv4"&&!n.internal)return n.address}}return"127.0.0.1"}catch{return"127.0.0.1"}}var qkr=te(()=>{"use strict"});import*as vX from"os";import*as bNe from"fs";function Gc(t){let e="0.4.2",r=process.env.IFLOW_ENV||"normal",n={darwin:"macOS",win32:"Windows",linux:"Linux",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",aix:"AIX"},o=vX.platform(),s=n[o]||o,a="unknown";try{if(o==="darwin")a=vX.release();else if(o==="linux")try{if(bNe.existsSync("/etc/os-release")){let m=bNe.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="(.+)"/m);m&&(a=m[1])}}catch{a=vX.release()}else o==="win32"&&(a=vX.release())}catch{a="unknown"}let c={name:"Node.js",version:process.version,architecture:process.arch},u=t.getModel()||"unknown",d=t.getUsageMode(),f=!1,p=t.getContentGeneratorConfig?.();if(p){let h=p.authType,m=p.baseUrl||"";(h===Yt.LOGIN_WITH_IFLOW||h===Yt.IFLOW||h===Yt.OPENAI_COMPATIBLE&&m.includes("apis.iflow.cn"))&&(f=!0)}return{app_name:sh,tenant__:"gen_ai",version:e,platform:s,os_model:a,runtime_name:c.name,runtime_version:c.version,runtime_architecture:c.architecture,model_name:u,is_iflow_open_user:String(f),ip:$kr(),iflow_env:r,usage_mode:d}}var S_t=te(()=>{"use strict";A_();qkr();uX()});function Hkr(){return x_t||(x_t=dde.getMeter(sh)),x_t}function Vkr(){if(ah)return;let t=Hkr();if(t){try{jkr(t,{enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0})}catch{}w_t=t.createHistogram(hkr,{description:"Counts tool calls, tagged by function name and success.",unit:"count",valueType:lc.INT}),T_t=t.createHistogram(mkr,{description:"Latency of tool calls in milliseconds.",unit:"ms",valueType:lc.INT}),I_t=t.createHistogram(gkr,{description:"Counts MCP tool calls, tagged by function name and success.",unit:"count",valueType:lc.INT}),D_t=t.createHistogram(Akr,{description:"Latency of MCP tool calls in milliseconds.",unit:"ms",valueType:lc.INT}),R_t=t.createHistogram(ykr,{description:"Counts built-in tool calls, tagged by function name and success.",unit:"count",valueType:lc.INT}),N_t=t.createHistogram(_kr,{description:"Latency of built-in tool calls in milliseconds.",unit:"ms",valueType:lc.INT}),Rpe=t.createHistogram(Ekr,{description:"Counts API requests, tagged by model and status.",unit:"count",valueType:lc.INT}),Npe=t.createHistogram(vkr,{description:"Latency of API requests in milliseconds.",unit:"ms",valueType:lc.INT}),O_t=t.createHistogram(bkr,{description:"Counts the total number of tokens used.",unit:"tokens",valueType:lc.INT}),k_t=t.createHistogram(Skr,{description:"Counts file operations (create, read, update).",unit:"count",valueType:lc.INT}),B_t=t.createHistogram(xkr,{description:"Counts user requests from prompt to completion.",unit:"count",valueType:lc.INT}),P_t=t.createHistogram(wkr,{description:"End-to-end latency of user requests in milliseconds.",unit:"ms",valueType:lc.INT}),M_t=t.createHistogram(Tkr,{description:"User experience success rate - counts successful user experiences including retries and fixes.",unit:"count",valueType:lc.INT}),F_t=t.createHistogram(Ikr,{description:"User identity for tracking unique installations.",unit:"count",valueType:lc.INT}),L_t=t.createHistogram(Dkr,{description:"Counts tool scheduler lock errors when new calls are blocked by running calls.",unit:"count",valueType:lc.INT}),U_t=t.createHistogram(Rkr,{description:"Counts MCP connection attempts and their success/failure status.",unit:"count",valueType:lc.INT}),Q_t=t.createHistogram(Nkr,{description:"Counts loop detection events by loop type.",unit:"count",valueType:lc.INT}),j_t=t.createHistogram(Okr,{description:"Counts paste operations, tagged by type and success.",unit:"count",valueType:lc.INT}),G_t=t.createHistogram(kkr,{description:"Latency of paste operations in milliseconds.",unit:"ms",valueType:lc.INT}),$_t=t.createHistogram(Bkr,{description:"Counts xinliu web search operations, tagged by success and error type.",unit:"count",valueType:lc.INT}),q_t=t.createHistogram(Pkr,{description:"Latency of xinliu web search operations in milliseconds.",unit:"ms",valueType:lc.INT}),H_t=t.createHistogram(Mkr,{description:"Counts web fetch operations, tagged by success and error type.",unit:"count",valueType:lc.INT}),V_t=t.createHistogram(Fkr,{description:"Latency of web fetch operations in milliseconds.",unit:"ms",valueType:lc.INT}),W_t=t.createHistogram(Lkr,{description:"Counts usage of different approval modes.",unit:"count",valueType:lc.INT}),ah=!0}}function CNe(t){let e=Hkr();if(!e||!ah)return;e.createHistogram(Ckr,{description:"Count of CLI sessions started.",unit:"count",valueType:lc.INT}).record(1,Gc(t))}function Wkr(t,e,r,n,o,s){if(!w_t||!T_t||!ah)return;let a={...Gc(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};w_t.record(1,a),T_t.record(r,{...Gc(t),function_name:e??"unknown",tool_type:s??"unknown"})}function zkr(t,e,r,n,o,s){if(!I_t||!D_t||!ah)return;let a={...Gc(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};s&&(a.execution_context=s),I_t.record(1,a),D_t.record(r,{...Gc(t),function_name:e??"unknown",execution_context:s??"unknown"})}function Ykr(t,e,r,n,o,s){if(!R_t||!N_t||!ah)return;let a={...Gc(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};s&&(a.execution_context=s),R_t.record(1,a),N_t.record(r,{...Gc(t),function_name:e??"unknown",execution_context:s??"unknown"})}function bX(t,e,r,n){!O_t||!ah||O_t.record(r,{...Gc(t),model:e??"unknown",type:n??"unknown"})}function Kkr(t,e,r,n,o,s,a,c){if(!Rpe||!Npe||!ah)return;let u={...Gc(t),model:e??"unknown",status_code:String(n??(o?"error":"ok"))};a!==void 0&&(u.http_status_code=String(a)),c!==void 0&&(u.business_code=String(c)),s&&(u.finish_reason=s),Rpe.record(1,u);let d={...Gc(t),model:e??"unknown",http_status_code:String(a??200),finish_reason:s??"unknown"};c!=null&&(d.business_code=String(c)),Npe.record(r,d)}function Xkr(t,e,r,n,o,s,a){if(!Rpe||!Npe||!ah)return;let c={...Gc(t),model:e??"unknown",status_code:String(n??"error"),error:o??"unknown"};s!==void 0&&(c.http_status_code=String(s)),a!==void 0&&(c.business_code=String(a)),Rpe.record(1,c);let u={...Gc(t),model:e??"unknown",http_status_code:String(s??0),error:o??"unknown"};a!=null&&(u.business_code=String(a)),Npe.record(r,u)}function dU(t,e,r,n,o){if(!k_t||!ah)return;let s={...Gc(t),operation:e};r!==void 0&&(s.lines=String(r)),n!==void 0&&(s.mimetype=n),o!==void 0&&(s.extension=o),k_t.record(1,s)}function Jkr(t,e,r,n,o){if(!B_t||!P_t||!ah)return;let s={...Gc(t),prompt_id:e,success:String(n)};o&&(s.error=o),B_t.record(1,s),P_t.record(r,s)}function z_t(t,e,r=!1,n=!1,o){if(!M_t||!ah)return;let s={...Gc(t),success:String(e),had_retries:String(r),had_fixes:String(n)};o&&(s.final_error=o),M_t.record(1,s)}function Zkr(t,e){if(!F_t||!ah)return;let r={...Gc(t),user_id:e};F_t.record(1,r)}function eBr(t,e,r){if(!L_t||!ah)return;let n={...Gc(t),running_calls_count:String(e)};r.forEach((o,s)=>{n[`call_${s}_name`]=o.name,n[`call_${s}_status`]=o.status}),L_t.record(1,n)}function Y_t(t,e,r,n,o){if(!U_t||!ah)return;let s={...Gc(t),server_name:e,success:String(r)};n&&(s.error_type=n),o&&(s.transport_type=o),U_t.record(1,s)}function tBr(t,e,r){if(!Q_t||!ah)return;let n={...Gc(t),loop_type:e,prompt_id:r};Q_t.record(1,n)}function SNe(t,e,r,n,o="text",s,a){if(!j_t||!G_t||!ah)return;let c={};try{c=Gc(t)}catch{c={app_name:sh,tenant__:"gen_ai",version:"unknown",platform:a||"unknown",os_model:"unknown",runtime_name:"Node.js",runtime_version:process.version,runtime_architecture:process.arch,model_name:"unknown",is_iflow_open_user:"false",ip:"unknown",iflow_env:"test",usage_mode:"unknown"}}let u={...c,success:String(n),paste_type:o};s&&(u.error_type=s),a&&(u.platform_specific=a),j_t.record(1,u);let d={...c,paste_type:o,text_length_range:String(r),performance_ratio:muo(e,r)};G_t.record(e,d)}function muo(t,e){if(e===0)return"no-text";let r=t/e;return r<=.1?"excellent":r<=.5?"good":r<=1?"normal":r<=2?"slow":"very-slow"}function xNe(t,e,r,n,o,s){if(!$_t||!q_t||!ah)return;let a={...Gc(t),success:String(r)};n&&(a.error_type=n),o!==void 0&&(a.results_count=String(o)),s&&(a.query_length=String(s.length)),$_t.record(1,a),q_t.record(e,{...Gc(t),error_type:n??"none"})}function fU(t,e,r,n,o,s){if(!H_t||!V_t||!ah)return;let a={...Gc(t),success:String(r)};n&&(a.error_type=n),o!==void 0&&(a.url_count=String(o)),s!==void 0&&(a.prompt_length=String(s)),H_t.record(1,a),V_t.record(e,{...Gc(t),error_type:n??"none"})}function wNe(t,e){if(!W_t||!ah)return;let r={...Gc(t),approval_mode:e};W_t.record(1,r)}var j9,x_t,w_t,T_t,I_t,D_t,R_t,N_t,Rpe,Npe,O_t,k_t,B_t,P_t,M_t,F_t,L_t,U_t,Q_t,j_t,G_t,$_t,q_t,H_t,V_t,W_t,ah,r1=te(()=>{"use strict";Zt();uX();Gkr();S_t();(function(t){t.CREATE="create",t.READ="read",t.UPDATE="update"})(j9||(j9={}));ah=!1});var es,xn,ts,rs,nf=te(()=>{"use strict";es=class{name;displayName;description;icon;kind;parameterSchema;isOutputMarkdown;canUpdateOutput;aliases;constructor(e,r,n,o,s,a,c=!0,u=!1,d=[]){this.name=e,this.displayName=r,this.description=n,this.icon=o,this.kind=s,this.parameterSchema=a,this.isOutputMarkdown=c,this.canUpdateOutput=u,this.aliases=d}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(e){return null}getDescription(e){return JSON.stringify(e)}shouldConfirmExecute(e,r){return Promise.resolve(!1)}toolLocations(e){return[]}};(function(t){t.ProceedOnce="proceed_once",t.ProceedAlways="proceed_always",t.ProceedAlwaysServer="proceed_always_server",t.ProceedAlwaysTool="proceed_always_tool",t.ModifyWithEditor="modify_with_editor",t.Cancel="cancel"})(xn||(xn={}));(function(t){t.FileSearch="fileSearch",t.Folder="folder",t.Globe="globe",t.Hammer="hammer",t.LightBulb="lightBulb",t.Pencil="pencil",t.Regex="regex",t.Terminal="terminal"})(ts||(ts={}));(function(t){t.Read="read",t.Edit="edit",t.Delete="delete",t.Move="move",t.Search="search",t.Execute="execute",t.Think="think",t.Fetch="fetch",t.Other="other"})(rs||(rs={}))});function guo(t){switch(t){case xn.ProceedOnce:case xn.ProceedAlways:case xn.ProceedAlwaysServer:case xn.ProceedAlwaysTool:return sv.ACCEPT;case xn.ModifyWithEditor:return sv.MODIFY;case xn.Cancel:default:return sv.REJECT}}var sv,CX,SX,xX,wX,TX,DA,IX,DX,av,RX,TNe,NX,INe,LN=te(()=>{"use strict";nf();A_();(function(t){t.ACCEPT="accept",t.REJECT="reject",t.MODIFY="modify"})(sv||(sv={}));CX=class{"event.name";"event.timestamp";model;embedding_model;sandbox_enabled;core_tools_enabled;approval_mode;api_key_enabled;vertex_ai_enabled;debug_enabled;mcp_servers;telemetry_enabled;telemetry_log_user_prompts_enabled;file_filtering_respect_git_ignore;constructor(e){let r=e.getContentGeneratorConfig(),n=e.getMcpServers(),o=!1,s=!1;r&&r.authType&&(o=r.authType===Yt.IFLOW,s=r.authType===Yt.AONE),this["event.name"]="cli_config",this.model=e.getModel(),this.embedding_model=e.getEmbeddingModel(),this.sandbox_enabled=typeof e.getSandbox()=="string"||!!e.getSandbox(),this.core_tools_enabled=(e.getCoreTools()??[]).join(","),this.approval_mode=e.getApprovalMode(),this.api_key_enabled=o||s,this.vertex_ai_enabled=s,this.debug_enabled=e.getDebugMode(),this.mcp_servers=n?Object.keys(n).join(","):"",this.telemetry_enabled=e.getTelemetryEnabled(),this.telemetry_log_user_prompts_enabled=e.getTelemetryLogPromptsEnabled(),this.file_filtering_respect_git_ignore=e.getFileFilteringRespectGitIgnore()}},SX=class{"event.name";"event.timestamp";session_id;constructor(e){this["event.name"]="end_session",this["event.timestamp"]=new Date().toISOString(),this.session_id=e?.getSessionId()}},xX=class{"event.name";"event.timestamp";prompt_length;prompt_id;auth_type;prompt;constructor(e,r,n,o){this["event.name"]="user_prompt",this["event.timestamp"]=new Date().toISOString(),this.prompt_length=e,this.prompt_id=r,this.auth_type=n,this.prompt=o}},wX=class{"event.name";"event.timestamp";function_name;function_args;duration_ms;success;decision;error;error_type;prompt_id;server_name;response_text;constructor(e){this["event.name"]="tool_call",this["event.timestamp"]=new Date().toISOString(),this.function_name=e.request.name,this.function_args=JSON.stringify(e.request.args),this.duration_ms=e.durationMs??0,this.success=e.status==="success",this.decision=e.outcome?guo(e.outcome):void 0,this.error=e.response.error?.message,this.error_type=e.response.errorType,this.prompt_id=e.request.prompt_id,this.response_text=JSON.stringify(e.response,null,2),"tool"in e&&e.tool&&"serverName"in e.tool&&(this.server_name=e.tool.serverName)}},TX=class{"event.name";"event.timestamp";model;prompt_id;request_text;base_url;openai_request;constructor(e,r,n,o,s){this["event.name"]="api_request",this["event.timestamp"]=new Date().toISOString(),this.model=r,this.prompt_id=o,this.request_text=s,this.base_url=e,this.openai_request=n}},DA=class{"event.name";"event.timestamp";model;error;error_type;status_code;http_status_code;business_code;duration_ms;prompt_id;auth_type;constructor(e,r,n,o,s,a,c,u,d){this["event.name"]="api_error",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.error=r,this.error_type=a,this.status_code=c,this.http_status_code=u,this.business_code=d,this.duration_ms=n,this.prompt_id=o,this.auth_type=s}},IX=class{"event.name";"event.timestamp";model;status_code;http_status_code;business_code;duration_ms;error;input_token_count;output_token_count;cached_content_token_count;thoughts_token_count;tool_token_count;total_token_count;response_text;prompt_id;auth_type;finish_reason;constructor(e,r,n,o,s,a,c,u,d,f){this["event.name"]="api_response",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.duration_ms=r,this.status_code=200,this.http_status_code=d||200,this.business_code=f,this.input_token_count=s?.promptTokenCount??0,this.output_token_count=s?.candidatesTokenCount??0,this.cached_content_token_count=s?.cachedContentTokenCount??0,this.thoughts_token_count=s?.thoughtsTokenCount??0,this.tool_token_count=s?.toolUsePromptTokenCount??0,this.total_token_count=s?.totalTokenCount??0,this.response_text=a,this.error=c,this.prompt_id=n,this.auth_type=o,this.finish_reason=u}},DX=class{"event.name";"event.timestamp";auth_type;constructor(e){this["event.name"]="flash_fallback",this["event.timestamp"]=new Date().toISOString(),this.auth_type=e}};(function(t){t.CONSECUTIVE_IDENTICAL_TOOL_CALLS="consecutive_identical_tool_calls",t.CHANTING_IDENTICAL_SENTENCES="chanting_identical_sentences",t.LLM_DETECTED_LOOP="llm_detected_loop"})(av||(av={}));RX=class{"event.name";"event.timestamp";loop_type;prompt_id;constructor(e,r){this["event.name"]="loop_detected",this["event.timestamp"]=new Date().toISOString(),this.loop_type=e,this.prompt_id=r}},TNe=class{"event.name";"event.timestamp";prompt_id;finish_reason;result;constructor(e,r,n){this["event.name"]="next_speaker_check",this["event.timestamp"]=new Date().toISOString(),this.prompt_id=e,this.finish_reason=r,this.result=n}},NX=class{"event.name";"event.timestamp";command;subcommand;constructor(e,r){this["event.name"]="slash_command",this["event.timestamp"]=new Date().toISOString(),this.command=e,this.subcommand=r}},INe=class{"event.name";"event.timestamp";model;constructor(e){this["event.name"]="malformed_json_response",this["event.timestamp"]=new Date().toISOString(),this.model=e}}});var Zn,rBr=te(()=>{"use strict";(function(t){t[t.IFLOW_CLI_KEY_UNKNOWN=0]="IFLOW_CLI_KEY_UNKNOWN",t[t.IFLOW_CLI_START_SESSION_MODEL=1]="IFLOW_CLI_START_SESSION_MODEL",t[t.IFLOW_CLI_START_SESSION_EMBEDDING_MODEL=2]="IFLOW_CLI_START_SESSION_EMBEDDING_MODEL",t[t.IFLOW_CLI_START_SESSION_SANDBOX=3]="IFLOW_CLI_START_SESSION_SANDBOX",t[t.IFLOW_CLI_START_SESSION_CORE_TOOLS=4]="IFLOW_CLI_START_SESSION_CORE_TOOLS",t[t.IFLOW_CLI_START_SESSION_APPROVAL_MODE=5]="IFLOW_CLI_START_SESSION_APPROVAL_MODE",t[t.IFLOW_CLI_START_SESSION_API_KEY_ENABLED=6]="IFLOW_CLI_START_SESSION_API_KEY_ENABLED",t[t.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED=7]="IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED",t[t.IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED=8]="IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED",t[t.IFLOW_CLI_START_SESSION_MCP_SERVERS=9]="IFLOW_CLI_START_SESSION_MCP_SERVERS",t[t.IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED=10]="IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED",t[t.IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED=11]="IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED",t[t.IFLOW_CLI_START_SESSION_RESPECT_GITIGNORE=12]="IFLOW_CLI_START_SESSION_RESPECT_GITIGNORE",t[t.IFLOW_CLI_USER_PROMPT_LENGTH=13]="IFLOW_CLI_USER_PROMPT_LENGTH",t[t.IFLOW_CLI_TOOL_CALL_NAME=14]="IFLOW_CLI_TOOL_CALL_NAME",t[t.IFLOW_CLI_TOOL_CALL_DECISION=15]="IFLOW_CLI_TOOL_CALL_DECISION",t[t.IFLOW_CLI_TOOL_CALL_SUCCESS=16]="IFLOW_CLI_TOOL_CALL_SUCCESS",t[t.IFLOW_CLI_TOOL_CALL_DURATION_MS=17]="IFLOW_CLI_TOOL_CALL_DURATION_MS",t[t.IFLOW_CLI_TOOL_ERROR_MESSAGE=18]="IFLOW_CLI_TOOL_ERROR_MESSAGE",t[t.IFLOW_CLI_TOOL_CALL_ERROR_TYPE=19]="IFLOW_CLI_TOOL_CALL_ERROR_TYPE",t[t.IFLOW_CLI_API_REQUEST_MODEL=20]="IFLOW_CLI_API_REQUEST_MODEL",t[t.IFLOW_CLI_API_RESPONSE_MODEL=21]="IFLOW_CLI_API_RESPONSE_MODEL",t[t.IFLOW_CLI_API_RESPONSE_STATUS_CODE=22]="IFLOW_CLI_API_RESPONSE_STATUS_CODE",t[t.IFLOW_CLI_API_RESPONSE_DURATION_MS=23]="IFLOW_CLI_API_RESPONSE_DURATION_MS",t[t.IFLOW_CLI_API_ERROR_MESSAGE=24]="IFLOW_CLI_API_ERROR_MESSAGE",t[t.IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT=25]="IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT=26]="IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT=27]="IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT=28]="IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT=29]="IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT",t[t.IFLOW_CLI_API_ERROR_MODEL=30]="IFLOW_CLI_API_ERROR_MODEL",t[t.IFLOW_CLI_API_ERROR_TYPE=31]="IFLOW_CLI_API_ERROR_TYPE",t[t.IFLOW_CLI_API_ERROR_STATUS_CODE=32]="IFLOW_CLI_API_ERROR_STATUS_CODE",t[t.IFLOW_CLI_API_ERROR_DURATION_MS=33]="IFLOW_CLI_API_ERROR_DURATION_MS",t[t.IFLOW_CLI_END_SESSION_ID=34]="IFLOW_CLI_END_SESSION_ID",t[t.IFLOW_CLI_PROMPT_ID=35]="IFLOW_CLI_PROMPT_ID",t[t.IFLOW_CLI_AUTH_TYPE=36]="IFLOW_CLI_AUTH_TYPE",t[t.IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT=37]="IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT",t[t.IFLOW_CLI_SURFACE=39]="IFLOW_CLI_SURFACE",t[t.IFLOW_CLI_SESSION_ID=40]="IFLOW_CLI_SESSION_ID",t[t.IFLOW_CLI_LOOP_DETECTED_TYPE=38]="IFLOW_CLI_LOOP_DETECTED_TYPE",t[t.IFLOW_CLI_SLASH_COMMAND_NAME=41]="IFLOW_CLI_SLASH_COMMAND_NAME",t[t.IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND=42]="IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND",t[t.IFLOW_CLI_RESPONSE_FINISH_REASON=43]="IFLOW_CLI_RESPONSE_FINISH_REASON",t[t.IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT=44]="IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT",t[t.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL=45]="IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL",t[t.IFLOW_CLI_RESPONSE_TYPE=46]="IFLOW_CLI_RESPONSE_TYPE",t[t.IFLOW_CLI_RESPONSE_LENGTH=47]="IFLOW_CLI_RESPONSE_LENGTH",t[t.IFLOW_CLI_RESPONSE_SUCCESS=48]="IFLOW_CLI_RESPONSE_SUCCESS",t[t.IFLOW_CLI_ERROR_MESSAGE=49]="IFLOW_CLI_ERROR_MESSAGE"})(Zn||(Zn={}))});function pU(t,e){let r=new WeakSet;return JSON.stringify(t,(n,o)=>{if(typeof o=="object"&&o!==null){if(r.has(o))return"[Circular]";r.add(o)}return o},e)}var DNe=te(()=>{"use strict";});import Qx,{dirname as Auo,join as K_t}from"node:path";import RNe from"os";import*as nBr from"crypto";import{fileURLToPath as yuo}from"node:url";import _uo from"node:fs";import{execSync as Euo}from"node:child_process";function jx(t){let e=RNe.homedir();return t.startsWith(e)?t.replace(e,"~"):t}function Il(t,e=35){if(t.length<=e)return t;let n=Qx.parse(t).root,o=Qx.sep,a=t.substring(n.length).split(o).filter(m=>m!=="");if(a.length<=1){let m=Math.floor((e-3)/2);if(m<=0)return t.substring(0,e-3)+"...";let g=t.substring(0,m),A=t.substring(t.length-m);return`${g}...${A}`}let c=a[0],u=a[a.length-1],d=n+c,f=[],p=o.length+u.length;for(let m=a.length-2;m>=0;m--){let g=a[m],A=p+o.length+g.length;if(A<=e)f.unshift(g),p=A;else break}let h=f.join(o)+o+u;return p>e?h:(h=d+o+h,h.length>e?"..."+h.substring(h.length-e-3):h)}function Ap(t,e){let r=Qx.resolve(t),n=Qx.resolve(e);return Qx.relative(n,r)||"."}function OX(t){let e="";for(let r=0;r<t.length;r++)t[r]===" "&&(r===0||t[r-1]!=="\\")?e+="\\ ":e+=t[r];return e}function G9(t){return process.platform==="win32"?t.replace(/\\([ ,;!?()[\]{}])/g,"$1"):t.replace(/\\(.)/g,"$1")}function NNe(t){return nBr.createHash("sha256").update(t).digest("hex")}function n1(t){let e=NNe(t);return Qx.join(RNe.homedir(),Ym,vuo,e)}function ONe(){return Qx.join(RNe.homedir(),Ym,iBr)}function kNe(t){return Qx.join(t,Ym,iBr)}function BNe(){if(process.env.USE_BUILTIN_RIPGREP==="0")return"rg";let t=Auo(yuo(import.meta.url)),e=[K_t(t,"..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),K_t(t,"..","..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),K_t(t,"..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`)];for(let r of e)try{if(_uo.existsSync(r))return process.platform==="darwin"&&oBr(r),r}catch{}return e[0]}function oBr(t){if(process.platform==="darwin")try{let e=["com.apple.quarantine","CachedFileMimeType","CachedFileType","FileXRayCachedResultInEA"];for(let r of e)try{Euo(`xattr -d "${r}" "${t}" 2>/dev/null`,{stdio:"ignore"})}catch{}}catch{}}function Ope(t,e){let n=RNe.platform()==="win32"?Qx.win32:Qx,o=n.relative(t,e);return!o.startsWith(`..${n.sep}`)&&o!==".."&&!n.isAbsolute(o)}var Ym,X_t,vuo,iBr,of=te(()=>{"use strict";Ym=".iflow",X_t="google_accounts.json",vuo="tmp",iBr="commands"});import buo from"node:path";import{promises as YLa,existsSync as sBr,readFileSync as aBr}from"node:fs";import*as cBr from"os";function lBr(){return buo.join(cBr.homedir(),Ym,X_t)}function uBr(){try{let t=lBr();if(sBr(t)){let e=aBr(t,"utf-8").trim();return e?JSON.parse(e).active:null}return null}catch(t){return console.debug("Error reading cached Google Account:",t),null}}function dBr(){try{let t=lBr();if(!sBr(t))return 0;let e=aBr(t,"utf-8").trim();if(!e)return 0;let r=JSON.parse(e);if(!r||typeof r!="object")return 0;let n=r,o=n.old&&Array.isArray(n.old)?n.old.length:0;return n.active&&o++,o}catch(t){return console.debug("Error reading lifetime Google Accounts:",t),0}}var fBr=te(()=>{"use strict";of();});import*as pBr from"os";import*as $9 from"fs";import*as eEt from"path";import{randomUUID as Cuo}from"crypto";function xuo(){$9.existsSync(J_t)||$9.mkdirSync(J_t,{recursive:!0})}function wuo(){return $9.existsSync(Z_t)&&$9.readFileSync(Z_t,"utf-8").trim()||null}function Tuo(t){$9.writeFileSync(Z_t,t,"utf-8")}function PNe(){try{xuo();let t=wuo();return t||(t=Cuo(),Tuo(t)),t}catch(t){return console.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}var Suo,J_t,Z_t,tEt=te(()=>{"use strict";of();Suo=pBr.homedir()??"",J_t=eEt.join(Suo,Ym),Z_t=eEt.join(J_t,"installation_id")});var hBr,Iuo,Duo,Ruo,Nuo,Ouo,kuo,Buo,Puo,Muo,Fuo,Luo,Uuo,Quo,qh,kpe=te(()=>{"use strict";hBr=Ie(Tlt(),1);LN();rBr();DNe();fBr();tEt();Iuo="start_session",Duo="new_prompt",Ruo="tool_call",Nuo="api_request",Ouo="api_response",kuo="api_error",Buo="end_session",Puo="flash_fallback",Muo="loop_detected",Fuo="next_speaker_check",Luo="slash_command",Uuo="malformed_json_response",Quo="cli_response",qh=class t{static instance;config;events=[];last_flush_time=Date.now();flush_interval_ms=1e3*60;constructor(e){this.config=e}static getInstance(e){if(!(e===void 0||!e?.getUsageStatisticsEnabled()))return t.instance||(t.instance=new t(e)),t.instance}enqueueLogEvent(e){this.events.push([{event_time_ms:Date.now(),source_extension_json:pU(e)}])}createLogEvent(e,r){let n=uBr(),o=dBr();r.push({iflow_cli_key:Zn.IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT,value:o.toString()});let s={console_type:"IFLOW_CLI",application:102,event_name:e,event_metadata:[r]};return n?s.client_email=n:s.client_install_id=PNe(),s}flushIfNeeded(){Date.now()-this.last_flush_time<this.flush_interval_ms||this.flushToClearcut().catch(e=>{console.debug("Error flushing to Clearcut:",e)})}async flushToClearcut(){return this.config?.getDebugMode()&&console.log("Telemetry disabled - not sending log events to Clearcut."),this.events.length=0,this.last_flush_time=Date.now(),Promise.resolve({})}decodeLogResponse(e){if(e.length<1||e.readUInt8(0)!==8)return;let r=BigInt(0),n=!0;for(let s=1;n&&s<e.length;s++){let a=e.readUInt8(s);r|=BigInt(a&127)<<BigInt(7*(s-1)),n=(a&128)!==0}return n?void 0:{nextRequestWaitMs:Number(r)}}handleLogEvent(e,r,n=!1){this.enqueueLogEvent(this.createLogEvent(e,r)),n?this.flushToClearcut().catch(o=>{console.debug("Error flushing to Clearcut:",o)}):this.flushIfNeeded()}logStartSessionEvent(e){let r=process.env.SURFACE||"SURFACE_NOT_SET",n=[{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_MODEL,value:e.model},{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_EMBEDDING_MODEL,value:e.embedding_model},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_SANDBOX,value:e.sandbox_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_CORE_TOOLS,value:e.core_tools_enabled},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_APPROVAL_MODE,value:e.approval_mode},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_API_KEY_ENABLED,value:e.api_key_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED,value:e.debug_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_MCP_SERVERS,value:e.mcp_servers},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED,value:e.telemetry_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED,value:e.telemetry_log_user_prompts_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_SURFACE,value:r}];this.handleLogEvent(Iuo,n,!0)}logNewPromptEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_USER_PROMPT_LENGTH,value:JSON.stringify(e.prompt_length)},{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(Duo,r)}logToolCallEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.function_name)},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_DECISION,value:JSON.stringify(e.decision)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_SUCCESS,value:JSON.stringify(e.success)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_ERROR_MESSAGE,value:JSON.stringify(e.error)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_ERROR_TYPE,value:JSON.stringify(e.error_type)}];this.handleLogEvent(Ruo,r)}logApiRequestEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_API_REQUEST_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)}];this.handleLogEvent(Nuo,r)}logApiResponseEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_STATUS_CODE,value:JSON.stringify(e.status_code)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_MESSAGE,value:JSON.stringify(e.error)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT,value:JSON.stringify(e.input_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT,value:JSON.stringify(e.output_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT,value:JSON.stringify(e.cached_content_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT,value:JSON.stringify(e.thoughts_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT,value:JSON.stringify(e.tool_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(Ouo,r)}logApiErrorEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_TYPE,value:JSON.stringify(e.error_type)},{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_STATUS_CODE,value:JSON.stringify(e.status_code)},{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Zn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(kuo,r)}logFlashFallbackEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)},{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""}];this.handleLogEvent(Puo,r,!0)}logLoopDetectedEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_LOOP_DETECTED_TYPE,value:JSON.stringify(e.loop_type)}];this.handleLogEvent(Muo,r)}logNextSpeakerCheck(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_RESPONSE_FINISH_REASON,value:JSON.stringify(e.finish_reason)},{iflow_cli_key:Zn.IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT,value:JSON.stringify(e.result)},{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""}];this.handleLogEvent(Fuo,r)}logSlashCommandEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_SLASH_COMMAND_NAME,value:JSON.stringify(e.command)}];e.subcommand&&r.push({iflow_cli_key:Zn.IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND,value:JSON.stringify(e.subcommand)}),this.handleLogEvent(Luo,r)}logMalformedJsonResponseEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.handleLogEvent(Uuo,r)}logCliResponseEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_RESPONSE_TYPE,value:JSON.stringify(e.response_type)},{iflow_cli_key:Zn.IFLOW_CLI_RESPONSE_LENGTH,value:JSON.stringify(e.response_length)},{iflow_cli_key:Zn.IFLOW_CLI_RESPONSE_SUCCESS,value:JSON.stringify(e.success)},{iflow_cli_key:Zn.IFLOW_CLI_ERROR_MESSAGE,value:JSON.stringify(e.error)}];this.handleLogEvent(Quo,r)}logEndSessionEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:e?.session_id?.toString()??""}];this.handleLogEvent(Buo,r,!0)}getProxyAgent(){let e=this.config?.getProxy();if(e){if(e.startsWith("http"))return new hBr.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}shutdown(){let e=new SX(this.config);this.logEndSessionEvent(e)}}});import*as mBr from"node:fs";var hU,gBr,Bpe,MNe,FNe,LNe,ABr=te(()=>{"use strict";hU=Ie(pi(),1),gBr=Ie(ex(),1);Bpe=class{writeStream;constructor(e){this.writeStream=mBr.createWriteStream(e,{flags:"a"})}serialize(e){let r=new WeakSet;return JSON.stringify(e,(o,s)=>{if(typeof s=="object"&&s!==null){if(r.has(s))return"[Circular]";r.add(s)}return s},2)+`
|
|
484
|
+
`).find(n=>n.includes("IOPlatformUUID"));if(!e)return;let r=e.split('" = "');if(r.length===2)return r[1].slice(0,-1)}catch(t){yao.diag.debug(`error reading machine id: ${t}`)}}dRe.getMachineId=_ao});var uNr=T(fRe=>{"use strict";Object.defineProperty(fRe,"__esModule",{value:!0});fRe.getMachineId=void 0;var Eao=ve("fs"),vao=(Zt(),vt(ur));async function bao(){let t=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let e of t)try{return(await Eao.promises.readFile(e,{encoding:"utf8"})).trim()}catch(r){vao.diag.debug(`error reading machine id: ${r}`)}}fRe.getMachineId=bao});var fNr=T(pRe=>{"use strict";Object.defineProperty(pRe,"__esModule",{value:!0});pRe.getMachineId=void 0;var Cao=ve("fs"),Sao=uRe(),dNr=(Zt(),vt(ur));async function xao(){try{return(await Cao.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(t){dNr.diag.debug(`error reading machine id: ${t}`)}try{return(await(0,Sao.execAsync)("kenv -q smbios.system.uuid")).stdout.trim()}catch(t){dNr.diag.debug(`error reading machine id: ${t}`)}}pRe.getMachineId=xao});var hNr=T(hRe=>{"use strict";Object.defineProperty(hRe,"__esModule",{value:!0});hRe.getMachineId=void 0;var pNr=ve("process"),wao=uRe(),Tao=(Zt(),vt(ur));async function Iao(){let t="QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",e="%windir%\\System32\\REG.exe";pNr.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in pNr.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{let n=(await(0,wao.execAsync)(`${e} ${t}`)).stdout.split("REG_SZ");if(n.length===2)return n[1].trim()}catch(r){Tao.diag.debug(`error reading machine id: ${r}`)}}hRe.getMachineId=Iao});var mNr=T(mRe=>{"use strict";Object.defineProperty(mRe,"__esModule",{value:!0});mRe.getMachineId=void 0;var Dao=(Zt(),vt(ur));async function Rao(){Dao.diag.debug("could not read machine-id: unsupported platform")}mRe.getMachineId=Rao});var gNr=T(gRe=>{"use strict";Object.defineProperty(gRe,"__esModule",{value:!0});gRe.getMachineId=void 0;var Nao=ve("process"),nU;async function Oao(){if(!nU)switch(Nao.platform){case"darwin":nU=(await Promise.resolve().then(()=>Ie(lNr()))).getMachineId;break;case"linux":nU=(await Promise.resolve().then(()=>Ie(uNr()))).getMachineId;break;case"freebsd":nU=(await Promise.resolve().then(()=>Ie(fNr()))).getMachineId;break;case"win32":nU=(await Promise.resolve().then(()=>Ie(hNr()))).getMachineId;break;default:nU=(await Promise.resolve().then(()=>Ie(mNr()))).getMachineId;break}return nU()}gRe.getMachineId=Oao});var Nyt=T(ZK=>{"use strict";Object.defineProperty(ZK,"__esModule",{value:!0});ZK.normalizeType=ZK.normalizeArch=void 0;var kao=t=>{switch(t){case"arm":return"arm32";case"ppc":return"ppc32";case"x64":return"amd64";default:return t}};ZK.normalizeArch=kao;var Bao=t=>{switch(t){case"sunos":return"solaris";case"win32":return"windows";default:return t}};ZK.normalizeType=Bao});var yNr=T(ARe=>{"use strict";Object.defineProperty(ARe,"__esModule",{value:!0});ARe.hostDetector=void 0;var Oyt=Epe(),ANr=ve("os"),Pao=gNr(),Mao=Nyt(),kyt=class{detect(e){return{attributes:{[Oyt.ATTR_HOST_NAME]:(0,ANr.hostname)(),[Oyt.ATTR_HOST_ARCH]:(0,Mao.normalizeArch)((0,ANr.arch)()),[Oyt.ATTR_HOST_ID]:(0,Pao.getMachineId)()}}}};ARe.hostDetector=new kyt});var vNr=T(yRe=>{"use strict";Object.defineProperty(yRe,"__esModule",{value:!0});yRe.osDetector=void 0;var _Nr=Epe(),ENr=ve("os"),Fao=Nyt(),Byt=class{detect(e){return{attributes:{[_Nr.ATTR_OS_TYPE]:(0,Fao.normalizeType)((0,ENr.platform)()),[_Nr.ATTR_OS_VERSION]:(0,ENr.release)()}}}};yRe.osDetector=new Byt});var bNr=T(_Re=>{"use strict";Object.defineProperty(_Re,"__esModule",{value:!0});_Re.processDetector=void 0;var Lao=(Zt(),vt(ur)),L9=Epe(),Uao=ve("os"),Pyt=class{detect(e){let r={[L9.ATTR_PROCESS_PID]:process.pid,[L9.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[L9.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[L9.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[L9.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[L9.ATTR_PROCESS_RUNTIME_NAME]:"nodejs",[L9.ATTR_PROCESS_RUNTIME_DESCRIPTION]:"Node.js"};process.argv.length>1&&(r[L9.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let n=Uao.userInfo();r[L9.ATTR_PROCESS_OWNER]=n.username}catch(n){Lao.diag.debug(`error obtaining process owner: ${n}`)}return{attributes:r}}};_Re.processDetector=new Pyt});var CNr=T(ERe=>{"use strict";Object.defineProperty(ERe,"__esModule",{value:!0});ERe.serviceInstanceIdDetector=void 0;var Qao=Epe(),jao=ve("crypto"),Myt=class{detect(e){return{attributes:{[Qao.ATTR_SERVICE_INSTANCE_ID]:(0,jao.randomUUID)()}}}};ERe.serviceInstanceIdDetector=new Myt});var SNr=T(Px=>{"use strict";Object.defineProperty(Px,"__esModule",{value:!0});Px.serviceInstanceIdDetector=Px.processDetector=Px.osDetector=Px.hostDetector=void 0;var Gao=yNr();Object.defineProperty(Px,"hostDetector",{enumerable:!0,get:function(){return Gao.hostDetector}});var $ao=vNr();Object.defineProperty(Px,"osDetector",{enumerable:!0,get:function(){return $ao.osDetector}});var qao=bNr();Object.defineProperty(Px,"processDetector",{enumerable:!0,get:function(){return qao.processDetector}});var Hao=CNr();Object.defineProperty(Px,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return Hao.serviceInstanceIdDetector}})});var xNr=T(Mx=>{"use strict";Object.defineProperty(Mx,"__esModule",{value:!0});Mx.serviceInstanceIdDetector=Mx.processDetector=Mx.osDetector=Mx.hostDetector=void 0;var vRe=SNr();Object.defineProperty(Mx,"hostDetector",{enumerable:!0,get:function(){return vRe.hostDetector}});Object.defineProperty(Mx,"osDetector",{enumerable:!0,get:function(){return vRe.osDetector}});Object.defineProperty(Mx,"processDetector",{enumerable:!0,get:function(){return vRe.processDetector}});Object.defineProperty(Mx,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return vRe.serviceInstanceIdDetector}})});var wNr=T(eX=>{"use strict";Object.defineProperty(eX,"__esModule",{value:!0});eX.noopDetector=eX.NoopDetector=void 0;var bRe=class{detect(){return{attributes:{}}}};eX.NoopDetector=bRe;eX.noopDetector=new bRe});var TNr=T(N3=>{"use strict";Object.defineProperty(N3,"__esModule",{value:!0});N3.noopDetector=N3.serviceInstanceIdDetector=N3.processDetector=N3.osDetector=N3.hostDetector=N3.envDetector=void 0;var Vao=cNr();Object.defineProperty(N3,"envDetector",{enumerable:!0,get:function(){return Vao.envDetector}});var CRe=xNr();Object.defineProperty(N3,"hostDetector",{enumerable:!0,get:function(){return CRe.hostDetector}});Object.defineProperty(N3,"osDetector",{enumerable:!0,get:function(){return CRe.osDetector}});Object.defineProperty(N3,"processDetector",{enumerable:!0,get:function(){return CRe.processDetector}});Object.defineProperty(N3,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return CRe.serviceInstanceIdDetector}});var Wao=wNr();Object.defineProperty(N3,"noopDetector",{enumerable:!0,get:function(){return Wao.noopDetector}})});var Lyt=T(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});Ff.defaultServiceName=Ff.emptyResource=Ff.defaultResource=Ff.resourceFromAttributes=Ff.serviceInstanceIdDetector=Ff.processDetector=Ff.osDetector=Ff.hostDetector=Ff.envDetector=Ff.detectResources=void 0;var zao=sNr();Object.defineProperty(Ff,"detectResources",{enumerable:!0,get:function(){return zao.detectResources}});var vpe=TNr();Object.defineProperty(Ff,"envDetector",{enumerable:!0,get:function(){return vpe.envDetector}});Object.defineProperty(Ff,"hostDetector",{enumerable:!0,get:function(){return vpe.hostDetector}});Object.defineProperty(Ff,"osDetector",{enumerable:!0,get:function(){return vpe.osDetector}});Object.defineProperty(Ff,"processDetector",{enumerable:!0,get:function(){return vpe.processDetector}});Object.defineProperty(Ff,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return vpe.serviceInstanceIdDetector}});var Fyt=Iyt();Object.defineProperty(Ff,"resourceFromAttributes",{enumerable:!0,get:function(){return Fyt.resourceFromAttributes}});Object.defineProperty(Ff,"defaultResource",{enumerable:!0,get:function(){return Fyt.defaultResource}});Object.defineProperty(Ff,"emptyResource",{enumerable:!0,get:function(){return Fyt.emptyResource}});var Yao=xyt();Object.defineProperty(Ff,"defaultServiceName",{enumerable:!0,get:function(){return Yao.defaultServiceName}})});var INr=T(bpe=>{"use strict";Object.defineProperty(bpe,"__esModule",{value:!0});bpe.SeverityNumber=void 0;var Kao;(function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.TRACE=1]="TRACE",t[t.TRACE2=2]="TRACE2",t[t.TRACE3=3]="TRACE3",t[t.TRACE4=4]="TRACE4",t[t.DEBUG=5]="DEBUG",t[t.DEBUG2=6]="DEBUG2",t[t.DEBUG3=7]="DEBUG3",t[t.DEBUG4=8]="DEBUG4",t[t.INFO=9]="INFO",t[t.INFO2=10]="INFO2",t[t.INFO3=11]="INFO3",t[t.INFO4=12]="INFO4",t[t.WARN=13]="WARN",t[t.WARN2=14]="WARN2",t[t.WARN3=15]="WARN3",t[t.WARN4=16]="WARN4",t[t.ERROR=17]="ERROR",t[t.ERROR2=18]="ERROR2",t[t.ERROR3=19]="ERROR3",t[t.ERROR4=20]="ERROR4",t[t.FATAL=21]="FATAL",t[t.FATAL2=22]="FATAL2",t[t.FATAL3=23]="FATAL3",t[t.FATAL4=24]="FATAL4"})(Kao=bpe.SeverityNumber||(bpe.SeverityNumber={}))});var xRe=T(tX=>{"use strict";Object.defineProperty(tX,"__esModule",{value:!0});tX.NOOP_LOGGER=tX.NoopLogger=void 0;var SRe=class{emit(e){}};tX.NoopLogger=SRe;tX.NOOP_LOGGER=new SRe});var TRe=T(rX=>{"use strict";Object.defineProperty(rX,"__esModule",{value:!0});rX.NOOP_LOGGER_PROVIDER=rX.NoopLoggerProvider=void 0;var Xao=xRe(),wRe=class{getLogger(e,r,n){return new Xao.NoopLogger}};rX.NoopLoggerProvider=wRe;rX.NOOP_LOGGER_PROVIDER=new wRe});var Qyt=T(IRe=>{"use strict";Object.defineProperty(IRe,"__esModule",{value:!0});IRe.ProxyLogger=void 0;var Jao=xRe(),Uyt=class{constructor(e,r,n,o){this._provider=e,this.name=r,this.version=n,this.options=o}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;let e=this._provider._getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Jao.NOOP_LOGGER}};IRe.ProxyLogger=Uyt});var Gyt=T(DRe=>{"use strict";Object.defineProperty(DRe,"__esModule",{value:!0});DRe.ProxyLoggerProvider=void 0;var Zao=TRe(),eco=Qyt(),jyt=class{getLogger(e,r,n){var o;return(o=this._getDelegateLogger(e,r,n))!==null&&o!==void 0?o:new eco.ProxyLogger(this,e,r,n)}_getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Zao.NOOP_LOGGER_PROVIDER}_setDelegate(e){this._delegate=e}_getDelegateLogger(e,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getLogger(e,r,n)}};DRe.ProxyLoggerProvider=jyt});var DNr=T(RRe=>{"use strict";Object.defineProperty(RRe,"__esModule",{value:!0});RRe._globalThis=void 0;RRe._globalThis=typeof globalThis=="object"?globalThis:global});var RNr=T(NRe=>{"use strict";Object.defineProperty(NRe,"__esModule",{value:!0});NRe._globalThis=void 0;var tco=DNr();Object.defineProperty(NRe,"_globalThis",{enumerable:!0,get:function(){return tco._globalThis}})});var NNr=T(ORe=>{"use strict";Object.defineProperty(ORe,"__esModule",{value:!0});ORe._globalThis=void 0;var rco=RNr();Object.defineProperty(ORe,"_globalThis",{enumerable:!0,get:function(){return rco._globalThis}})});var ONr=T(Fx=>{"use strict";Object.defineProperty(Fx,"__esModule",{value:!0});Fx.API_BACKWARDS_COMPATIBILITY_VERSION=Fx.makeGetter=Fx._global=Fx.GLOBAL_LOGS_API_KEY=void 0;var nco=NNr();Fx.GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs");Fx._global=nco._globalThis;function ico(t,e,r){return n=>n===t?e:r}Fx.makeGetter=ico;Fx.API_BACKWARDS_COMPATIBILITY_VERSION=1});var BNr=T(kRe=>{"use strict";Object.defineProperty(kRe,"__esModule",{value:!0});kRe.LogsAPI=void 0;var nv=ONr(),oco=TRe(),kNr=Gyt(),$yt=class t{constructor(){this._proxyLoggerProvider=new kNr.ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalLoggerProvider(e){return nv._global[nv.GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(nv._global[nv.GLOBAL_LOGS_API_KEY]=(0,nv.makeGetter)(nv.API_BACKWARDS_COMPATIBILITY_VERSION,e,oco.NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider._setDelegate(e),e)}getLoggerProvider(){var e,r;return(r=(e=nv._global[nv.GLOBAL_LOGS_API_KEY])===null||e===void 0?void 0:e.call(nv._global,nv.API_BACKWARDS_COMPATIBILITY_VERSION))!==null&&r!==void 0?r:this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){delete nv._global[nv.GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new kNr.ProxyLoggerProvider}};kRe.LogsAPI=$yt});var FNr=T(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});zm.logs=zm.ProxyLoggerProvider=zm.ProxyLogger=zm.NoopLoggerProvider=zm.NOOP_LOGGER_PROVIDER=zm.NoopLogger=zm.NOOP_LOGGER=zm.SeverityNumber=void 0;var sco=INr();Object.defineProperty(zm,"SeverityNumber",{enumerable:!0,get:function(){return sco.SeverityNumber}});var PNr=xRe();Object.defineProperty(zm,"NOOP_LOGGER",{enumerable:!0,get:function(){return PNr.NOOP_LOGGER}});Object.defineProperty(zm,"NoopLogger",{enumerable:!0,get:function(){return PNr.NoopLogger}});var MNr=TRe();Object.defineProperty(zm,"NOOP_LOGGER_PROVIDER",{enumerable:!0,get:function(){return MNr.NOOP_LOGGER_PROVIDER}});Object.defineProperty(zm,"NoopLoggerProvider",{enumerable:!0,get:function(){return MNr.NoopLoggerProvider}});var aco=Qyt();Object.defineProperty(zm,"ProxyLogger",{enumerable:!0,get:function(){return aco.ProxyLogger}});var cco=Gyt();Object.defineProperty(zm,"ProxyLoggerProvider",{enumerable:!0,get:function(){return cco.ProxyLoggerProvider}});var lco=BNr();zm.logs=lco.LogsAPI.getInstance()});var Cpe=T(MN=>{"use strict";Object.defineProperty(MN,"__esModule",{value:!0});MN.isTracingSuppressed=MN.unsuppressTracing=MN.suppressTracing=void 0;var uco=(Zt(),vt(ur)),qyt=(0,uco.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function dco(t){return t.setValue(qyt,!0)}MN.suppressTracing=dco;function fco(t){return t.deleteValue(qyt)}MN.unsuppressTracing=fco;function pco(t){return t.getValue(qyt)===!0}MN.isTracingSuppressed=pco});var Hyt=T(xA=>{"use strict";Object.defineProperty(xA,"__esModule",{value:!0});xA.BAGGAGE_MAX_TOTAL_LENGTH=xA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=xA.BAGGAGE_MAX_NAME_VALUE_PAIRS=xA.BAGGAGE_HEADER=xA.BAGGAGE_ITEMS_SEPARATOR=xA.BAGGAGE_PROPERTIES_SEPARATOR=xA.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;xA.BAGGAGE_KEY_PAIR_SEPARATOR="=";xA.BAGGAGE_PROPERTIES_SEPARATOR=";";xA.BAGGAGE_ITEMS_SEPARATOR=",";xA.BAGGAGE_HEADER="baggage";xA.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;xA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;xA.BAGGAGE_MAX_TOTAL_LENGTH=8192});var Vyt=T(Lx=>{"use strict";Object.defineProperty(Lx,"__esModule",{value:!0});Lx.parseKeyPairsIntoRecord=Lx.parsePairKeyValue=Lx.getKeyPairs=Lx.serializeKeyPairs=void 0;var hco=(Zt(),vt(ur)),iU=Hyt();function mco(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?iU.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>iU.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}Lx.serializeKeyPairs=mco;function gco(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=iU.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}Lx.getKeyPairs=gco;function LNr(t){let e=t.split(iU.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(iU.BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;let o=decodeURIComponent(r.substring(0,n).trim()),s=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=(0,hco.baggageEntryMetadataFromString)(e.join(iU.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:a}}Lx.parsePairKeyValue=LNr;function Aco(t){let e={};return typeof t=="string"&&t.length>0&&t.split(iU.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=LNr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}Lx.parseKeyPairsIntoRecord=Aco});var UNr=T(BRe=>{"use strict";Object.defineProperty(BRe,"__esModule",{value:!0});BRe.W3CBaggagePropagator=void 0;var Wyt=(Zt(),vt(ur)),yco=Cpe(),oU=Hyt(),zyt=Vyt(),Yyt=class{inject(e,r,n){let o=Wyt.propagation.getBaggage(e);if(!o||(0,yco.isTracingSuppressed)(e))return;let s=(0,zyt.getKeyPairs)(o).filter(c=>c.length<=oU.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,oU.BAGGAGE_MAX_NAME_VALUE_PAIRS),a=(0,zyt.serializeKeyPairs)(s);a.length>0&&n.set(r,oU.BAGGAGE_HEADER,a)}extract(e,r,n){let o=n.get(r,oU.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(oU.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let a={};return s.length===0||(s.split(oU.BAGGAGE_ITEMS_SEPARATOR).forEach(u=>{let d=(0,zyt.parsePairKeyValue)(u);if(d){let f={value:d.value};d.metadata&&(f.metadata=d.metadata),a[d.key]=f}}),Object.entries(a).length===0)?e:Wyt.propagation.setBaggage(e,Wyt.propagation.createBaggage(a))}fields(){return[oU.BAGGAGE_HEADER]}};BRe.W3CBaggagePropagator=Yyt});var QNr=T(PRe=>{"use strict";Object.defineProperty(PRe,"__esModule",{value:!0});PRe.AnchoredClock=void 0;var Kyt=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,r){this._monotonicClock=r,this._epochMillis=e.now(),this._performanceMillis=r.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}};PRe.AnchoredClock=Kyt});var HNr=T(FN=>{"use strict";Object.defineProperty(FN,"__esModule",{value:!0});FN.isAttributeValue=FN.isAttributeKey=FN.sanitizeAttributes=void 0;var jNr=(Zt(),vt(ur));function _co(t){let e={};if(typeof t!="object"||t==null)return e;for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;if(!GNr(r)){jNr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!$Nr(n)){jNr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}FN.sanitizeAttributes=_co;function GNr(t){return typeof t=="string"&&t!==""}FN.isAttributeKey=GNr;function $Nr(t){return t==null?!0:Array.isArray(t)?Eco(t):qNr(typeof t)}FN.isAttributeValue=$Nr;function Eco(t){let e;for(let r of t){if(r==null)continue;let n=typeof r;if(n!==e){if(!e){if(qNr(n)){e=n;continue}return!1}return!1}}return!0}function qNr(t){switch(t){case"number":case"boolean":case"string":return!0}return!1}});var Xyt=T(MRe=>{"use strict";Object.defineProperty(MRe,"__esModule",{value:!0});MRe.loggingErrorHandler=void 0;var vco=(Zt(),vt(ur));function bco(){return t=>{vco.diag.error(Cco(t))}}MRe.loggingErrorHandler=bco;function Cco(t){return typeof t=="string"?t:JSON.stringify(Sco(t))}function Sco(t){let e={},r=t;for(;r!==null;)Object.getOwnPropertyNames(r).forEach(n=>{if(e[n])return;let o=r[n];o&&(e[n]=String(o))}),r=Object.getPrototypeOf(r);return e}});var WNr=T(nX=>{"use strict";Object.defineProperty(nX,"__esModule",{value:!0});nX.globalErrorHandler=nX.setGlobalErrorHandler=void 0;var xco=Xyt(),VNr=(0,xco.loggingErrorHandler)();function wco(t){VNr=t}nX.setGlobalErrorHandler=wco;function Tco(t){try{VNr(t)}catch{}}nX.globalErrorHandler=Tco});var XNr=T(Ux=>{"use strict";Object.defineProperty(Ux,"__esModule",{value:!0});Ux.getStringListFromEnv=Ux.getBooleanFromEnv=Ux.getStringFromEnv=Ux.getNumberFromEnv=void 0;var zNr=(Zt(),vt(ur)),YNr=ve("util");function Ico(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){zNr.diag.warn(`Unknown value ${(0,YNr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}Ux.getNumberFromEnv=Ico;function KNr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}Ux.getStringFromEnv=KNr;function Dco(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||zNr.diag.warn(`Unknown value ${(0,YNr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}Ux.getBooleanFromEnv=Dco;function Rco(t){return KNr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}Ux.getStringListFromEnv=Rco});var JNr=T(FRe=>{"use strict";Object.defineProperty(FRe,"__esModule",{value:!0});FRe._globalThis=void 0;FRe._globalThis=typeof globalThis=="object"?globalThis:global});var ZNr=T(LRe=>{"use strict";Object.defineProperty(LRe,"__esModule",{value:!0});LRe.otperformance=void 0;var Nco=ve("perf_hooks");LRe.otperformance=Nco.performance});var eOr=T(URe=>{"use strict";Object.defineProperty(URe,"__esModule",{value:!0});URe.VERSION=void 0;URe.VERSION="2.2.0"});var tOr=T(QRe=>{"use strict";Object.defineProperty(QRe,"__esModule",{value:!0});QRe.ATTR_PROCESS_RUNTIME_NAME=void 0;QRe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var rOr=T(GRe=>{"use strict";Object.defineProperty(GRe,"__esModule",{value:!0});GRe.SDK_INFO=void 0;var Oco=eOr(),jRe=(jh(),vt(gA)),kco=tOr();GRe.SDK_INFO={[jRe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[kco.ATTR_PROCESS_RUNTIME_NAME]:"node",[jRe.ATTR_TELEMETRY_SDK_LANGUAGE]:jRe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[jRe.ATTR_TELEMETRY_SDK_VERSION]:Oco.VERSION}});var nOr=T(wA=>{"use strict";Object.defineProperty(wA,"__esModule",{value:!0});wA.SDK_INFO=wA.otperformance=wA._globalThis=wA.getStringListFromEnv=wA.getNumberFromEnv=wA.getBooleanFromEnv=wA.getStringFromEnv=void 0;var $Re=XNr();Object.defineProperty(wA,"getStringFromEnv",{enumerable:!0,get:function(){return $Re.getStringFromEnv}});Object.defineProperty(wA,"getBooleanFromEnv",{enumerable:!0,get:function(){return $Re.getBooleanFromEnv}});Object.defineProperty(wA,"getNumberFromEnv",{enumerable:!0,get:function(){return $Re.getNumberFromEnv}});Object.defineProperty(wA,"getStringListFromEnv",{enumerable:!0,get:function(){return $Re.getStringListFromEnv}});var Bco=JNr();Object.defineProperty(wA,"_globalThis",{enumerable:!0,get:function(){return Bco._globalThis}});var Pco=ZNr();Object.defineProperty(wA,"otperformance",{enumerable:!0,get:function(){return Pco.otperformance}});var Mco=rOr();Object.defineProperty(wA,"SDK_INFO",{enumerable:!0,get:function(){return Mco.SDK_INFO}})});var Jyt=T(TA=>{"use strict";Object.defineProperty(TA,"__esModule",{value:!0});TA.getStringListFromEnv=TA.getNumberFromEnv=TA.getStringFromEnv=TA.getBooleanFromEnv=TA.otperformance=TA._globalThis=TA.SDK_INFO=void 0;var sU=nOr();Object.defineProperty(TA,"SDK_INFO",{enumerable:!0,get:function(){return sU.SDK_INFO}});Object.defineProperty(TA,"_globalThis",{enumerable:!0,get:function(){return sU._globalThis}});Object.defineProperty(TA,"otperformance",{enumerable:!0,get:function(){return sU.otperformance}});Object.defineProperty(TA,"getBooleanFromEnv",{enumerable:!0,get:function(){return sU.getBooleanFromEnv}});Object.defineProperty(TA,"getStringFromEnv",{enumerable:!0,get:function(){return sU.getStringFromEnv}});Object.defineProperty(TA,"getNumberFromEnv",{enumerable:!0,get:function(){return sU.getNumberFromEnv}});Object.defineProperty(TA,"getStringListFromEnv",{enumerable:!0,get:function(){return sU.getStringListFromEnv}})});var aOr=T(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.addHrTimes=Su.isTimeInput=Su.isTimeInputHrTime=Su.hrTimeToMicroseconds=Su.hrTimeToMilliseconds=Su.hrTimeToNanoseconds=Su.hrTimeToTimeStamp=Su.hrTimeDuration=Su.timeInputToHrTime=Su.hrTime=Su.getTimeOrigin=Su.millisToHrTime=void 0;var Zyt=Jyt(),iOr=9,Fco=6,Lco=Math.pow(10,Fco),qRe=Math.pow(10,iOr);function Spe(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Lco);return[r,n]}Su.millisToHrTime=Spe;function e_t(){let t=Zyt.otperformance.timeOrigin;if(typeof t!="number"){let e=Zyt.otperformance;t=e.timing&&e.timing.fetchStart}return t}Su.getTimeOrigin=e_t;function oOr(t){let e=Spe(e_t()),r=Spe(typeof t=="number"?t:Zyt.otperformance.now());return sOr(e,r)}Su.hrTime=oOr;function Uco(t){if(t_t(t))return t;if(typeof t=="number")return t<e_t()?oOr(t):Spe(t);if(t instanceof Date)return Spe(t.getTime());throw TypeError("Invalid input type")}Su.timeInputToHrTime=Uco;function Qco(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=qRe),[r,n]}Su.hrTimeDuration=Qco;function jco(t){let e=iOr,r=`${"0".repeat(e)}${t[1]}Z`,n=r.substring(r.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",n)}Su.hrTimeToTimeStamp=jco;function Gco(t){return t[0]*qRe+t[1]}Su.hrTimeToNanoseconds=Gco;function $co(t){return t[0]*1e3+t[1]/1e6}Su.hrTimeToMilliseconds=$co;function qco(t){return t[0]*1e6+t[1]/1e3}Su.hrTimeToMicroseconds=qco;function t_t(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}Su.isTimeInputHrTime=t_t;function Hco(t){return t_t(t)||typeof t=="number"||t instanceof Date}Su.isTimeInput=Hco;function sOr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=qRe&&(r[1]-=qRe,r[0]+=1),r}Su.addHrTimes=sOr});var cOr=T(HRe=>{"use strict";Object.defineProperty(HRe,"__esModule",{value:!0});HRe.unrefTimer=void 0;function Vco(t){typeof t!="number"&&t.unref()}HRe.unrefTimer=Vco});var lOr=T(xpe=>{"use strict";Object.defineProperty(xpe,"__esModule",{value:!0});xpe.ExportResultCode=void 0;var Wco;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Wco=xpe.ExportResultCode||(xpe.ExportResultCode={}))});var dOr=T(VRe=>{"use strict";Object.defineProperty(VRe,"__esModule",{value:!0});VRe.CompositePropagator=void 0;var uOr=(Zt(),vt(ur)),r_t=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(r=>typeof r.fields=="function"?r.fields():[]).reduce((r,n)=>r.concat(n),[])))}inject(e,r,n){for(let o of this._propagators)try{o.inject(e,r,n)}catch(s){uOr.diag.warn(`Failed to inject with ${o.constructor.name}. Err: ${s.message}`)}}extract(e,r,n){return this._propagators.reduce((o,s)=>{try{return s.extract(o,r,n)}catch(a){uOr.diag.warn(`Failed to extract with ${s.constructor.name}. Err: ${a.message}`)}return o},e)}fields(){return this._fields.slice()}};VRe.CompositePropagator=r_t});var fOr=T(iX=>{"use strict";Object.defineProperty(iX,"__esModule",{value:!0});iX.validateValue=iX.validateKey=void 0;var n_t="[_0-9a-z-*/]",zco=`[a-z]${n_t}{0,255}`,Yco=`[a-z0-9]${n_t}{0,240}@[a-z]${n_t}{0,13}`,Kco=new RegExp(`^(?:${zco}|${Yco})$`),Xco=/^[ -~]{0,255}[!-~]$/,Jco=/,|=/;function Zco(t){return Kco.test(t)}iX.validateKey=Zco;function elo(t){return Xco.test(t)&&!Jco.test(t)}iX.validateValue=elo});var o_t=T(WRe=>{"use strict";Object.defineProperty(WRe,"__esModule",{value:!0});WRe.TraceState=void 0;var pOr=fOr(),hOr=32,tlo=512,mOr=",",gOr="=",i_t=class t{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,r)=>(e.push(r+gOr+this.get(r)),e),[]).join(mOr)}_parse(e){e.length>tlo||(this._internalState=e.split(mOr).reverse().reduce((r,n)=>{let o=n.trim(),s=o.indexOf(gOr);if(s!==-1){let a=o.slice(0,s),c=o.slice(s+1,n.length);(0,pOr.validateKey)(a)&&(0,pOr.validateValue)(c)&&r.set(a,c)}return r},new Map),this._internalState.size>hOr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,hOr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};WRe.TraceState=i_t});var yOr=T(IA=>{"use strict";Object.defineProperty(IA,"__esModule",{value:!0});IA.W3CTraceContextPropagator=IA.parseTraceParent=IA.TRACE_STATE_HEADER=IA.TRACE_PARENT_HEADER=void 0;var zRe=(Zt(),vt(ur)),rlo=Cpe(),nlo=o_t();IA.TRACE_PARENT_HEADER="traceparent";IA.TRACE_STATE_HEADER="tracestate";var ilo="00",olo="(?!ff)[\\da-f]{2}",slo="(?![0]{32})[\\da-f]{32}",alo="(?![0]{16})[\\da-f]{16}",clo="[\\da-f]{2}",llo=new RegExp(`^\\s?(${olo})-(${slo})-(${alo})-(${clo})(-.*)?\\s?$`);function AOr(t){let e=llo.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}IA.parseTraceParent=AOr;var s_t=class{inject(e,r,n){let o=zRe.trace.getSpanContext(e);if(!o||(0,rlo.isTracingSuppressed)(e)||!(0,zRe.isSpanContextValid)(o))return;let s=`${ilo}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||zRe.TraceFlags.NONE).toString(16)}`;n.set(r,IA.TRACE_PARENT_HEADER,s),o.traceState&&n.set(r,IA.TRACE_STATE_HEADER,o.traceState.serialize())}extract(e,r,n){let o=n.get(r,IA.TRACE_PARENT_HEADER);if(!o)return e;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let a=AOr(s);if(!a)return e;a.isRemote=!0;let c=n.get(r,IA.TRACE_STATE_HEADER);if(c){let u=Array.isArray(c)?c.join(","):c;a.traceState=new nlo.TraceState(typeof u=="string"?u:void 0)}return zRe.trace.setSpanContext(e,a)}fields(){return[IA.TRACE_PARENT_HEADER,IA.TRACE_STATE_HEADER]}};IA.W3CTraceContextPropagator=s_t});var _Or=T(gC=>{"use strict";Object.defineProperty(gC,"__esModule",{value:!0});gC.getRPCMetadata=gC.deleteRPCMetadata=gC.setRPCMetadata=gC.RPCType=void 0;var ulo=(Zt(),vt(ur)),a_t=(0,ulo.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),dlo;(function(t){t.HTTP="http"})(dlo=gC.RPCType||(gC.RPCType={}));function flo(t,e){return t.setValue(a_t,e)}gC.setRPCMetadata=flo;function plo(t){return t.deleteValue(a_t)}gC.deleteRPCMetadata=plo;function hlo(t){return t.getValue(a_t)}gC.getRPCMetadata=hlo});var SOr=T(YRe=>{"use strict";Object.defineProperty(YRe,"__esModule",{value:!0});YRe.isPlainObject=void 0;var mlo="[object Object]",glo="[object Null]",Alo="[object Undefined]",ylo=Function.prototype,EOr=ylo.toString,_lo=EOr.call(Object),Elo=Object.getPrototypeOf,vOr=Object.prototype,bOr=vOr.hasOwnProperty,aU=Symbol?Symbol.toStringTag:void 0,COr=vOr.toString;function vlo(t){if(!blo(t)||Clo(t)!==mlo)return!1;let e=Elo(t);if(e===null)return!0;let r=bOr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&EOr.call(r)===_lo}YRe.isPlainObject=vlo;function blo(t){return t!=null&&typeof t=="object"}function Clo(t){return t==null?t===void 0?Alo:glo:aU&&aU in Object(t)?Slo(t):xlo(t)}function Slo(t){let e=bOr.call(t,aU),r=t[aU],n=!1;try{t[aU]=void 0,n=!0}catch{}let o=COr.call(t);return n&&(e?t[aU]=r:delete t[aU]),o}function xlo(t){return COr.call(t)}});var DOr=T(JRe=>{"use strict";Object.defineProperty(JRe,"__esModule",{value:!0});JRe.merge=void 0;var xOr=SOr(),wlo=20;function Tlo(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=TOr(e,t.shift(),0,r);return e}JRe.merge=Tlo;function c_t(t){return XRe(t)?t.slice():t}function TOr(t,e,r=0,n){let o;if(!(r>wlo)){if(r++,KRe(t)||KRe(e)||IOr(e))o=c_t(e);else if(XRe(t)){if(o=t.slice(),XRe(e))for(let s=0,a=e.length;s<a;s++)o.push(c_t(e[s]));else if(wpe(e)){let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a];o[u]=c_t(e[u])}}}else if(wpe(t))if(wpe(e)){if(!Ilo(t,e))return e;o=Object.assign({},t);let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a],d=e[u];if(KRe(d))typeof d>"u"?delete o[u]:o[u]=d;else{let f=o[u],p=d;if(wOr(t,u,n)||wOr(e,u,n))delete o[u];else{if(wpe(f)&&wpe(p)){let h=n.get(f)||[],m=n.get(p)||[];h.push({obj:t,key:u}),m.push({obj:e,key:u}),n.set(f,h),n.set(p,m)}o[u]=TOr(o[u],d,r,n)}}}}else o=e;return o}}function wOr(t,e,r){let n=r.get(t[e])||[];for(let o=0,s=n.length;o<s;o++){let a=n[o];if(a.key===e&&a.obj===t)return!0}return!1}function XRe(t){return Array.isArray(t)}function IOr(t){return typeof t=="function"}function wpe(t){return!KRe(t)&&!XRe(t)&&!IOr(t)&&typeof t=="object"}function KRe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function Ilo(t,e){return!(!(0,xOr.isPlainObject)(t)||!(0,xOr.isPlainObject)(e))}});var ROr=T(oX=>{"use strict";Object.defineProperty(oX,"__esModule",{value:!0});oX.callWithTimeout=oX.TimeoutError=void 0;var ZRe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};oX.TimeoutError=ZRe;function Dlo(t,e){let r,n=new Promise(function(s,a){r=setTimeout(function(){a(new ZRe("Operation timed out."))},e)});return Promise.race([t,n]).then(o=>(clearTimeout(r),o),o=>{throw clearTimeout(r),o})}oX.callWithTimeout=Dlo});var OOr=T(sX=>{"use strict";Object.defineProperty(sX,"__esModule",{value:!0});sX.isUrlIgnored=sX.urlMatches=void 0;function NOr(t,e){return typeof e=="string"?t===e:!!t.match(e)}sX.urlMatches=NOr;function Rlo(t,e){if(!e)return!1;for(let r of e)if(NOr(t,r))return!0;return!1}sX.isUrlIgnored=Rlo});var kOr=T(eNe=>{"use strict";Object.defineProperty(eNe,"__esModule",{value:!0});eNe.Deferred=void 0;var l_t=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,r)=>{this._resolve=e,this._reject=r})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}};eNe.Deferred=l_t});var BOr=T(tNe=>{"use strict";Object.defineProperty(tNe,"__esModule",{value:!0});tNe.BindOnceFuture=void 0;var Nlo=kOr(),u_t=class{_callback;_that;_isCalled=!1;_deferred=new Nlo.Deferred;constructor(e,r){this._callback=e,this._that=r}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(r=>this._deferred.resolve(r),r=>this._deferred.reject(r))}catch(r){this._deferred.reject(r)}}return this._deferred.promise}};tNe.BindOnceFuture=u_t});var MOr=T(rNe=>{"use strict";Object.defineProperty(rNe,"__esModule",{value:!0});rNe.diagLogLevelFromString=void 0;var U9=(Zt(),vt(ur)),POr={ALL:U9.DiagLogLevel.ALL,VERBOSE:U9.DiagLogLevel.VERBOSE,DEBUG:U9.DiagLogLevel.DEBUG,INFO:U9.DiagLogLevel.INFO,WARN:U9.DiagLogLevel.WARN,ERROR:U9.DiagLogLevel.ERROR,NONE:U9.DiagLogLevel.NONE};function Olo(t){if(t==null)return;let e=POr[t.toUpperCase()];return e??(U9.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys(POr)}, using default`),U9.DiagLogLevel.INFO)}rNe.diagLogLevelFromString=Olo});var LOr=T(nNe=>{"use strict";Object.defineProperty(nNe,"__esModule",{value:!0});nNe._export=void 0;var FOr=(Zt(),vt(ur)),klo=Cpe();function Blo(t,e){return new Promise(r=>{FOr.context.with((0,klo.suppressTracing)(FOr.context.active()),()=>{t.export(e,n=>{r(n)})})})}nNe._export=Blo});var Q9=T(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.internal=Gr.diagLogLevelFromString=Gr.BindOnceFuture=Gr.urlMatches=Gr.isUrlIgnored=Gr.callWithTimeout=Gr.TimeoutError=Gr.merge=Gr.TraceState=Gr.unsuppressTracing=Gr.suppressTracing=Gr.isTracingSuppressed=Gr.setRPCMetadata=Gr.getRPCMetadata=Gr.deleteRPCMetadata=Gr.RPCType=Gr.parseTraceParent=Gr.W3CTraceContextPropagator=Gr.TRACE_STATE_HEADER=Gr.TRACE_PARENT_HEADER=Gr.CompositePropagator=Gr.otperformance=Gr.getStringListFromEnv=Gr.getNumberFromEnv=Gr.getBooleanFromEnv=Gr.getStringFromEnv=Gr._globalThis=Gr.SDK_INFO=Gr.parseKeyPairsIntoRecord=Gr.ExportResultCode=Gr.unrefTimer=Gr.timeInputToHrTime=Gr.millisToHrTime=Gr.isTimeInputHrTime=Gr.isTimeInput=Gr.hrTimeToTimeStamp=Gr.hrTimeToNanoseconds=Gr.hrTimeToMilliseconds=Gr.hrTimeToMicroseconds=Gr.hrTimeDuration=Gr.hrTime=Gr.getTimeOrigin=Gr.addHrTimes=Gr.loggingErrorHandler=Gr.setGlobalErrorHandler=Gr.globalErrorHandler=Gr.sanitizeAttributes=Gr.isAttributeValue=Gr.AnchoredClock=Gr.W3CBaggagePropagator=void 0;var Plo=UNr();Object.defineProperty(Gr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return Plo.W3CBaggagePropagator}});var Mlo=QNr();Object.defineProperty(Gr,"AnchoredClock",{enumerable:!0,get:function(){return Mlo.AnchoredClock}});var UOr=HNr();Object.defineProperty(Gr,"isAttributeValue",{enumerable:!0,get:function(){return UOr.isAttributeValue}});Object.defineProperty(Gr,"sanitizeAttributes",{enumerable:!0,get:function(){return UOr.sanitizeAttributes}});var QOr=WNr();Object.defineProperty(Gr,"globalErrorHandler",{enumerable:!0,get:function(){return QOr.globalErrorHandler}});Object.defineProperty(Gr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return QOr.setGlobalErrorHandler}});var Flo=Xyt();Object.defineProperty(Gr,"loggingErrorHandler",{enumerable:!0,get:function(){return Flo.loggingErrorHandler}});var iv=aOr();Object.defineProperty(Gr,"addHrTimes",{enumerable:!0,get:function(){return iv.addHrTimes}});Object.defineProperty(Gr,"getTimeOrigin",{enumerable:!0,get:function(){return iv.getTimeOrigin}});Object.defineProperty(Gr,"hrTime",{enumerable:!0,get:function(){return iv.hrTime}});Object.defineProperty(Gr,"hrTimeDuration",{enumerable:!0,get:function(){return iv.hrTimeDuration}});Object.defineProperty(Gr,"hrTimeToMicroseconds",{enumerable:!0,get:function(){return iv.hrTimeToMicroseconds}});Object.defineProperty(Gr,"hrTimeToMilliseconds",{enumerable:!0,get:function(){return iv.hrTimeToMilliseconds}});Object.defineProperty(Gr,"hrTimeToNanoseconds",{enumerable:!0,get:function(){return iv.hrTimeToNanoseconds}});Object.defineProperty(Gr,"hrTimeToTimeStamp",{enumerable:!0,get:function(){return iv.hrTimeToTimeStamp}});Object.defineProperty(Gr,"isTimeInput",{enumerable:!0,get:function(){return iv.isTimeInput}});Object.defineProperty(Gr,"isTimeInputHrTime",{enumerable:!0,get:function(){return iv.isTimeInputHrTime}});Object.defineProperty(Gr,"millisToHrTime",{enumerable:!0,get:function(){return iv.millisToHrTime}});Object.defineProperty(Gr,"timeInputToHrTime",{enumerable:!0,get:function(){return iv.timeInputToHrTime}});var Llo=cOr();Object.defineProperty(Gr,"unrefTimer",{enumerable:!0,get:function(){return Llo.unrefTimer}});var Ulo=lOr();Object.defineProperty(Gr,"ExportResultCode",{enumerable:!0,get:function(){return Ulo.ExportResultCode}});var Qlo=Vyt();Object.defineProperty(Gr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return Qlo.parseKeyPairsIntoRecord}});var cU=Jyt();Object.defineProperty(Gr,"SDK_INFO",{enumerable:!0,get:function(){return cU.SDK_INFO}});Object.defineProperty(Gr,"_globalThis",{enumerable:!0,get:function(){return cU._globalThis}});Object.defineProperty(Gr,"getStringFromEnv",{enumerable:!0,get:function(){return cU.getStringFromEnv}});Object.defineProperty(Gr,"getBooleanFromEnv",{enumerable:!0,get:function(){return cU.getBooleanFromEnv}});Object.defineProperty(Gr,"getNumberFromEnv",{enumerable:!0,get:function(){return cU.getNumberFromEnv}});Object.defineProperty(Gr,"getStringListFromEnv",{enumerable:!0,get:function(){return cU.getStringListFromEnv}});Object.defineProperty(Gr,"otperformance",{enumerable:!0,get:function(){return cU.otperformance}});var jlo=dOr();Object.defineProperty(Gr,"CompositePropagator",{enumerable:!0,get:function(){return jlo.CompositePropagator}});var iNe=yOr();Object.defineProperty(Gr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return iNe.TRACE_PARENT_HEADER}});Object.defineProperty(Gr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return iNe.TRACE_STATE_HEADER}});Object.defineProperty(Gr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return iNe.W3CTraceContextPropagator}});Object.defineProperty(Gr,"parseTraceParent",{enumerable:!0,get:function(){return iNe.parseTraceParent}});var oNe=_Or();Object.defineProperty(Gr,"RPCType",{enumerable:!0,get:function(){return oNe.RPCType}});Object.defineProperty(Gr,"deleteRPCMetadata",{enumerable:!0,get:function(){return oNe.deleteRPCMetadata}});Object.defineProperty(Gr,"getRPCMetadata",{enumerable:!0,get:function(){return oNe.getRPCMetadata}});Object.defineProperty(Gr,"setRPCMetadata",{enumerable:!0,get:function(){return oNe.setRPCMetadata}});var d_t=Cpe();Object.defineProperty(Gr,"isTracingSuppressed",{enumerable:!0,get:function(){return d_t.isTracingSuppressed}});Object.defineProperty(Gr,"suppressTracing",{enumerable:!0,get:function(){return d_t.suppressTracing}});Object.defineProperty(Gr,"unsuppressTracing",{enumerable:!0,get:function(){return d_t.unsuppressTracing}});var Glo=o_t();Object.defineProperty(Gr,"TraceState",{enumerable:!0,get:function(){return Glo.TraceState}});var $lo=DOr();Object.defineProperty(Gr,"merge",{enumerable:!0,get:function(){return $lo.merge}});var jOr=ROr();Object.defineProperty(Gr,"TimeoutError",{enumerable:!0,get:function(){return jOr.TimeoutError}});Object.defineProperty(Gr,"callWithTimeout",{enumerable:!0,get:function(){return jOr.callWithTimeout}});var GOr=OOr();Object.defineProperty(Gr,"isUrlIgnored",{enumerable:!0,get:function(){return GOr.isUrlIgnored}});Object.defineProperty(Gr,"urlMatches",{enumerable:!0,get:function(){return GOr.urlMatches}});var qlo=BOr();Object.defineProperty(Gr,"BindOnceFuture",{enumerable:!0,get:function(){return qlo.BindOnceFuture}});var Hlo=MOr();Object.defineProperty(Gr,"diagLogLevelFromString",{enumerable:!0,get:function(){return Hlo.diagLogLevelFromString}});var Vlo=LOr();Gr.internal={_export:Vlo._export}});var $Or=T(aNe=>{"use strict";Object.defineProperty(aNe,"__esModule",{value:!0});aNe.LogRecordImpl=void 0;var lU=(Zt(),vt(ur)),sNe=Q9(),f_t=class{hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;_eventName;totalAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get eventName(){return this._eventName}set eventName(e){this._isLogRecordReadonly()||(this._eventName=e)}get droppedAttributesCount(){return this.totalAttributesCount-Object.keys(this.attributes).length}constructor(e,r,n){let{timestamp:o,observedTimestamp:s,eventName:a,severityNumber:c,severityText:u,body:d,attributes:f={},context:p}=n,h=Date.now();if(this.hrTime=(0,sNe.timeInputToHrTime)(o??h),this.hrTimeObserved=(0,sNe.timeInputToHrTime)(s??h),p){let m=lU.trace.getSpanContext(p);m&&lU.isSpanContextValid(m)&&(this.spanContext=m)}this.severityNumber=c,this.severityText=u,this.body=d,this.resource=e.resource,this.instrumentationScope=r,this._logRecordLimits=e.logRecordLimits,this._eventName=a,this.setAttributes(f)}setAttribute(e,r){return this._isLogRecordReadonly()?this:r===null?this:e.length===0?(lU.diag.warn(`Invalid attribute key: ${e}`),this):!(0,sNe.isAttributeValue)(r)&&!(typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length>0)?(lU.diag.warn(`Invalid attribute value set for key: ${e}`),this):(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this.droppedAttributesCount===1&&lU.diag.warn("Dropping extra attributes."),this):((0,sNe.isAttributeValue)(r)?this.attributes[e]=this._truncateToSize(r):this.attributes[e]=r,this))}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}setBody(e){return this.body=e,this}setEventName(e){return this.eventName=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){let r=this._logRecordLimits.attributeValueLengthLimit;return r<=0?(lU.diag.warn(`Attribute value limit must be positive, got ${r}`),e):typeof e=="string"?this._truncateToLimitUtil(e,r):Array.isArray(e)?e.map(n=>typeof n=="string"?this._truncateToLimitUtil(n,r):n):e}_truncateToLimitUtil(e,r){return e.length<=r?e:e.substring(0,r)}_isLogRecordReadonly(){return this._isReadonly&&lU.diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}};aNe.LogRecordImpl=f_t});var qOr=T(cNe=>{"use strict";Object.defineProperty(cNe,"__esModule",{value:!0});cNe.Logger=void 0;var Wlo=(Zt(),vt(ur)),zlo=$Or(),p_t=class{instrumentationScope;_sharedState;constructor(e,r){this.instrumentationScope=e,this._sharedState=r}emit(e){let r=e.context||Wlo.context.active(),n=new zlo.LogRecordImpl(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(n,r),n._makeReadonly()}};cNe.Logger=p_t});var HOr=T(cX=>{"use strict";Object.defineProperty(cX,"__esModule",{value:!0});cX.reconfigureLimits=cX.loadDefaultConfig=void 0;var aX=Q9();function Ylo(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:(0,aX.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:(0,aX.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??128},includeTraceContext:!0}}cX.loadDefaultConfig=Ylo;function Klo(t){return{attributeCountLimit:t.attributeCountLimit??(0,aX.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??(0,aX.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT")??128,attributeValueLengthLimit:t.attributeValueLengthLimit??(0,aX.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??(0,aX.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0}}cX.reconfigureLimits=Klo});var m_t=T(lNe=>{"use strict";Object.defineProperty(lNe,"__esModule",{value:!0});lNe.NoopLogRecordProcessor=void 0;var h_t=class{forceFlush(){return Promise.resolve()}onEmit(e,r){}shutdown(){return Promise.resolve()}};lNe.NoopLogRecordProcessor=h_t});var VOr=T(uNe=>{"use strict";Object.defineProperty(uNe,"__esModule",{value:!0});uNe.MultiLogRecordProcessor=void 0;var Xlo=Q9(),g_t=class{processors;forceFlushTimeoutMillis;constructor(e,r){this.processors=e,this.forceFlushTimeoutMillis=r}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(r=>(0,Xlo.callWithTimeout)(r.forceFlush(),e)))}onEmit(e,r){this.processors.forEach(n=>n.onEmit(e,r))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}};uNe.MultiLogRecordProcessor=g_t});var WOr=T(dNe=>{"use strict";Object.defineProperty(dNe,"__esModule",{value:!0});dNe.LoggerProviderSharedState=void 0;var Jlo=m_t(),Zlo=VOr(),A_t=class{resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,r,n,o){this.resource=e,this.forceFlushTimeoutMillis=r,this.logRecordLimits=n,this.processors=o,o.length>0?(this.registeredLogRecordProcessors=o,this.activeProcessor=new Zlo.MultiLogRecordProcessor(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new Jlo.NoopLogRecordProcessor}};dNe.LoggerProviderSharedState=A_t});var KOr=T(uU=>{"use strict";Object.defineProperty(uU,"__esModule",{value:!0});uU.LoggerProvider=uU.DEFAULT_LOGGER_NAME=void 0;var fNe=(Zt(),vt(ur)),euo=FNr(),tuo=Lyt(),zOr=Q9(),ruo=qOr(),YOr=HOr(),nuo=WOr();uU.DEFAULT_LOGGER_NAME="unknown";var y_t=class{_shutdownOnce;_sharedState;constructor(e={}){let r=(0,zOr.merge)({},(0,YOr.loadDefaultConfig)(),e),n=e.resource??(0,tuo.defaultResource)();this._sharedState=new nuo.LoggerProviderSharedState(n,r.forceFlushTimeoutMillis,(0,YOr.reconfigureLimits)(r.logRecordLimits),e?.processors??[]),this._shutdownOnce=new zOr.BindOnceFuture(this._shutdown,this)}getLogger(e,r,n){if(this._shutdownOnce.isCalled)return fNe.diag.warn("A shutdown LoggerProvider cannot provide a Logger"),euo.NOOP_LOGGER;e||fNe.diag.warn("Logger requested without instrumentation scope name.");let o=e||uU.DEFAULT_LOGGER_NAME,s=`${o}@${r||""}:${n?.schemaUrl||""}`;return this._sharedState.loggers.has(s)||this._sharedState.loggers.set(s,new ruo.Logger({name:o,version:r,schemaUrl:n?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(s)}forceFlush(){return this._shutdownOnce.isCalled?(fNe.diag.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(fNe.diag.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}};uU.LoggerProvider=y_t});var JOr=T(pNe=>{"use strict";Object.defineProperty(pNe,"__esModule",{value:!0});pNe.ConsoleLogRecordExporter=void 0;var XOr=Q9(),__t=class{export(e,r){this._sendLogRecords(e,r)}shutdown(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:(0,XOr.hrTimeToMicroseconds)(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,body:e.body,attributes:e.attributes}}_sendLogRecords(e,r){for(let n of e)console.dir(this._exportInfo(n),{depth:3});r?.({code:XOr.ExportResultCode.SUCCESS})}};pNe.ConsoleLogRecordExporter=__t});var ZOr=T(hNe=>{"use strict";Object.defineProperty(hNe,"__esModule",{value:!0});hNe.SimpleLogRecordProcessor=void 0;var lX=Q9(),E_t=class{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new lX.BindOnceFuture(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e){if(this._shutdownOnce.isCalled)return;let r=()=>lX.internal._export(this._exporter,[e]).then(n=>{n.code!==lX.ExportResultCode.SUCCESS&&(0,lX.globalErrorHandler)(n.error??new Error(`SimpleLogRecordProcessor: log record export failed (status ${n})`))}).catch(lX.globalErrorHandler);if(e.resource.asyncAttributesPending){let n=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(n),r()),lX.globalErrorHandler);n!=null&&this._unresolvedExports.add(n)}else r()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}};hNe.SimpleLogRecordProcessor=E_t});var tkr=T(mNe=>{"use strict";Object.defineProperty(mNe,"__esModule",{value:!0});mNe.InMemoryLogRecordExporter=void 0;var ekr=Q9(),v_t=class{_finishedLogRecords=[];_stopped=!1;export(e,r){if(this._stopped)return r({code:ekr.ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),r({code:ekr.ExportResultCode.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}};mNe.InMemoryLogRecordExporter=v_t});var rkr=T(gNe=>{"use strict";Object.defineProperty(gNe,"__esModule",{value:!0});gNe.BatchLogRecordProcessorBase=void 0;var iuo=(Zt(),vt(ur)),ov=Q9(),b_t=class{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,r){this._exporter=e,this._maxExportBatchSize=r?.maxExportBatchSize??(0,ov.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=r?.maxQueueSize??(0,ov.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=r?.scheduledDelayMillis??(0,ov.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY")??5e3,this._exportTimeoutMillis=r?.exportTimeoutMillis??(0,ov.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT")??3e4,this._shutdownOnce=new ov.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(iuo.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,r)=>{let n=[],o=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let s=0;s<o;s++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(r)})}_flushOneBatch(){return this._clearTimer(),this._finishedLogRecords.length===0?Promise.resolve():new Promise((e,r)=>{(0,ov.callWithTimeout)(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis).then(()=>e()).catch(r)})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().then(()=>{this._isExporting=!1,this._finishedLogRecords.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(r=>{this._isExporting=!1,(0,ov.globalErrorHandler)(r)})};if(this._finishedLogRecords.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!="number"&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}_export(e){let r=()=>ov.internal._export(this._exporter,e).then(o=>{o.code!==ov.ExportResultCode.SUCCESS&&(0,ov.globalErrorHandler)(o.error??new Error(`BatchLogRecordProcessor: log record export failed (status ${o})`))}).catch(ov.globalErrorHandler),n=e.map(o=>o.resource).filter(o=>o.asyncAttributesPending);return n.length===0?r():Promise.all(n.map(o=>o.waitForAsyncAttributes?.())).then(r,ov.globalErrorHandler)}};gNe.BatchLogRecordProcessorBase=b_t});var nkr=T(ANe=>{"use strict";Object.defineProperty(ANe,"__esModule",{value:!0});ANe.BatchLogRecordProcessor=void 0;var ouo=rkr(),C_t=class extends ouo.BatchLogRecordProcessorBase{onShutdown(){}};ANe.BatchLogRecordProcessor=C_t});var ikr=T(yNe=>{"use strict";Object.defineProperty(yNe,"__esModule",{value:!0});yNe.BatchLogRecordProcessor=void 0;var suo=nkr();Object.defineProperty(yNe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return suo.BatchLogRecordProcessor}})});var okr=T(_Ne=>{"use strict";Object.defineProperty(_Ne,"__esModule",{value:!0});_Ne.BatchLogRecordProcessor=void 0;var auo=ikr();Object.defineProperty(_Ne,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return auo.BatchLogRecordProcessor}})});var skr=T(O3=>{"use strict";Object.defineProperty(O3,"__esModule",{value:!0});O3.BatchLogRecordProcessor=O3.InMemoryLogRecordExporter=O3.SimpleLogRecordProcessor=O3.ConsoleLogRecordExporter=O3.NoopLogRecordProcessor=O3.LoggerProvider=void 0;var cuo=KOr();Object.defineProperty(O3,"LoggerProvider",{enumerable:!0,get:function(){return cuo.LoggerProvider}});var luo=m_t();Object.defineProperty(O3,"NoopLogRecordProcessor",{enumerable:!0,get:function(){return luo.NoopLogRecordProcessor}});var uuo=JOr();Object.defineProperty(O3,"ConsoleLogRecordExporter",{enumerable:!0,get:function(){return uuo.ConsoleLogRecordExporter}});var duo=ZOr();Object.defineProperty(O3,"SimpleLogRecordProcessor",{enumerable:!0,get:function(){return duo.SimpleLogRecordProcessor}});var fuo=tkr();Object.defineProperty(O3,"InMemoryLogRecordExporter",{enumerable:!0,get:function(){return fuo.InMemoryLogRecordExporter}});var puo=okr();Object.defineProperty(O3,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return puo.BatchLogRecordProcessor}})});var sh,akr,Tpe,ckr,Ipe,Dpe,lkr,ukr,dkr,fkr,pkr,hkr,mkr,gkr,Akr,ykr,_kr,Ekr,vkr,bkr,Ckr,Skr,xkr,wkr,Tkr,Ikr,Dkr,Rkr,Nkr,Okr,kkr,Bkr,Pkr,Mkr,Fkr,Lkr,uX=te(()=>{"use strict";sh="iflow-cli",akr="iflow_cli.user_prompt",Tpe="iflow_cli.tool_call",ckr="iflow_cli.api_request",Ipe="iflow_cli.api_error",Dpe="iflow_cli.api_response",lkr="iflow_cli.config",ukr="iflow_cli.flash_fallback",dkr="iflow_cli.next_speaker_check",fkr="iflow_cli.slash_command",pkr="iflow_cli.cli_response",hkr="iflow_cli.tool.call.count",mkr="iflow_cli.tool.call.latency",gkr="iflow_cli.mcp.tool.call.count",Akr="iflow_cli.mcp.tool.call.latency",ykr="iflow_cli.builtin.tool.call.count",_kr="iflow_cli.builtin.tool.call.latency",Ekr="gen_ai.client.operation",vkr="gen_ai.client.operation.duration",bkr="gen_ai.client.token.usage",Ckr="iflow_cli.session.count",Skr="iflow_cli.file.operation.count",xkr="iflow_cli.user_request.count",wkr="iflow_cli.user_request.latency",Tkr="iflow_cli.user_experience.success",Ikr="iflow_cli.user.identity",Dkr="iflow_cli.scheduler.lock.error",Rkr="iflow_cli.mcp.connect.count",Nkr="iflow_cli.loop.detection.count",Okr="iflow_cli.paste.operation.count",kkr="iflow_cli.paste.operation.latency",Bkr="iflow_cli.xinliu.web.search.count",Pkr="iflow_cli.xinliu.web.search.latency",Mkr="iflow_cli.web.fetch.count",Fkr="iflow_cli.web.fetch.latency",Lkr="iflow_cli.approval.mode.count"});var dX,fX,pX,hX,mX,gX,AX,yX,_X,EX,AC,yC,Ukr=te(()=>{"use strict";dX="iflow_cli.cpu.usage_percentage",fX="iflow_cli.cpu.user_percentage",pX="iflow_cli.cpu.system_percentage",hX="iflow_cli.cpu.cores",mX="iflow_cli.memory.heap_used",gX="iflow_cli.memory.heap_total",AX="iflow_cli.memory.rss",yX="iflow_cli.memory.external",_X="iflow_cli.memory.system_usage_percentage",EX="iflow_cli.memory.process_usage_percentage",AC={[dX]:"CPU usage percentage",[fX]:"CPU user time percentage",[pX]:"CPU system time percentage",[hX]:"Number of CPU cores",[mX]:"Heap memory used in bytes",[gX]:"Heap memory total in bytes",[AX]:"Resident Set Size in bytes",[yX]:"External memory in bytes",[_X]:"System memory usage percentage",[EX]:"Process memory usage percentage relative to Node.js limits"},yC={[dX]:"percent",[fX]:"percent",[pX]:"percent",[hX]:"cores",[mX]:"bytes",[gX]:"bytes",[AX]:"bytes",[yX]:"bytes",[_X]:"percent",[EX]:"percent"}});import*as _C from"os";var ENe,Qkr=te(()=>{"use strict";Ukr();ENe=class{meter;options;lastCpuMeasurement;lastMeasureTime;cpuCores;totalSystemMemory;nodeJSMemoryLimit;cpuUsageGauge;cpuUserGauge;cpuSystemGauge;cpuCoresGauge;memoryHeapUsedGauge;memoryHeapTotalGauge;memoryRssGauge;memoryExternalGauge;memorySystemUsageGauge;memoryProcessUsageGauge;constructor(e,r={}){this.meter=e,this.options={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...r},this.lastCpuMeasurement=process.cpuUsage(),this.lastMeasureTime=Date.now(),this.cpuCores=_C.cpus().length,this.totalSystemMemory=_C.totalmem(),this.nodeJSMemoryLimit=this.getNodeJSMemoryLimit(),this.initializeMetrics()}getCurrentCpuMetrics(){try{let e=process.cpuUsage(this.lastCpuMeasurement),r=Date.now(),n=r-this.lastMeasureTime;if(this.lastCpuMeasurement=process.cpuUsage(),this.lastMeasureTime=r,n<=0)return{usage:0,user:0,system:0,cores:this.cpuCores};let o=Math.max(0,e.user+e.system),s=Math.max(0,e.user),a=Math.max(0,e.system),c=o/(n*1e3)*100,u=s/(n*1e3)*100,d=a/(n*1e3)*100,f=Number.isFinite(c)?Math.min(100,Math.max(0,c)):0,p=Number.isFinite(u)?Math.min(100,Math.max(0,u)):0,h=Number.isFinite(d)?Math.min(100,Math.max(0,d)):0;return{usage:f,user:p,system:h,cores:this.cpuCores}}catch{return{usage:0,user:0,system:0,cores:this.cpuCores}}}getCurrentMemoryMetrics(){try{let e=process.memoryUsage(),r=_C.freemem(),o=(this.totalSystemMemory-r)/this.totalSystemMemory*100,s=e.rss/this.nodeJSMemoryLimit*100;return{heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,external:e.external,systemUsage:Math.min(100,Math.max(0,o)),processUsage:Math.min(100,Math.max(0,s))}}catch{return{heapUsed:0,heapTotal:0,rss:0,external:0,systemUsage:0,processUsage:0}}}initializeMetrics(){let e=_C.platform(),r=_C.arch(),n=process.version;this.options.enableCpuMetrics&&(this.cpuUsageGauge=this.meter.createObservableGauge(dX,{description:AC[dX],unit:yC[dX]}),this.cpuUserGauge=this.meter.createObservableGauge(fX,{description:AC[fX],unit:yC[fX]}),this.cpuSystemGauge=this.meter.createObservableGauge(pX,{description:AC[pX],unit:yC[pX]}),this.cpuCoresGauge=this.meter.createObservableGauge(hX,{description:AC[hX],unit:yC[hX]}),this.cpuUsageGauge.addCallback(o=>{let s=this.getCurrentCpuMetrics();o.observe(s.usage,{platform:e,arch:r,node_version:n})}),this.cpuUserGauge.addCallback(o=>{let s=this.getCurrentCpuMetrics();o.observe(s.user,{platform:e,arch:r,node_version:n})}),this.cpuSystemGauge.addCallback(o=>{let s=this.getCurrentCpuMetrics();o.observe(s.system,{platform:e,arch:r,node_version:n})}),this.cpuCoresGauge?.addCallback(o=>{o.observe(this.cpuCores,{platform:e,arch:r})})),this.options.enableMemoryMetrics&&(this.memoryHeapUsedGauge=this.meter.createObservableGauge(mX,{description:AC[mX],unit:yC[mX]}),this.memoryHeapTotalGauge=this.meter.createObservableGauge(gX,{description:AC[gX],unit:yC[gX]}),this.memoryRssGauge=this.meter.createObservableGauge(AX,{description:AC[AX],unit:yC[AX]}),this.memoryExternalGauge=this.meter.createObservableGauge(yX,{description:AC[yX],unit:yC[yX]}),this.memorySystemUsageGauge=this.meter.createObservableGauge(_X,{description:AC[_X],unit:yC[_X]}),this.memoryProcessUsageGauge=this.meter.createObservableGauge(EX,{description:AC[EX],unit:yC[EX]}),this.memoryHeapUsedGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.heapUsed,{platform:e,arch:r,node_version:n})}),this.memoryHeapTotalGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.heapTotal,{platform:e,arch:r,node_version:n})}),this.memoryRssGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.rss,{platform:e,arch:r,node_version:n})}),this.memoryExternalGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.external,{platform:e,arch:r,node_version:n})}),this.memorySystemUsageGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.systemUsage,{platform:e,arch:r,node_version:n})}),this.memoryProcessUsageGauge.addCallback(o=>{let s=this.getCurrentMemoryMetrics();o.observe(s.processUsage,{platform:e,arch:r,node_version:n,memory_limit_mb:Math.round(this.nodeJSMemoryLimit/(1024*1024)).toString()})}))}getNodeJSMemoryLimit(){let e=process.execArgv.find(o=>o.startsWith("--max-old-space-size="))?.split("=")[1];if(e){let o=parseInt(e,10);if(!isNaN(o)&&o>0)return o*1024*1024}let r=process.execArgv.find(o=>o.startsWith("--max_old_space_size="))?.split("=")[1];if(r){let o=parseInt(r,10);if(!isNaN(o)&&o>0)return o*1024*1024}let n=_C.arch();return n==="x64"||n==="arm64"?1400*1024*1024:700*1024*1024}}});function jkr(t,e={}){if(vNe)return vNe;let r={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...e};return vNe=new ENe(t,r),vNe}var vNe,Gkr=te(()=>{"use strict";Qkr();vNe=null});import huo from"os";function $kr(){try{let t=huo.networkInterfaces();for(let e of Object.keys(t)){let r=t[e];if(r){for(let n of r)if(n.family==="IPv4"&&!n.internal)return n.address}}return"127.0.0.1"}catch{return"127.0.0.1"}}var qkr=te(()=>{"use strict"});import*as vX from"os";import*as bNe from"fs";function Gc(t){let e="0.4.3",r=process.env.IFLOW_ENV||"normal",n={darwin:"macOS",win32:"Windows",linux:"Linux",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",aix:"AIX"},o=vX.platform(),s=n[o]||o,a="unknown";try{if(o==="darwin")a=vX.release();else if(o==="linux")try{if(bNe.existsSync("/etc/os-release")){let m=bNe.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="(.+)"/m);m&&(a=m[1])}}catch{a=vX.release()}else o==="win32"&&(a=vX.release())}catch{a="unknown"}let c={name:"Node.js",version:process.version,architecture:process.arch},u=t.getModel()||"unknown",d=t.getUsageMode(),f=!1,p=t.getContentGeneratorConfig?.();if(p){let h=p.authType,m=p.baseUrl||"";(h===Yt.LOGIN_WITH_IFLOW||h===Yt.IFLOW||h===Yt.OPENAI_COMPATIBLE&&m.includes("apis.iflow.cn"))&&(f=!0)}return{app_name:sh,tenant__:"gen_ai",version:e,platform:s,os_model:a,runtime_name:c.name,runtime_version:c.version,runtime_architecture:c.architecture,model_name:u,is_iflow_open_user:String(f),ip:$kr(),iflow_env:r,usage_mode:d}}var S_t=te(()=>{"use strict";A_();qkr();uX()});function Hkr(){return x_t||(x_t=dde.getMeter(sh)),x_t}function Vkr(){if(ah)return;let t=Hkr();if(t){try{jkr(t,{enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0})}catch{}w_t=t.createHistogram(hkr,{description:"Counts tool calls, tagged by function name and success.",unit:"count",valueType:lc.INT}),T_t=t.createHistogram(mkr,{description:"Latency of tool calls in milliseconds.",unit:"ms",valueType:lc.INT}),I_t=t.createHistogram(gkr,{description:"Counts MCP tool calls, tagged by function name and success.",unit:"count",valueType:lc.INT}),D_t=t.createHistogram(Akr,{description:"Latency of MCP tool calls in milliseconds.",unit:"ms",valueType:lc.INT}),R_t=t.createHistogram(ykr,{description:"Counts built-in tool calls, tagged by function name and success.",unit:"count",valueType:lc.INT}),N_t=t.createHistogram(_kr,{description:"Latency of built-in tool calls in milliseconds.",unit:"ms",valueType:lc.INT}),Rpe=t.createHistogram(Ekr,{description:"Counts API requests, tagged by model and status.",unit:"count",valueType:lc.INT}),Npe=t.createHistogram(vkr,{description:"Latency of API requests in milliseconds.",unit:"ms",valueType:lc.INT}),O_t=t.createHistogram(bkr,{description:"Counts the total number of tokens used.",unit:"tokens",valueType:lc.INT}),k_t=t.createHistogram(Skr,{description:"Counts file operations (create, read, update).",unit:"count",valueType:lc.INT}),B_t=t.createHistogram(xkr,{description:"Counts user requests from prompt to completion.",unit:"count",valueType:lc.INT}),P_t=t.createHistogram(wkr,{description:"End-to-end latency of user requests in milliseconds.",unit:"ms",valueType:lc.INT}),M_t=t.createHistogram(Tkr,{description:"User experience success rate - counts successful user experiences including retries and fixes.",unit:"count",valueType:lc.INT}),F_t=t.createHistogram(Ikr,{description:"User identity for tracking unique installations.",unit:"count",valueType:lc.INT}),L_t=t.createHistogram(Dkr,{description:"Counts tool scheduler lock errors when new calls are blocked by running calls.",unit:"count",valueType:lc.INT}),U_t=t.createHistogram(Rkr,{description:"Counts MCP connection attempts and their success/failure status.",unit:"count",valueType:lc.INT}),Q_t=t.createHistogram(Nkr,{description:"Counts loop detection events by loop type.",unit:"count",valueType:lc.INT}),j_t=t.createHistogram(Okr,{description:"Counts paste operations, tagged by type and success.",unit:"count",valueType:lc.INT}),G_t=t.createHistogram(kkr,{description:"Latency of paste operations in milliseconds.",unit:"ms",valueType:lc.INT}),$_t=t.createHistogram(Bkr,{description:"Counts xinliu web search operations, tagged by success and error type.",unit:"count",valueType:lc.INT}),q_t=t.createHistogram(Pkr,{description:"Latency of xinliu web search operations in milliseconds.",unit:"ms",valueType:lc.INT}),H_t=t.createHistogram(Mkr,{description:"Counts web fetch operations, tagged by success and error type.",unit:"count",valueType:lc.INT}),V_t=t.createHistogram(Fkr,{description:"Latency of web fetch operations in milliseconds.",unit:"ms",valueType:lc.INT}),W_t=t.createHistogram(Lkr,{description:"Counts usage of different approval modes.",unit:"count",valueType:lc.INT}),ah=!0}}function CNe(t){let e=Hkr();if(!e||!ah)return;e.createHistogram(Ckr,{description:"Count of CLI sessions started.",unit:"count",valueType:lc.INT}).record(1,Gc(t))}function Wkr(t,e,r,n,o,s){if(!w_t||!T_t||!ah)return;let a={...Gc(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};w_t.record(1,a),T_t.record(r,{...Gc(t),function_name:e??"unknown",tool_type:s??"unknown"})}function zkr(t,e,r,n,o,s){if(!I_t||!D_t||!ah)return;let a={...Gc(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};s&&(a.execution_context=s),I_t.record(1,a),D_t.record(r,{...Gc(t),function_name:e??"unknown",execution_context:s??"unknown"})}function Ykr(t,e,r,n,o,s){if(!R_t||!N_t||!ah)return;let a={...Gc(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};s&&(a.execution_context=s),R_t.record(1,a),N_t.record(r,{...Gc(t),function_name:e??"unknown",execution_context:s??"unknown"})}function bX(t,e,r,n){!O_t||!ah||O_t.record(r,{...Gc(t),model:e??"unknown",type:n??"unknown"})}function Kkr(t,e,r,n,o,s,a,c){if(!Rpe||!Npe||!ah)return;let u={...Gc(t),model:e??"unknown",status_code:String(n??(o?"error":"ok"))};a!==void 0&&(u.http_status_code=String(a)),c!==void 0&&(u.business_code=String(c)),s&&(u.finish_reason=s),Rpe.record(1,u);let d={...Gc(t),model:e??"unknown",http_status_code:String(a??200),finish_reason:s??"unknown"};c!=null&&(d.business_code=String(c)),Npe.record(r,d)}function Xkr(t,e,r,n,o,s,a){if(!Rpe||!Npe||!ah)return;let c={...Gc(t),model:e??"unknown",status_code:String(n??"error"),error:o??"unknown"};s!==void 0&&(c.http_status_code=String(s)),a!==void 0&&(c.business_code=String(a)),Rpe.record(1,c);let u={...Gc(t),model:e??"unknown",http_status_code:String(s??0),error:o??"unknown"};a!=null&&(u.business_code=String(a)),Npe.record(r,u)}function dU(t,e,r,n,o){if(!k_t||!ah)return;let s={...Gc(t),operation:e};r!==void 0&&(s.lines=String(r)),n!==void 0&&(s.mimetype=n),o!==void 0&&(s.extension=o),k_t.record(1,s)}function Jkr(t,e,r,n,o){if(!B_t||!P_t||!ah)return;let s={...Gc(t),prompt_id:e,success:String(n)};o&&(s.error=o),B_t.record(1,s),P_t.record(r,s)}function z_t(t,e,r=!1,n=!1,o){if(!M_t||!ah)return;let s={...Gc(t),success:String(e),had_retries:String(r),had_fixes:String(n)};o&&(s.final_error=o),M_t.record(1,s)}function Zkr(t,e){if(!F_t||!ah)return;let r={...Gc(t),user_id:e};F_t.record(1,r)}function eBr(t,e,r){if(!L_t||!ah)return;let n={...Gc(t),running_calls_count:String(e)};r.forEach((o,s)=>{n[`call_${s}_name`]=o.name,n[`call_${s}_status`]=o.status}),L_t.record(1,n)}function Y_t(t,e,r,n,o){if(!U_t||!ah)return;let s={...Gc(t),server_name:e,success:String(r)};n&&(s.error_type=n),o&&(s.transport_type=o),U_t.record(1,s)}function tBr(t,e,r){if(!Q_t||!ah)return;let n={...Gc(t),loop_type:e,prompt_id:r};Q_t.record(1,n)}function SNe(t,e,r,n,o="text",s,a){if(!j_t||!G_t||!ah)return;let c={};try{c=Gc(t)}catch{c={app_name:sh,tenant__:"gen_ai",version:"unknown",platform:a||"unknown",os_model:"unknown",runtime_name:"Node.js",runtime_version:process.version,runtime_architecture:process.arch,model_name:"unknown",is_iflow_open_user:"false",ip:"unknown",iflow_env:"test",usage_mode:"unknown"}}let u={...c,success:String(n),paste_type:o};s&&(u.error_type=s),a&&(u.platform_specific=a),j_t.record(1,u);let d={...c,paste_type:o,text_length_range:String(r),performance_ratio:muo(e,r)};G_t.record(e,d)}function muo(t,e){if(e===0)return"no-text";let r=t/e;return r<=.1?"excellent":r<=.5?"good":r<=1?"normal":r<=2?"slow":"very-slow"}function xNe(t,e,r,n,o,s){if(!$_t||!q_t||!ah)return;let a={...Gc(t),success:String(r)};n&&(a.error_type=n),o!==void 0&&(a.results_count=String(o)),s&&(a.query_length=String(s.length)),$_t.record(1,a),q_t.record(e,{...Gc(t),error_type:n??"none"})}function fU(t,e,r,n,o,s){if(!H_t||!V_t||!ah)return;let a={...Gc(t),success:String(r)};n&&(a.error_type=n),o!==void 0&&(a.url_count=String(o)),s!==void 0&&(a.prompt_length=String(s)),H_t.record(1,a),V_t.record(e,{...Gc(t),error_type:n??"none"})}function wNe(t,e){if(!W_t||!ah)return;let r={...Gc(t),approval_mode:e};W_t.record(1,r)}var j9,x_t,w_t,T_t,I_t,D_t,R_t,N_t,Rpe,Npe,O_t,k_t,B_t,P_t,M_t,F_t,L_t,U_t,Q_t,j_t,G_t,$_t,q_t,H_t,V_t,W_t,ah,r1=te(()=>{"use strict";Zt();uX();Gkr();S_t();(function(t){t.CREATE="create",t.READ="read",t.UPDATE="update"})(j9||(j9={}));ah=!1});var es,xn,ts,rs,nf=te(()=>{"use strict";es=class{name;displayName;description;icon;kind;parameterSchema;isOutputMarkdown;canUpdateOutput;aliases;constructor(e,r,n,o,s,a,c=!0,u=!1,d=[]){this.name=e,this.displayName=r,this.description=n,this.icon=o,this.kind=s,this.parameterSchema=a,this.isOutputMarkdown=c,this.canUpdateOutput=u,this.aliases=d}get schema(){return{name:this.name,description:this.description,parameters:this.parameterSchema}}validateToolParams(e){return null}getDescription(e){return JSON.stringify(e)}shouldConfirmExecute(e,r){return Promise.resolve(!1)}toolLocations(e){return[]}};(function(t){t.ProceedOnce="proceed_once",t.ProceedAlways="proceed_always",t.ProceedAlwaysServer="proceed_always_server",t.ProceedAlwaysTool="proceed_always_tool",t.ModifyWithEditor="modify_with_editor",t.Cancel="cancel"})(xn||(xn={}));(function(t){t.FileSearch="fileSearch",t.Folder="folder",t.Globe="globe",t.Hammer="hammer",t.LightBulb="lightBulb",t.Pencil="pencil",t.Regex="regex",t.Terminal="terminal"})(ts||(ts={}));(function(t){t.Read="read",t.Edit="edit",t.Delete="delete",t.Move="move",t.Search="search",t.Execute="execute",t.Think="think",t.Fetch="fetch",t.Other="other"})(rs||(rs={}))});function guo(t){switch(t){case xn.ProceedOnce:case xn.ProceedAlways:case xn.ProceedAlwaysServer:case xn.ProceedAlwaysTool:return sv.ACCEPT;case xn.ModifyWithEditor:return sv.MODIFY;case xn.Cancel:default:return sv.REJECT}}var sv,CX,SX,xX,wX,TX,DA,IX,DX,av,RX,TNe,NX,INe,LN=te(()=>{"use strict";nf();A_();(function(t){t.ACCEPT="accept",t.REJECT="reject",t.MODIFY="modify"})(sv||(sv={}));CX=class{"event.name";"event.timestamp";model;embedding_model;sandbox_enabled;core_tools_enabled;approval_mode;api_key_enabled;vertex_ai_enabled;debug_enabled;mcp_servers;telemetry_enabled;telemetry_log_user_prompts_enabled;file_filtering_respect_git_ignore;constructor(e){let r=e.getContentGeneratorConfig(),n=e.getMcpServers(),o=!1,s=!1;r&&r.authType&&(o=r.authType===Yt.IFLOW,s=r.authType===Yt.AONE),this["event.name"]="cli_config",this.model=e.getModel(),this.embedding_model=e.getEmbeddingModel(),this.sandbox_enabled=typeof e.getSandbox()=="string"||!!e.getSandbox(),this.core_tools_enabled=(e.getCoreTools()??[]).join(","),this.approval_mode=e.getApprovalMode(),this.api_key_enabled=o||s,this.vertex_ai_enabled=s,this.debug_enabled=e.getDebugMode(),this.mcp_servers=n?Object.keys(n).join(","):"",this.telemetry_enabled=e.getTelemetryEnabled(),this.telemetry_log_user_prompts_enabled=e.getTelemetryLogPromptsEnabled(),this.file_filtering_respect_git_ignore=e.getFileFilteringRespectGitIgnore()}},SX=class{"event.name";"event.timestamp";session_id;constructor(e){this["event.name"]="end_session",this["event.timestamp"]=new Date().toISOString(),this.session_id=e?.getSessionId()}},xX=class{"event.name";"event.timestamp";prompt_length;prompt_id;auth_type;prompt;constructor(e,r,n,o){this["event.name"]="user_prompt",this["event.timestamp"]=new Date().toISOString(),this.prompt_length=e,this.prompt_id=r,this.auth_type=n,this.prompt=o}},wX=class{"event.name";"event.timestamp";function_name;function_args;duration_ms;success;decision;error;error_type;prompt_id;server_name;response_text;constructor(e){this["event.name"]="tool_call",this["event.timestamp"]=new Date().toISOString(),this.function_name=e.request.name,this.function_args=JSON.stringify(e.request.args),this.duration_ms=e.durationMs??0,this.success=e.status==="success",this.decision=e.outcome?guo(e.outcome):void 0,this.error=e.response.error?.message,this.error_type=e.response.errorType,this.prompt_id=e.request.prompt_id,this.response_text=JSON.stringify(e.response,null,2),"tool"in e&&e.tool&&"serverName"in e.tool&&(this.server_name=e.tool.serverName)}},TX=class{"event.name";"event.timestamp";model;prompt_id;request_text;base_url;openai_request;constructor(e,r,n,o,s){this["event.name"]="api_request",this["event.timestamp"]=new Date().toISOString(),this.model=r,this.prompt_id=o,this.request_text=s,this.base_url=e,this.openai_request=n}},DA=class{"event.name";"event.timestamp";model;error;error_type;status_code;http_status_code;business_code;duration_ms;prompt_id;auth_type;constructor(e,r,n,o,s,a,c,u,d){this["event.name"]="api_error",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.error=r,this.error_type=a,this.status_code=c,this.http_status_code=u,this.business_code=d,this.duration_ms=n,this.prompt_id=o,this.auth_type=s}},IX=class{"event.name";"event.timestamp";model;status_code;http_status_code;business_code;duration_ms;error;input_token_count;output_token_count;cached_content_token_count;thoughts_token_count;tool_token_count;total_token_count;response_text;prompt_id;auth_type;finish_reason;constructor(e,r,n,o,s,a,c,u,d,f){this["event.name"]="api_response",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.duration_ms=r,this.status_code=200,this.http_status_code=d||200,this.business_code=f,this.input_token_count=s?.promptTokenCount??0,this.output_token_count=s?.candidatesTokenCount??0,this.cached_content_token_count=s?.cachedContentTokenCount??0,this.thoughts_token_count=s?.thoughtsTokenCount??0,this.tool_token_count=s?.toolUsePromptTokenCount??0,this.total_token_count=s?.totalTokenCount??0,this.response_text=a,this.error=c,this.prompt_id=n,this.auth_type=o,this.finish_reason=u}},DX=class{"event.name";"event.timestamp";auth_type;constructor(e){this["event.name"]="flash_fallback",this["event.timestamp"]=new Date().toISOString(),this.auth_type=e}};(function(t){t.CONSECUTIVE_IDENTICAL_TOOL_CALLS="consecutive_identical_tool_calls",t.CHANTING_IDENTICAL_SENTENCES="chanting_identical_sentences",t.LLM_DETECTED_LOOP="llm_detected_loop"})(av||(av={}));RX=class{"event.name";"event.timestamp";loop_type;prompt_id;constructor(e,r){this["event.name"]="loop_detected",this["event.timestamp"]=new Date().toISOString(),this.loop_type=e,this.prompt_id=r}},TNe=class{"event.name";"event.timestamp";prompt_id;finish_reason;result;constructor(e,r,n){this["event.name"]="next_speaker_check",this["event.timestamp"]=new Date().toISOString(),this.prompt_id=e,this.finish_reason=r,this.result=n}},NX=class{"event.name";"event.timestamp";command;subcommand;constructor(e,r){this["event.name"]="slash_command",this["event.timestamp"]=new Date().toISOString(),this.command=e,this.subcommand=r}},INe=class{"event.name";"event.timestamp";model;constructor(e){this["event.name"]="malformed_json_response",this["event.timestamp"]=new Date().toISOString(),this.model=e}}});var Zn,rBr=te(()=>{"use strict";(function(t){t[t.IFLOW_CLI_KEY_UNKNOWN=0]="IFLOW_CLI_KEY_UNKNOWN",t[t.IFLOW_CLI_START_SESSION_MODEL=1]="IFLOW_CLI_START_SESSION_MODEL",t[t.IFLOW_CLI_START_SESSION_EMBEDDING_MODEL=2]="IFLOW_CLI_START_SESSION_EMBEDDING_MODEL",t[t.IFLOW_CLI_START_SESSION_SANDBOX=3]="IFLOW_CLI_START_SESSION_SANDBOX",t[t.IFLOW_CLI_START_SESSION_CORE_TOOLS=4]="IFLOW_CLI_START_SESSION_CORE_TOOLS",t[t.IFLOW_CLI_START_SESSION_APPROVAL_MODE=5]="IFLOW_CLI_START_SESSION_APPROVAL_MODE",t[t.IFLOW_CLI_START_SESSION_API_KEY_ENABLED=6]="IFLOW_CLI_START_SESSION_API_KEY_ENABLED",t[t.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED=7]="IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED",t[t.IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED=8]="IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED",t[t.IFLOW_CLI_START_SESSION_MCP_SERVERS=9]="IFLOW_CLI_START_SESSION_MCP_SERVERS",t[t.IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED=10]="IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED",t[t.IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED=11]="IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED",t[t.IFLOW_CLI_START_SESSION_RESPECT_GITIGNORE=12]="IFLOW_CLI_START_SESSION_RESPECT_GITIGNORE",t[t.IFLOW_CLI_USER_PROMPT_LENGTH=13]="IFLOW_CLI_USER_PROMPT_LENGTH",t[t.IFLOW_CLI_TOOL_CALL_NAME=14]="IFLOW_CLI_TOOL_CALL_NAME",t[t.IFLOW_CLI_TOOL_CALL_DECISION=15]="IFLOW_CLI_TOOL_CALL_DECISION",t[t.IFLOW_CLI_TOOL_CALL_SUCCESS=16]="IFLOW_CLI_TOOL_CALL_SUCCESS",t[t.IFLOW_CLI_TOOL_CALL_DURATION_MS=17]="IFLOW_CLI_TOOL_CALL_DURATION_MS",t[t.IFLOW_CLI_TOOL_ERROR_MESSAGE=18]="IFLOW_CLI_TOOL_ERROR_MESSAGE",t[t.IFLOW_CLI_TOOL_CALL_ERROR_TYPE=19]="IFLOW_CLI_TOOL_CALL_ERROR_TYPE",t[t.IFLOW_CLI_API_REQUEST_MODEL=20]="IFLOW_CLI_API_REQUEST_MODEL",t[t.IFLOW_CLI_API_RESPONSE_MODEL=21]="IFLOW_CLI_API_RESPONSE_MODEL",t[t.IFLOW_CLI_API_RESPONSE_STATUS_CODE=22]="IFLOW_CLI_API_RESPONSE_STATUS_CODE",t[t.IFLOW_CLI_API_RESPONSE_DURATION_MS=23]="IFLOW_CLI_API_RESPONSE_DURATION_MS",t[t.IFLOW_CLI_API_ERROR_MESSAGE=24]="IFLOW_CLI_API_ERROR_MESSAGE",t[t.IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT=25]="IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT=26]="IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT=27]="IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT=28]="IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT",t[t.IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT=29]="IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT",t[t.IFLOW_CLI_API_ERROR_MODEL=30]="IFLOW_CLI_API_ERROR_MODEL",t[t.IFLOW_CLI_API_ERROR_TYPE=31]="IFLOW_CLI_API_ERROR_TYPE",t[t.IFLOW_CLI_API_ERROR_STATUS_CODE=32]="IFLOW_CLI_API_ERROR_STATUS_CODE",t[t.IFLOW_CLI_API_ERROR_DURATION_MS=33]="IFLOW_CLI_API_ERROR_DURATION_MS",t[t.IFLOW_CLI_END_SESSION_ID=34]="IFLOW_CLI_END_SESSION_ID",t[t.IFLOW_CLI_PROMPT_ID=35]="IFLOW_CLI_PROMPT_ID",t[t.IFLOW_CLI_AUTH_TYPE=36]="IFLOW_CLI_AUTH_TYPE",t[t.IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT=37]="IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT",t[t.IFLOW_CLI_SURFACE=39]="IFLOW_CLI_SURFACE",t[t.IFLOW_CLI_SESSION_ID=40]="IFLOW_CLI_SESSION_ID",t[t.IFLOW_CLI_LOOP_DETECTED_TYPE=38]="IFLOW_CLI_LOOP_DETECTED_TYPE",t[t.IFLOW_CLI_SLASH_COMMAND_NAME=41]="IFLOW_CLI_SLASH_COMMAND_NAME",t[t.IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND=42]="IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND",t[t.IFLOW_CLI_RESPONSE_FINISH_REASON=43]="IFLOW_CLI_RESPONSE_FINISH_REASON",t[t.IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT=44]="IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT",t[t.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL=45]="IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL",t[t.IFLOW_CLI_RESPONSE_TYPE=46]="IFLOW_CLI_RESPONSE_TYPE",t[t.IFLOW_CLI_RESPONSE_LENGTH=47]="IFLOW_CLI_RESPONSE_LENGTH",t[t.IFLOW_CLI_RESPONSE_SUCCESS=48]="IFLOW_CLI_RESPONSE_SUCCESS",t[t.IFLOW_CLI_ERROR_MESSAGE=49]="IFLOW_CLI_ERROR_MESSAGE"})(Zn||(Zn={}))});function pU(t,e){let r=new WeakSet;return JSON.stringify(t,(n,o)=>{if(typeof o=="object"&&o!==null){if(r.has(o))return"[Circular]";r.add(o)}return o},e)}var DNe=te(()=>{"use strict";});import Qx,{dirname as Auo,join as K_t}from"node:path";import RNe from"os";import*as nBr from"crypto";import{fileURLToPath as yuo}from"node:url";import _uo from"node:fs";import{execSync as Euo}from"node:child_process";function jx(t){let e=RNe.homedir();return t.startsWith(e)?t.replace(e,"~"):t}function Il(t,e=35){if(t.length<=e)return t;let n=Qx.parse(t).root,o=Qx.sep,a=t.substring(n.length).split(o).filter(m=>m!=="");if(a.length<=1){let m=Math.floor((e-3)/2);if(m<=0)return t.substring(0,e-3)+"...";let g=t.substring(0,m),A=t.substring(t.length-m);return`${g}...${A}`}let c=a[0],u=a[a.length-1],d=n+c,f=[],p=o.length+u.length;for(let m=a.length-2;m>=0;m--){let g=a[m],A=p+o.length+g.length;if(A<=e)f.unshift(g),p=A;else break}let h=f.join(o)+o+u;return p>e?h:(h=d+o+h,h.length>e?"..."+h.substring(h.length-e-3):h)}function Ap(t,e){let r=Qx.resolve(t),n=Qx.resolve(e);return Qx.relative(n,r)||"."}function OX(t){let e="";for(let r=0;r<t.length;r++)t[r]===" "&&(r===0||t[r-1]!=="\\")?e+="\\ ":e+=t[r];return e}function G9(t){return process.platform==="win32"?t.replace(/\\([ ,;!?()[\]{}])/g,"$1"):t.replace(/\\(.)/g,"$1")}function NNe(t){return nBr.createHash("sha256").update(t).digest("hex")}function n1(t){let e=NNe(t);return Qx.join(RNe.homedir(),Ym,vuo,e)}function ONe(){return Qx.join(RNe.homedir(),Ym,iBr)}function kNe(t){return Qx.join(t,Ym,iBr)}function BNe(){if(process.env.USE_BUILTIN_RIPGREP==="0")return"rg";let t=Auo(yuo(import.meta.url)),e=[K_t(t,"..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),K_t(t,"..","..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),K_t(t,"..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`)];for(let r of e)try{if(_uo.existsSync(r))return process.platform==="darwin"&&oBr(r),r}catch{}return e[0]}function oBr(t){if(process.platform==="darwin")try{let e=["com.apple.quarantine","CachedFileMimeType","CachedFileType","FileXRayCachedResultInEA"];for(let r of e)try{Euo(`xattr -d "${r}" "${t}" 2>/dev/null`,{stdio:"ignore"})}catch{}}catch{}}function Ope(t,e){let n=RNe.platform()==="win32"?Qx.win32:Qx,o=n.relative(t,e);return!o.startsWith(`..${n.sep}`)&&o!==".."&&!n.isAbsolute(o)}var Ym,X_t,vuo,iBr,of=te(()=>{"use strict";Ym=".iflow",X_t="google_accounts.json",vuo="tmp",iBr="commands"});import buo from"node:path";import{promises as YLa,existsSync as sBr,readFileSync as aBr}from"node:fs";import*as cBr from"os";function lBr(){return buo.join(cBr.homedir(),Ym,X_t)}function uBr(){try{let t=lBr();if(sBr(t)){let e=aBr(t,"utf-8").trim();return e?JSON.parse(e).active:null}return null}catch(t){return console.debug("Error reading cached Google Account:",t),null}}function dBr(){try{let t=lBr();if(!sBr(t))return 0;let e=aBr(t,"utf-8").trim();if(!e)return 0;let r=JSON.parse(e);if(!r||typeof r!="object")return 0;let n=r,o=n.old&&Array.isArray(n.old)?n.old.length:0;return n.active&&o++,o}catch(t){return console.debug("Error reading lifetime Google Accounts:",t),0}}var fBr=te(()=>{"use strict";of();});import*as pBr from"os";import*as $9 from"fs";import*as eEt from"path";import{randomUUID as Cuo}from"crypto";function xuo(){$9.existsSync(J_t)||$9.mkdirSync(J_t,{recursive:!0})}function wuo(){return $9.existsSync(Z_t)&&$9.readFileSync(Z_t,"utf-8").trim()||null}function Tuo(t){$9.writeFileSync(Z_t,t,"utf-8")}function PNe(){try{xuo();let t=wuo();return t||(t=Cuo(),Tuo(t)),t}catch(t){return console.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}var Suo,J_t,Z_t,tEt=te(()=>{"use strict";of();Suo=pBr.homedir()??"",J_t=eEt.join(Suo,Ym),Z_t=eEt.join(J_t,"installation_id")});var hBr,Iuo,Duo,Ruo,Nuo,Ouo,kuo,Buo,Puo,Muo,Fuo,Luo,Uuo,Quo,qh,kpe=te(()=>{"use strict";hBr=Ie(Tlt(),1);LN();rBr();DNe();fBr();tEt();Iuo="start_session",Duo="new_prompt",Ruo="tool_call",Nuo="api_request",Ouo="api_response",kuo="api_error",Buo="end_session",Puo="flash_fallback",Muo="loop_detected",Fuo="next_speaker_check",Luo="slash_command",Uuo="malformed_json_response",Quo="cli_response",qh=class t{static instance;config;events=[];last_flush_time=Date.now();flush_interval_ms=1e3*60;constructor(e){this.config=e}static getInstance(e){if(!(e===void 0||!e?.getUsageStatisticsEnabled()))return t.instance||(t.instance=new t(e)),t.instance}enqueueLogEvent(e){this.events.push([{event_time_ms:Date.now(),source_extension_json:pU(e)}])}createLogEvent(e,r){let n=uBr(),o=dBr();r.push({iflow_cli_key:Zn.IFLOW_CLI_GOOGLE_ACCOUNTS_COUNT,value:o.toString()});let s={console_type:"IFLOW_CLI",application:102,event_name:e,event_metadata:[r]};return n?s.client_email=n:s.client_install_id=PNe(),s}flushIfNeeded(){Date.now()-this.last_flush_time<this.flush_interval_ms||this.flushToClearcut().catch(e=>{console.debug("Error flushing to Clearcut:",e)})}async flushToClearcut(){return this.config?.getDebugMode()&&console.log("Telemetry disabled - not sending log events to Clearcut."),this.events.length=0,this.last_flush_time=Date.now(),Promise.resolve({})}decodeLogResponse(e){if(e.length<1||e.readUInt8(0)!==8)return;let r=BigInt(0),n=!0;for(let s=1;n&&s<e.length;s++){let a=e.readUInt8(s);r|=BigInt(a&127)<<BigInt(7*(s-1)),n=(a&128)!==0}return n?void 0:{nextRequestWaitMs:Number(r)}}handleLogEvent(e,r,n=!1){this.enqueueLogEvent(this.createLogEvent(e,r)),n?this.flushToClearcut().catch(o=>{console.debug("Error flushing to Clearcut:",o)}):this.flushIfNeeded()}logStartSessionEvent(e){let r=process.env.SURFACE||"SURFACE_NOT_SET",n=[{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_MODEL,value:e.model},{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_EMBEDDING_MODEL,value:e.embedding_model},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_SANDBOX,value:e.sandbox_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_CORE_TOOLS,value:e.core_tools_enabled},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_APPROVAL_MODE,value:e.approval_mode},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_API_KEY_ENABLED,value:e.api_key_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_DEBUG_MODE_ENABLED,value:e.debug_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_MCP_SERVERS,value:e.mcp_servers},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_TELEMETRY_ENABLED,value:e.telemetry_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED,value:e.telemetry_log_user_prompts_enabled.toString()},{iflow_cli_key:Zn.IFLOW_CLI_SURFACE,value:r}];this.handleLogEvent(Iuo,n,!0)}logNewPromptEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_USER_PROMPT_LENGTH,value:JSON.stringify(e.prompt_length)},{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(Duo,r)}logToolCallEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.function_name)},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_DECISION,value:JSON.stringify(e.decision)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_SUCCESS,value:JSON.stringify(e.success)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_ERROR_MESSAGE,value:JSON.stringify(e.error)},{iflow_cli_key:Zn.IFLOW_CLI_TOOL_CALL_ERROR_TYPE,value:JSON.stringify(e.error_type)}];this.handleLogEvent(Ruo,r)}logApiRequestEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_API_REQUEST_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)}];this.handleLogEvent(Nuo,r)}logApiResponseEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_STATUS_CODE,value:JSON.stringify(e.status_code)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_MESSAGE,value:JSON.stringify(e.error)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_INPUT_TOKEN_COUNT,value:JSON.stringify(e.input_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT,value:JSON.stringify(e.output_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_CACHED_TOKEN_COUNT,value:JSON.stringify(e.cached_content_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_THINKING_TOKEN_COUNT,value:JSON.stringify(e.thoughts_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_API_RESPONSE_TOOL_TOKEN_COUNT,value:JSON.stringify(e.tool_token_count)},{iflow_cli_key:Zn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(Ouo,r)}logApiErrorEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_MODEL,value:JSON.stringify(e.model)},{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_TYPE,value:JSON.stringify(e.error_type)},{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_STATUS_CODE,value:JSON.stringify(e.status_code)},{iflow_cli_key:Zn.IFLOW_CLI_API_ERROR_DURATION_MS,value:JSON.stringify(e.duration_ms)},{iflow_cli_key:Zn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)}];this.handleLogEvent(kuo,r)}logFlashFallbackEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_AUTH_TYPE,value:JSON.stringify(e.auth_type)},{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""}];this.handleLogEvent(Puo,r,!0)}logLoopDetectedEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_LOOP_DETECTED_TYPE,value:JSON.stringify(e.loop_type)}];this.handleLogEvent(Muo,r)}logNextSpeakerCheck(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_RESPONSE_FINISH_REASON,value:JSON.stringify(e.finish_reason)},{iflow_cli_key:Zn.IFLOW_CLI_NEXT_SPEAKER_CHECK_RESULT,value:JSON.stringify(e.result)},{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:this.config?.getSessionId()??""}];this.handleLogEvent(Fuo,r)}logSlashCommandEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_SLASH_COMMAND_NAME,value:JSON.stringify(e.command)}];e.subcommand&&r.push({iflow_cli_key:Zn.IFLOW_CLI_SLASH_COMMAND_SUBCOMMAND,value:JSON.stringify(e.subcommand)}),this.handleLogEvent(Luo,r)}logMalformedJsonResponseEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.handleLogEvent(Uuo,r)}logCliResponseEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_PROMPT_ID,value:JSON.stringify(e.prompt_id)},{iflow_cli_key:Zn.IFLOW_CLI_RESPONSE_TYPE,value:JSON.stringify(e.response_type)},{iflow_cli_key:Zn.IFLOW_CLI_RESPONSE_LENGTH,value:JSON.stringify(e.response_length)},{iflow_cli_key:Zn.IFLOW_CLI_RESPONSE_SUCCESS,value:JSON.stringify(e.success)},{iflow_cli_key:Zn.IFLOW_CLI_ERROR_MESSAGE,value:JSON.stringify(e.error)}];this.handleLogEvent(Quo,r)}logEndSessionEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:e?.session_id?.toString()??""}];this.handleLogEvent(Buo,r,!0)}getProxyAgent(){let e=this.config?.getProxy();if(e){if(e.startsWith("http"))return new hBr.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}shutdown(){let e=new SX(this.config);this.logEndSessionEvent(e)}}});import*as mBr from"node:fs";var hU,gBr,Bpe,MNe,FNe,LNe,ABr=te(()=>{"use strict";hU=Ie(pi(),1),gBr=Ie(ex(),1);Bpe=class{writeStream;constructor(e){this.writeStream=mBr.createWriteStream(e,{flags:"a"})}serialize(e){let r=new WeakSet;return JSON.stringify(e,(o,s)=>{if(typeof s=="object"&&s!==null){if(r.has(s))return"[Circular]";r.add(s)}return s},2)+`
|
|
485
485
|
`}shutdown(){return new Promise(e=>{this.writeStream.end(e)})}},MNe=class extends Bpe{export(e,r){let n=e.map(o=>this.serialize(o)).join("");this.writeStream.write(n,o=>{r({code:o?hU.ExportResultCode.FAILED:hU.ExportResultCode.SUCCESS,error:o||void 0})})}},FNe=class extends Bpe{export(e,r){let n=e.map(o=>this.serialize(o)).join("");this.writeStream.write(n,o=>{r({code:o?hU.ExportResultCode.FAILED:hU.ExportResultCode.SUCCESS,error:o||void 0})})}},LNe=class extends Bpe{export(e,r){let n=this.serialize(e);this.writeStream.write(n,o=>{r({code:o?hU.ExportResultCode.FAILED:hU.ExportResultCode.SUCCESS,error:o||void 0})})}getPreferredAggregationTemporality(){return gBr.AggregationTemporality.CUMULATIVE}async forceFlush(){return Promise.resolve()}}});function RA(){return kX}function juo(t){if(!t)return;let e=t.replace(/^["']|["']$/g,"");try{let r=new URL(e),o=r.port==="4318"||r.protocol==="http:"||r.protocol==="https:"?"http":"grpc";return{url:o==="grpc"?r.origin:e,protocol:o}}catch(r){Of.error("Invalid OTLP endpoint URL provided:",e,r);return}}function GNe(t){if(kX)return;let e=(0,QNe.defaultResource)().merge((0,QNe.resourceFromAttributes)({[Vft]:sh,[Wft]:process.version,"session.id":t.getSessionId()})),r=t.getTelemetryOtlpEndpoint(),n=juo(r),o=!!n,s=t.getTelemetryOutfile(),a=[];o&&a.push(new yBr.OTLPTraceExporter({url:`${n.url}/v1/traces`})),s&&a.push(new MNe(s));let c=[];o&&n&&c.push(new EBr.OTLPLogExporter({url:`${n.url}/v1/logs`})),s&&c.push(new FNe(s));let u=[];o&&u.push(new RDe({exporter:new _Br.OTLPMetricExporter({url:`${n.url}/v1/metrics`,temporalityPreference:jNe.AggregationTemporality.DELTA}),exportIntervalMillis:2e4})),s&&u.push(new jNe.PeriodicExportingMetricReader({exporter:new LNe(s),exportIntervalMillis:1e4}));let d={resource:e,serviceName:sh,logRecordProcessors:[],spanProcessors:[],metricReaders:[]};a.forEach(f=>{d.spanProcessors.push(new bBr.BatchSpanProcessor(f,{exportTimeoutMillis:1e4}))}),c.forEach(f=>{d.logRecordProcessors.push(new CBr.BatchLogRecordProcessor(f,{exportTimeoutMillis:1e4}))}),u.forEach(f=>{d.metricReaders.push(f)}),UNe=new vBr.NodeSDK({...d});try{UNe.start(),kX=!0,Vkr()}catch(f){console.error("Error starting OpenTelemetry SDK:",f)}process.on("SIGTERM",BX),process.on("SIGINT",BX)}async function SBr(){if(kX)try{let{trace:t}=await Promise.resolve().then(()=>(Zt(),ur)),e=t.getTracerProvider();"forceFlush"in e&&await e.forceFlush();let{metrics:r}=await Promise.resolve().then(()=>(Zt(),ur)),n=r.getMeterProvider();"forceFlush"in n&&await n.forceFlush()}catch(t){process.env.DEBUG&&console.error("Error flushing telemetry:",t)}}async function BX(){if(!(!kX||!UNe))try{qh.getInstance()?.shutdown(),await UNe.shutdown()}catch(t){console.error("Error shutting down SDK:",t)}finally{kX=!1}}var yBr,_Br,EBr,vBr,QNe,bBr,CBr,jNe,UNe,kX,$Ne=te(()=>{"use strict";Zt();yBr=Ie(rmt(),1),_Br=Ie(cmt(),1),EBr=Ie(umt(),1),vBr=Ie(WDr(),1);YDr();jh();QNe=Ie(Lyt(),1),bBr=Ie(o9e(),1),CBr=Ie(skr(),1),jNe=Ie(ex(),1);uX();r1();kpe();ABr();process.env.DEBUG?Of.setLogger(new ode,eh.DEBUG):Of.setLogger(new ode,eh.NONE);kX=!1});var xBr={};Ws(xBr,{TraceContext:()=>q9});var q9,rEt=te(()=>{"use strict";Zt();$Ne();q9=class{static rootSpan=null;static tracer=Au.getTracer("iflow-cli-tracer");static spanLock=null;static startRootSpan(e="iflow_cli_request",r=!1){return this.rootSpan&&r&&(this.rootSpan.end(),this.rootSpan=null),this.rootSpan||(this.rootSpan=this.tracer.startSpan(e)),this.rootSpan}static async withRootSpan(e,r){let n=r?this.startRootSpan(r):this.getRootSpan();return n?hA.with(Au.setSpan(hA.active(),n),async()=>{try{return await e()}catch(o){throw n.recordException(o),n.setStatus({code:F6.ERROR,message:o.message}),o}}):e()}static startChildSpan(e){return this.tracer.startSpan(e)}static async withChildSpan(e,r,n){let o=this.startChildSpan(e);return n&&o.setAttributes(n),hA.with(Au.setSpan(hA.active(),o),async()=>{try{let s=await r();return o.setStatus({code:F6.OK}),s}catch(s){throw o.recordException(s),o.setStatus({code:F6.ERROR,message:s.message}),s}finally{o.end()}})}static getRootSpan(){return this.rootSpan}static async endRootSpan(){this.spanLock&&await this.spanLock,this.spanLock=(async()=>{if(this.rootSpan){let e=this.rootSpan;this.rootSpan=null,e.end();try{await SBr()}catch{}}})(),await this.spanLock,this.spanLock=null}static getActiveSpan(){return Au.getActiveSpan()}static setSpanAttributes(e){let r=this.getActiveSpan();r&&r.setAttributes(e)}static addSpanEvent(e,r){let n=this.getActiveSpan();n&&n.addEvent(e,r)}}});function Ppe(){let t=Au.getActiveSpan();if(t){let r=t.spanContext();if(r&&r.traceId&&r.spanId){let o=r.traceId,s=r.spanId,a=(r.traceFlags||0).toString(16).padStart(2,"0");return`00-${o}-${s}-${a}`}}return UN.getCurrentSession()?.traceparent}function Mpe(t){let e=Ppe();return e?{...t,traceparent:e}:t}function nEt(){return Ppe()}async function mU(t,e,r){let n=Au.getTracer("iflow-cli"),{TraceContext:o}=await Promise.resolve().then(()=>(rEt(),xBr)),s=o.getRootSpan(),a;if(s){let c=Au.setSpan(hA.active(),s);a=hA.with(c,()=>n.startSpan(t,{attributes:e}))}else a=n.startSpan(t,{attributes:e});try{return await hA.with(Au.setSpan(hA.active(),a),r)}catch(c){throw a.recordException(c),a.setStatus({code:F6.ERROR,message:c instanceof Error?c.message:"Unknown error"}),c}finally{a.end()}}var gU=te(()=>{"use strict";Zt();qNe();});import{release as Guo,version as $uo}from"os";var HNe,UN,qNe=te(()=>{"use strict";lft();uft();gU();HNe=class{currentSession=null;async startSession(e,r,n,o){let{model:s,tool:a}=o||{},c="iflow",u="cli",d=Ppe()||"",f="";d&&(f=d.split("-")[1]??"");let p=tY(),h=f?`${c}.${u}.${n}.${f}`:"",m=Date.now();return this.currentSession={traceId:f,parent_observation_id:p,conversationId:n,sessionId:e,userId:r,pid:c,sceneId:u,sam:h,traceparent:d,startTime:m,model:s,tool:a},await ede("/aitrack.lifecycle.run_started",{gmkey:"AI",gokey:{pid:c,sam:h,trace_id:f,session_id:e,conversation_id:n,observation_id:p,model:s,tool:a,user_id:r}}),this.currentSession}async endSession(){if(!this.currentSession)return;let{pid:e,sam:r,traceId:n,parent_observation_id:o,model:s,tool:a,sessionId:c,conversationId:u,userId:d,startTime:f}=this.currentSession,p=Date.now()-f,h=tY();await ede("/aitrack.lifecycle.run_finished",{gmkey:"AI",gokey:{pid:e,sam:r,trace_id:n,session_id:c,conversation_id:u,observation_id:h,parent_observation_id:o,duration:p,model:s,tool:a,sessionId:c,user_id:d}})}async recordError(e,r){if(!this.currentSession)throw new Error("No active session to record error");let{pid:n,sam:o,traceId:s,parent_observation_id:a,model:c,tool:u,sessionId:d,conversationId:f,userId:p}=this.currentSession,h=tY(),m="",g="";e instanceof Error?(m=e.cause?`${e.message}:${e.cause.message}`:e.message,g=e.cause?e.cause.stack||"":e.stack||""):m=String(e);let A={gmkey:"AI",gokey:{pid:n,sam:o,trace_id:s,observation_id:h,parent_observation_id:a,session_id:d,conversation_id:f,user_id:p,error_msg:`${m}
|
|
486
|
-
${g.slice(0,2e4)}`,model:c,tool:u,toolName:r?.toolName,toolArgs:r?.toolArgs?JSON.stringify(r.toolArgs):void 0,cliVer:"0.4.
|
|
486
|
+
${g.slice(0,2e4)}`,model:c,tool:u,toolName:r?.toolName,toolArgs:r?.toolArgs?JSON.stringify(r.toolArgs):void 0,cliVer:"0.4.3",platform:process.platform,arch:process.arch,nodeVersion:process.version,osVersion:process.platform==="darwin"?Guo():$uo()}};await ede("/aitrack.lifecycle.run_error",A)}getCurrentSession(){return this.currentSession}},UN=new HNe});var wBr=T((wUa,quo)=>{quo.exports={name:"systeminformation",version:"5.27.11",description:"Advanced, lightweight system and OS information library",license:"MIT",author:"Sebastian Hildebrandt <hildebrandt@plus-innovations.com> (https://plus-innovations.com)",homepage:"https://systeminformation.io",main:"./lib/index.js",type:"commonjs",bin:{systeminformation:"lib/cli.js"},types:"./lib/index.d.ts",scripts:{test:"node ./test/test.js",testDeno:"deno run -A ./test/test.js"},files:["lib/"],keywords:["system information","sysinfo","monitor","monitoring","os","linux","osx","windows","freebsd","openbsd","netbsd","cpu","cpuload","physical cores","logical cores","processor","cores","threads","socket type","memory","file system","fsstats","diskio","block devices","netstats","network","network interfaces","network connections","network stats","iface","printer","processes","users","internet","battery","docker","docker stats","docker processes","graphics","graphic card","graphic controller","gpu","display","smart","disk layout","usb","audio","bluetooth","wifi","wifinetworks","virtual box","virtualbox","vm","backend","hardware","BIOS","chassis"],repository:{type:"git",url:"git+https://github.com/sebhildebrandt/systeminformation.git"},funding:{type:"Buy me a coffee",url:"https://www.buymeacoffee.com/systeminfo"},os:["darwin","linux","win32","freebsd","openbsd","netbsd","sunos","android"],engines:{node:">=8.0.0"}}});var ch=T(ki=>{"use strict";var MX=ve("os"),bC=ve("fs"),Huo=ve("path"),uEt=ve("child_process").spawn,Vuo=ve("child_process").exec,FX=ve("child_process").execSync,Wuo=ve("util"),yU=process.platform,dEt=yU==="linux"||yU==="android",DBr=yU==="darwin",YNe=yU==="win32",RBr=yU==="freebsd",NBr=yU==="openbsd",OBr=yU==="netbsd",iEt=0,AU="",EC="",QN=null,vC=null,fEt=process.env.WINDIR||"C:\\Windows",Hh,PX="",Fpe=[],pEt=!1,WNe="",zuo="$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ",sEt="--###START###--",TBr="--ERROR--",zNe="--###ENDCMD###--",aEt="--##ID##--",Lpe={windowsHide:!0,maxBuffer:1024*2e4,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})},KNe={maxBuffer:1024*2e4,encoding:"UTF-8",stdio:["pipe","pipe","ignore"]};function Yuo(t){let e=parseInt(t,10);return isNaN(e)&&(e=0),e}function Kuo(t){let e=!1,r="",n="";for(let o of t)o>="0"&&o<="9"||e?(e=!0,r+=o):n+=o;return[n,r]}var VNe=new String,cEt=new String().replace,lEt=new String().toLowerCase,kBr=new String().toString,BBr=new String().substr,PBr=new String().substring,MBr=new String().trim,FBr=new String().startsWith,LBr=Math.min;function Xuo(t){return t&&{}.toString.call(t)==="[object Function]"}function Juo(t){let e=[],r={};for(let n=0;n<t.length;n++){let o=Object.keys(t[n]);o.sort(function(a,c){return a-c});let s="";for(let a=0;a<o.length;a++)s+=JSON.stringify(o[a]),s+=JSON.stringify(t[n][o[a]]);({}).hasOwnProperty.call(r,s)||(e.push(t[n]),r[s]=!0)}return e}function Zuo(t,e){return t.sort(function(r,n){let o="",s="";return e.forEach(function(a){o=o+r[a],s=s+n[a]}),o<s?-1:o>s?1:0})}function edo(){return iEt===0&&(iEt=MX.cpus().length),iEt}function jN(t,e,r,n,o){r=r||":",e=e.toLowerCase(),n=n||!1,o=o||!1;let s="";return t.some(a=>{let c=a.toLowerCase().replace(/\t/g,"");if(n&&(c=c.trim()),c.startsWith(e)&&(!o||c.match(e+r)||c.match(e+" "+r))){let u=n?a.trim().split(r):a.split(r);if(u.length>=2)return u.shift(),s=u.join(r).trim(),!0}}),s}function tdo(t,e){return e=e||16,t.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],e))})}function rdo(t){let e="",r=0;return t.split("").forEach(n=>{n>="0"&&n<="9"?r===1&&r++:(r===0&&r++,r===1&&(e+=n))}),e}function ndo(t,e){e=e||"",t=t.toUpperCase();let r=0,n=0,o=rdo(t),s=t.split(o);if(s.length>=2){s[2]&&(s[1]+=s[2]);let a=s[1]&&s[1].toLowerCase().indexOf("pm")>-1||s[1].toLowerCase().indexOf("p.m.")>-1||s[1].toLowerCase().indexOf("p. m.")>-1||s[1].toLowerCase().indexOf("n")>-1||s[1].toLowerCase().indexOf("ch")>-1||s[1].toLowerCase().indexOf("\xF6s")>-1||e&&s[1].toLowerCase().indexOf(e)>-1;return r=parseInt(s[0],10),n=parseInt(s[1],10),r=a&&r<12?r+12:r,("0"+r).substr(-2)+":"+("0"+n).substr(-2)}}function ido(t,e){let r={date:"",time:""};e=e||{};let n=(e.dateFormat||"").toLowerCase(),o=e.pmDesignator||"",s=t.split(" ");if(s[0]){if(s[0].indexOf("/")>=0){let a=s[0].split("/");a.length===3&&(a[0].length===4?r.date=a[0]+"-"+("0"+a[1]).substr(-2)+"-"+("0"+a[2]).substr(-2):a[2].length===2?(n.indexOf("/d/")>-1||n.indexOf("/dd/")>-1,r.date="20"+a[2]+"-"+("0"+a[1]).substr(-2)+"-"+("0"+a[0]).substr(-2)):(t.toLowerCase().indexOf("pm")>-1||t.toLowerCase().indexOf("p.m.")>-1||t.toLowerCase().indexOf("p. m.")>-1||t.toLowerCase().indexOf("am")>-1||t.toLowerCase().indexOf("a.m.")>-1||t.toLowerCase().indexOf("a. m.")>-1||n.indexOf("/d/")>-1||n.indexOf("/dd/")>-1)&&n.indexOf("dd/")!==0?r.date=a[2]+"-"+("0"+a[0]).substr(-2)+"-"+("0"+a[1]).substr(-2):r.date=a[2]+"-"+("0"+a[1]).substr(-2)+"-"+("0"+a[0]).substr(-2))}if(s[0].indexOf(".")>=0){let a=s[0].split(".");a.length===3&&(n.indexOf(".d.")>-1||n.indexOf(".dd.")>-1?r.date=a[2]+"-"+("0"+a[0]).substr(-2)+"-"+("0"+a[1]).substr(-2):r.date=a[2]+"-"+("0"+a[1]).substr(-2)+"-"+("0"+a[0]).substr(-2))}if(s[0].indexOf("-")>=0){let a=s[0].split("-");a.length===3&&(r.date=a[0]+"-"+("0"+a[1]).substr(-2)+"-"+("0"+a[2]).substr(-2))}}if(s[1]){s.shift();let a=s.join(" ");r.time=ndo(a,o)}return r}function odo(t,e){let r=e>0,n=1,o=0,s=0,a=[];for(let u=0;u<t.length;u++)n<=e?(/\s/.test(t[u])&&!r&&(s=u-1,a.push({from:o,to:s+1,cap:t.substring(o,s+1)}),o=s+2,n++),r=t[u]===" "):(!/\s/.test(t[u])&&r&&(s=u-1,o<s&&a.push({from:o,to:s,cap:t.substring(o,s)}),o=s+1,n++),r=t[u]===" ");s=5e3,a.push({from:o,to:s,cap:t.substring(o,s)});let c=a.length;for(let u=0;u<c;u++)a[u].cap.replace(/\s/g,"").length===0&&u+1<c&&(a[u].to=a[u+1].to,a[u].cap=a[u].cap+a[u+1].cap,a.splice(u+1,1),c=c-1);return a}function sdo(t,e,r){for(let n=0;n<t.length;n++)if(t[n][e]===r)return n;return-1}function ado(){if(WNe="powershell.exe",YNe){let t=`${fEt}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;bC.existsSync(t)&&(WNe=t)}}function UBr(){if(MX.type()==="Windows_NT"&&!AU&&(AU=fEt+"\\system32\\wbem\\wmic.exe",!bC.existsSync(AU)))try{let t=FX("WHERE WMIC",Lpe).toString().split(`\r
|
|
487
487
|
`);t&&t.length?AU=t[0]:AU="wmic"}catch{AU="wmic"}return AU}function cdo(t){return new Promise(e=>{process.nextTick(()=>{try{QBr(UBr()+" "+t).then(r=>{e(r,"")})}catch(r){e("",r)}})})}function ldo(){return YNe?`"${process.env.VBOX_INSTALL_PATH||process.env.VBOX_MSI_INSTALL_PATH}\\VBoxManage.exe"`:"vboxmanage"}function oEt(t){let e="",r,n="";if(t.indexOf(sEt)>=0){r=t.split(sEt);let s=r[1].split(aEt);e=s[0],s.length>1&&(t=s.slice(1).join(aEt))}t.indexOf(zNe)>=0&&(r=t.split(zNe),n=r[0]);let o=-1;for(let s=0;s<Fpe.length;s++)Fpe[s].id===e&&(o=s,Fpe[s].callback(n));o>=0&&Fpe.splice(o,1)}function udo(){Hh||(Hh=uEt(WNe,["-NoProfile","-NoLogo","-InputFormat","Text","-NoExit","-Command","-"],{stdio:"pipe",windowsHide:!0,maxBuffer:1024*2e4,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})}),Hh&&Hh.pid&&(pEt=!0,Hh.stdout.on("data",function(t){PX=PX+t.toString("utf8"),t.indexOf(zNe)>=0&&(oEt(PX),PX="")}),Hh.stderr.on("data",function(){oEt(PX+TBr)}),Hh.on("error",function(){oEt(PX+TBr)}),Hh.on("close",function(){Hh&&Hh.kill()})))}function ddo(){try{Hh&&(Hh.stdin.write("exit"+MX.EOL),Hh.stdin.end(),pEt=!1)}catch{Hh&&Hh.kill()}Hh=null}function QBr(t){if(pEt){let e=Math.random().toString(36).substring(2,12);return new Promise(r=>{process.nextTick(()=>{function n(o){r(o)}Fpe.push({id:e,cmd:t,callback:n,start:new Date});try{Hh&&Hh.pid&&Hh.stdin.write(zuo+"echo "+sEt+e+aEt+"; "+MX.EOL+t+MX.EOL+"echo "+zNe+MX.EOL)}catch{r("")}})})}else{let e="";return new Promise(r=>{process.nextTick(()=>{try{let n=uEt(WNe,["-NoProfile","-NoLogo","-InputFormat","Text","-ExecutionPolicy","Unrestricted","-Command",t],{stdio:"pipe",windowsHide:!0,maxBuffer:2048e4,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})});n&&!n.pid&&n.on("error",function(){r(e)}),n&&n.pid?(n.stdout.on("data",function(o){e=e+o.toString("utf8")}),n.stderr.on("data",function(){n.kill(),r(e)}),n.on("close",function(){n.kill(),r(e)}),n.on("error",function(){n.kill(),r(e)})):r(e)}catch{r(e)}})})}}function fdo(t,e,r){let n="";return r=r||{},new Promise(o=>{process.nextTick(()=>{try{let s=uEt(t,e,r);s&&!s.pid&&s.on("error",function(){o(n)}),s&&s.pid?(s.stdout.on("data",function(a){n+=a.toString()}),s.on("close",function(){s.kill(),o(n)}),s.on("error",function(){s.kill(),o(n)})):o(n)}catch{o(n)}})})}function pdo(){if(YNe){if(!EC)try{let r=FX("chcp",Lpe).toString().split(`\r
|
|
488
488
|
`)[0].split(":");EC=r.length>1?r[1].replace(".","").trim():""}catch{EC="437"}return EC}if(dEt||DBr||RBr||NBr||OBr){if(!EC)try{let r=FX("echo $LANG",KNe).toString().split(`\r
|
|
489
489
|
`)[0].split(".");EC=r.length>1?r[1].trim():"",EC||(EC="UTF-8")}catch{EC="UTF-8"}return EC}}function hdo(){if(QN!==null)return QN;if(QN=!1,YNe)try{let t=FX("WHERE smartctl 2>nul",Lpe).toString().split(`\r
|
|
@@ -927,13 +927,13 @@ Bus `);for(let c=1;c<a.length;c++){let u=Sho(a[c]);r.push(u)}}t&&t(r),e(r)}),Aho
|
|
|
927
927
|
- \u7EC4\u4EF6\u6837\u5F0F\uFF1A[\u6309\u94AE\u3001\u5361\u7247\u3001\u8868\u5355\u7B49UI\u7EC4\u4EF6\u7684\u8BBE\u8BA1\u89C4\u8303]
|
|
928
928
|
- \u4EA4\u4E92\u72B6\u6001\uFF1A[hover\u3001active\u3001disabled\u7B49\u72B6\u6001\u8BBE\u8BA1]
|
|
929
929
|
|
|
930
|
-
\u8F93\u51FA\u8981\u6C42\uFF1A\u7528**\u7528\u6237\u6240\u4F7F\u7528\u7684\u8BED\u8A00**\u8F93\u51FA\uFF0C\u7B80\u6D01\uFF0C\u4F46\u4FE1\u606F\u5B8C\u6574\u3001\u51C6\u786E\u3002`}static isMultimodalModel(e){let r=["gemini-2.5-flash-06-17","gemini-2.5-flash-lite-preview-06-17","gemini-2.5-flash-preview-05-20","gemini-2.5-flash-preview-04-17","gemini-2.5-pro-06-17","gemini-2.5-pro-preview-05-06","gemini-2.5-pro-03-25","gemini-2.5-pro-preview-06-05","o3-pro-0610-global","claude_opus4","claude3_opus","claude_sonnet4","claude37_sonnet","claude35_sonnet2","claude35_sonnet","o3-0416-global","o4-mini-0416-global","o3-mini-2025-01-31","o3-mini-0131-global","o1-preview-0912-global","o1-preview-0912","o1-mini-0912-global","o1-mini-0912","o1-2024-12-17","o1-1217-global","o1-1217","qwen-plus-latest-inc","qwen-plus-latest","qwen-plus","qwen-plus-safe","gemini-2.0-flash","gemini-2.0-flash-thinking","gemini-2.0-flash-exp","qwen2.5-vl-72b-instruct","qwen-vl-max","qwen3-vl-plus","Qwen-VL","qwen-vl-max-latest","nova-lite-v1","nova-pro-v1","gpt-5","gpt-5-0807-global","gpt-5-mini","gpt-5-chat-0807-global","gpt-5-mini-0807-global","gpt-5-nano-0807-global","gpt-4o-1120-global","gpt-4o-0806-global","gpt-4o-0806","gpt-4o-0513-global","gpt-4o-0513-Batch","gpt-4o-0513","gpt-4o-0806-Batch","gpt-4o-mini-0718-global","gpt-4o-mini-0718","gpt-4o-mini-0718-Batch"],n=e.toLowerCase();return r.some(o=>n.includes(o.toLowerCase()))||n.includes("vision")||n.includes("visual")||n.includes("vl")}}});var GOe,IU,$Oe=te(()=>{"use strict";GOe=class{modelCapabilities=new Map;constructor(){this.initializeModelCapabilities()}initializeModelCapabilities(){this.registerModel(/^o1-(preview|mini)/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:32e3,configureRequest:(e,r)=>{r.reasoningLevel!=="low"&&(e.reasoning=!0)}}),this.registerModel(/^deepseek/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:32e3,configureRequest:(e,r)=>{r.reasoningLevel!=="low"&&(e.reasoning=!0),e.thinking_mode=!0}}),this.registerModel(/^glm
|
|
930
|
+
\u8F93\u51FA\u8981\u6C42\uFF1A\u7528**\u7528\u6237\u6240\u4F7F\u7528\u7684\u8BED\u8A00**\u8F93\u51FA\uFF0C\u7B80\u6D01\uFF0C\u4F46\u4FE1\u606F\u5B8C\u6574\u3001\u51C6\u786E\u3002`}static isMultimodalModel(e){let r=["gemini-2.5-flash-06-17","gemini-2.5-flash-lite-preview-06-17","gemini-2.5-flash-preview-05-20","gemini-2.5-flash-preview-04-17","gemini-2.5-pro-06-17","gemini-2.5-pro-preview-05-06","gemini-2.5-pro-03-25","gemini-2.5-pro-preview-06-05","o3-pro-0610-global","claude_opus4","claude3_opus","claude_sonnet4","claude37_sonnet","claude35_sonnet2","claude35_sonnet","o3-0416-global","o4-mini-0416-global","o3-mini-2025-01-31","o3-mini-0131-global","o1-preview-0912-global","o1-preview-0912","o1-mini-0912-global","o1-mini-0912","o1-2024-12-17","o1-1217-global","o1-1217","qwen-plus-latest-inc","qwen-plus-latest","qwen-plus","qwen-plus-safe","gemini-2.0-flash","gemini-2.0-flash-thinking","gemini-2.0-flash-exp","qwen2.5-vl-72b-instruct","qwen-vl-max","qwen3-vl-plus","Qwen-VL","qwen-vl-max-latest","nova-lite-v1","nova-pro-v1","gpt-5","gpt-5-0807-global","gpt-5-mini","gpt-5-chat-0807-global","gpt-5-mini-0807-global","gpt-5-nano-0807-global","gpt-4o-1120-global","gpt-4o-0806-global","gpt-4o-0806","gpt-4o-0513-global","gpt-4o-0513-Batch","gpt-4o-0513","gpt-4o-0806-Batch","gpt-4o-mini-0718-global","gpt-4o-mini-0718","gpt-4o-mini-0718-Batch"],n=e.toLowerCase();return r.some(o=>n.includes(o.toLowerCase()))||n.includes("vision")||n.includes("visual")||n.includes("vl")}}});var GOe,IU,$Oe=te(()=>{"use strict";GOe=class{modelCapabilities=new Map;constructor(){this.initializeModelCapabilities()}initializeModelCapabilities(){this.registerModel(/^o1-(preview|mini)/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:32e3,configureRequest:(e,r)=>{r.reasoningLevel!=="low"&&(e.reasoning=!0)}}),this.registerModel(/^deepseek/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:32e3,configureRequest:(e,r)=>{r.reasoningLevel!=="low"&&(e.reasoning=!0),e.thinking_mode=!0}}),this.registerModel(/^glm-4\.5/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:2e4,configureRequest:e=>{e.chat_template_kwargs={enable_thinking:!0}},configureNonThinkingRequest:e=>{e.chat_template_kwargs={enable_thinking:!1}}}),this.registerModel(/^glm-4\.6$/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:2e4,configureRequest:e=>{e.chat_template_kwargs={enable_thinking:!0}},configureNonThinkingRequest:e=>{e.chat_template_kwargs={enable_thinking:!1}}}),this.registerModel(/^glm-4\.6-exp$/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:2e4,configureRequest:e=>{e.extendParams={thinking:{type:"enabled",budget_tokens:32e3}},e.temperature=1}}),this.registerModel(/^claude-3\.5-sonnet/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:25e3,configureRequest:(e,r)=>{e.thinking={enabled:!0,max_tokens:r.maxTokens,reasoning_level:r.reasoningLevel}}}),this.registerModel(/.*reasoning.*/,{supportsThinking:!0,supportedReasoningLevels:["low","medium"],maxThinkingTokens:1e4,configureRequest:e=>{e.reasoning=!0}}),this.registerModel(/.*thinking.*/,{supportsThinking:!0,supportedReasoningLevels:["low","medium","high"],maxThinkingTokens:15e3,configureRequest:e=>{e.thinking_mode=!0}})}registerModel(e,r){let n=e instanceof RegExp?e.source:e;this.modelCapabilities.set(n,r)}supportsThinking(e){return this.getModelCapability(e)?.supportsThinking??!1}getModelCapability(e){for(let[r,n]of this.modelCapabilities)if(new RegExp(r,"i").test(e))return n;return null}configureThinkingRequest(e,r,n){let o=this.getModelCapability(e);if(!o||!o.supportsThinking)return!1;if(!o.supportedReasoningLevels.includes(n.reasoningLevel)){let s=o.supportedReasoningLevels;s.includes("high")?n.reasoningLevel="high":s.includes("medium")?n.reasoningLevel="medium":n.reasoningLevel="low"}return o.maxThinkingTokens&&n.maxTokens>o.maxThinkingTokens&&(n.maxTokens=o.maxThinkingTokens),o.configureRequest&&o.configureRequest(r,n),e==="deepseek-v3.2-chat"&&(r.model="deepseek-v3.2-reasoner"),!0}configureNonThinkingRequest(e,r){let n=this.getModelCapability(e);return!n||!n.supportsThinking?!1:n.configureNonThinkingRequest?(n.configureNonThinkingRequest(r),!0):!1}getMaxThinkingTokens(e){return this.getModelCapability(e)?.maxThinkingTokens??null}getSupportedReasoningLevels(e){return this.getModelCapability(e)?.supportedReasoningLevels??[]}getSupportedModels(){let e=[];for(let[r,n]of this.modelCapabilities)n.supportsThinking&&e.push(r);return e}validateThinkingConfig(e,r){let n=this.getModelCapability(e),o=[];if(!n)return{isValid:!1,warnings:[`Model ${e} does not support thinking`]};if(!n.supportsThinking)return{isValid:!1,warnings:[`Model ${e} does not support thinking`]};let s={...r};if(!n.supportedReasoningLevels.includes(r.reasoningLevel)){let a=n.supportedReasoningLevels,c=a.includes("high")?"high":a.includes("medium")?"medium":"low";s.reasoningLevel=c,o.push(`Reasoning level ${r.reasoningLevel} not supported, adjusted to ${c}`)}return n.maxThinkingTokens&&r.maxTokens>n.maxThinkingTokens&&(s.maxTokens=n.maxThinkingTokens,o.push(`Token limit ${r.maxTokens} exceeds model maximum, adjusted to ${n.maxThinkingTokens}`)),{isValid:!0,warnings:o,adjustedConfig:o.length>0?s:void 0}}},IU=new GOe});function BMr(){console.log("\u{1F9F9} Cleaning up all global performance trackers"),Object.values(J9).forEach(t=>{t.cleanup()}),console.log("\u{1F9F9} All performance trackers cleaned up")}var iJ,J9,uhe=te(()=>{"use strict";iJ=class{timers=new Map;durations=new Map;stackDepth=0;enabled;context;cleanupInterval;maxDurationsPerOperation=1e3;maxAge=300*1e3;constructor(e="default",r=!1){this.context=e,this.enabled=r||process.env.IFLOW_PERFORMANCE_DEBUG==="true",this.startPeriodicCleanup()}start(e){if(!this.enabled)return;let r=`${this.context}:${e}`;this.timers.set(r,performance.now());let n=" ".repeat(this.stackDepth);console.log(`\u{1F535} ${n}[${this.context}] Started: ${e}`),this.stackDepth++}end(e){if(!this.enabled)return;this.stackDepth=Math.max(0,this.stackDepth-1);let r=" ".repeat(this.stackDepth),n=`${this.context}:${e}`,o=this.timers.get(n);if(o===void 0){console.warn(`\u26A0\uFE0F ${r}[${this.context}] No start time found for: ${e}`);return}let s=performance.now()-o;this.timers.delete(n),this.durations.has(e)||this.durations.set(e,[]);let a=this.durations.get(e);a.push(s),a.length>this.maxDurationsPerOperation&&a.splice(0,a.length-this.maxDurationsPerOperation);let c=this.getDurationColor(s);return console.log(`${c} ${r}[${this.context}] Completed: ${e} (${s.toFixed(2)}ms)`),s}async time(e,r){if(!this.enabled)return await r();this.start(e);try{let n=await r();return this.end(e),n}catch(n){this.stackDepth=Math.max(0,this.stackDepth-1);let o=" ".repeat(this.stackDepth);throw console.log(`\u{1F534} ${o}[${this.context}] Error in: ${e}`),n}}timeSync(e,r){if(!this.enabled)return r();this.start(e);try{let n=r();return this.end(e),n}catch(n){this.stackDepth=Math.max(0,this.stackDepth-1);let o=" ".repeat(this.stackDepth);throw console.log(`\u{1F534} ${o}[${this.context}] Error in: ${e}`),n}}checkpoint(e,r){if(!this.enabled)return;let n=" ".repeat(this.stackDepth),o=r?` | ${JSON.stringify(r)}`:"";console.log(`\u{1F4CD} ${n}[${this.context}] Checkpoint: ${e}${o}`)}getStats(){let e={context:this.context,operations:{},summary:{totalOperations:0,totalTime:0,averageTime:0}},r=0,n=0;for(let[o,s]of this.durations){let a=s.reduce((f,p)=>f+p,0),c=a/s.length,u=Math.min(...s),d=Math.max(...s);e.operations[o]={count:s.length,totalTime:a,averageTime:c,minTime:u,maxTime:d,lastTime:s[s.length-1]},r+=a,n+=s.length}return e.summary.totalTime=r,e.summary.totalOperations=n,e.summary.averageTime=n>0?r/n:0,e}printReport(){if(!this.enabled)return;let e=this.getStats();console.log(`
|
|
931
931
|
\u{1F4CA} Performance Report [${this.context}]`),console.log("=".repeat(50)),console.log(`Total Operations: ${e.summary.totalOperations}`),console.log(`Total Time: ${e.summary.totalTime.toFixed(2)}ms`),console.log(`Average Time: ${e.summary.averageTime.toFixed(2)}ms`),console.log("");let r=Object.entries(e.operations).sort(([,n],[,o])=>o.totalTime-n.totalTime);for(let[n,o]of r){let s=(o.totalTime/e.summary.totalTime*100).toFixed(1);console.log(`${n}:`),console.log(` Count: ${o.count}, Total: ${o.totalTime.toFixed(2)}ms (${s}%)`),console.log(` Avg: ${o.averageTime.toFixed(2)}ms, Min: ${o.minTime.toFixed(2)}ms, Max: ${o.maxTime.toFixed(2)}ms`)}console.log("=".repeat(50))}reset(){this.timers.clear(),this.durations.clear(),this.stackDepth=0}getDurationColor(e){return e<10?"\u{1F7E2}":e<100?"\u{1F7E1}":e<1e3?"\u{1F7E0}":"\u{1F534}"}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}startPeriodicCleanup(){this.cleanupInterval=setInterval(()=>{this.performPeriodicCleanup()},120*1e3),typeof process<"u"&&process.on("beforeExit",()=>{this.cleanup()})}performPeriodicCleanup(){if(!this.enabled)return;let e=Date.now(),r=0;for(let[n,o]of this.durations){let s=o.length;o.length>this.maxDurationsPerOperation&&o.splice(0,o.length-this.maxDurationsPerOperation),o.length===0&&this.durations.delete(n),r+=s-o.length}r>0&&console.log(`\u{1F9F9} [${this.context}] Cleaned up ${r} old performance entries`)}cleanup(){this.timers.clear(),this.durations.clear(),this.stackDepth=0,this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0),console.log(`\u{1F9F9} [${this.context}] Performance tracker cleaned up`)}getMemoryUsage(){let e=Array.from(this.durations.values()).reduce((r,n)=>r+n.length,0);return{timersCount:this.timers.size,durationsCount:this.durations.size,totalEntries:e}}},J9={subagent:new iJ("SubAgent"),api:new iJ("API"),tools:new iJ("Tools"),client:new iJ("GeminiClient")}});import{promises as PMr}from"fs";import MMr from"path";var DU,s6t=te(()=>{"use strict";al();e6t();che();LN();gU();RMr();r1();A_();QOe();jOe();kOe();of();zR();_i();$Oe();uhe();DU=class{apiKey;baseUrl;modelName;multimodalModelName;multimodalHelper;progressCallback;debugMode;authType;logFilePath;config;lastUsageMetadata;isSessionInitialized=!1;constructor(e){this.modelName=e.model,this.apiKey=e.apiKey||"",this.baseUrl=e.baseUrl||"",this.multimodalModelName=e.multimodalModelName||"";let r=e.authType===Yt.IFLOW||e.authType===Yt.LOGIN_WITH_IFLOW||!!(this.baseUrl&&this.baseUrl.toLowerCase().includes("apis.iflow.cn")),n=e.authType===Yt.AONE||e.authType===Yt.LOGIN_WITH_AONE,o=r?"qwen3-vl-plus":n?"ide-qwen3-coder-modelscope":e.multimodalModelName||void 0;if(this.multimodalHelper=new X9(this.apiKey,this.baseUrl,o,r,n),this.debugMode=e.debugMode||!1,this.authType=e.authType,this.config=e.config,this.debugMode){let s=n1(process.cwd());this.logFilePath=MMr.join(s,"prompt.txt")}}async logToPromptFile(e,r){if(!this.debugMode||!this.logFilePath)return;let n=`${r}
|
|
932
932
|
${JSON.stringify(e,null,2)}`;try{let o=MMr.dirname(this.logFilePath);await PMr.mkdir(o,{recursive:!0});let a=`
|
|
933
933
|
[${new Date().toISOString()}]
|
|
934
934
|
${n}
|
|
935
935
|
${"=".repeat(80)}
|
|
936
|
-
`;await PMr.appendFile(this.logFilePath,a,"utf-8")}catch(o){console.debug(O.t("openaiContentGenerator.errors.failedWriteDebugLog"),o)}}logTelemetryFailure(e,r){let n=r instanceof Error&&r.message?r.message:String(r);B3(new Error(`${e}: ${n}`))}async generateContent(e,r){let n={"model.name":this.modelName,"model.provider":"openai","api.endpoint":`${this.baseUrl}/chat/completions`};return mU("model_call",n,async()=>{let o=Date.now(),s={},a;try{let c=await this.generateContentInternal(e,r,d=>{s=d},(d,f,p,h)=>{a=h;let m=Au.getActiveSpan();if(m){let g=Date.now()-o,A={"request.model":s.model||this.modelName,"request.temperature":s.temperature,"request.max_tokens":s.max_tokens||s.max_new_tokens,"request.tools_count":s.tools?.length||0,"request.messages_count":s.messages?.length||0,"response.http_status":d||200,"response.business_error_code":f,"response.finish_reason":p||"unknown","response.duration_ms":g,"response.success":!0};try{A["request.full_body"]=this.safeStringify(s),a&&(A["response.full_body"]=this.safeStringify(a))}catch(y){console.error("Failed to serialize request/response data for telemetry:",y),A["request.body_serialization_error"]=!0,A.serialization_error_message=y instanceof Error?y.message:String(y)}try{m.setAttributes(A)}catch(y){console.error("Failed to set span attributes:",y)}}}),u=Au.getActiveSpan();if(u&&c.usageMetadata){let d={"response.prompt_tokens":c.usageMetadata.promptTokenCount,"response.completion_tokens":c.usageMetadata.candidatesTokenCount,"response.total_tokens":c.usageMetadata.totalTokenCount};try{d["request.full_body"]=this.safeStringify(s),a&&(d["response.full_body"]=this.safeStringify(a))}catch(f){console.error("Failed to serialize request/response data for telemetry:",f),d["request.body_serialization_error"]=!0,d.serialization_error_message=f instanceof Error?f.message:String(f)}try{u.setAttributes(d)}catch(f){console.error("Failed to set span attributes:",f)}}return c}catch(c){let u=Date.now()-o,d=c instanceof Error?c.message:String(c),f=Au.getActiveSpan();if(f){let p={"request.model":s.model||this.modelName,"request.temperature":s.temperature,"request.max_tokens":s.max_tokens||s.max_new_tokens,"request.tools_count":s.tools?.length||0,"request.messages_count":s.messages?.length||0,"response.duration_ms":u,"response.success":!1,"response.error_message":d};try{p["request.full_body"]=this.safeStringify(s),a&&(p["response.full_body"]=this.safeStringify(a))}catch(h){console.error("Failed to serialize request/response data for telemetry:",h),p["request.body_serialization_error"]=!0,p.serialization_error_message=h instanceof Error?h.message:String(h)}try{f.setAttributes(p)}catch(h){console.error("Failed to set span attributes:",h)}}throw c}})}safeStringify(e){let r=new WeakSet;return JSON.stringify(e,(n,o)=>{if(typeof o=="object"&&o!==null){if(r.has(o))return"[Circular Reference]";r.add(o)}return o})}async generateContentInternal(e,r,n,o){let s=J9.api;s.start("OpenAI-GenerateContent-Total");let a=!1;try{if((this.authType===Yt.LOGIN_WITH_IFLOW||this.authType===Yt.IFLOW)&&await Jz()){this.authType===Yt.LOGIN_WITH_IFLOW&&await dSe();let{getCachedApiKey:B}=await Promise.resolve().then(()=>(zR(),eft)),j=await B();j&&(this.apiKey=j)}let c=await this.convertToOpenAIMessages(e),u=DMr(c);if(this.config){let N=this.config.getConversationId();if(N)try{await ZEt(this.config,N,{model:this.modelName,tool:u})}catch(B){this.logTelemetryFailure("Telemetry initialization failed",B)}}let d=this.convertToOpenAITools(e.config?.tools),f={model:this.modelName,messages:c},p=!1;this.config?.getTemperature()!==void 0&&this.config.getTemperature()!==-1?(f.temperature=this.config.getTemperature(),p=!0):e.config?.temperature!==void 0&&(this.config?.getTemperature()===void 0||this.config.getTemperature()!==-1)&&(f.temperature=e.config.temperature,p=!0),p||(this.config?.getTopP()!==void 0&&this.config.getTopP()!==-1?f.top_p=this.config.getTopP():e.config?.topP!==void 0&&(this.config?.getTopP()===void 0||this.config.getTopP()!==-1)&&(f.top_p=e.config.topP));let h=this.config?.getContentGeneratorConfig?.();h?.thinking&&h.thinking.maxTokens>0?(IU.configureThinkingRequest(this.modelName,f,h.thinking)||console.debug(`Model ${this.modelName} does not support thinking mode`),h.thinking=null):IU.configureNonThinkingRequest(this.modelName,f);let m=await this.calculateInputTokens(e),g=o6t(f.model,m),A="global";A==="aone"&&(f.max_tokens=g),this.modelName.includes("deepseek")&&(f.max_tokens=g),f.max_new_tokens=g,e.config?.stopSequences&&e.config.stopSequences.length>0&&(f.stop=e.config.stopSequences),d&&d.length>0&&(f.tools=d),await this.logToPromptFile(f,"INPUT REQUEST"),n&&n(f);let y=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl;["offline-whale-wave.alibaba-inc.com","whale.wave.vipserver.offline","whale-wave.alibaba-inc.com","pre-whale-wave.alibaba-inc.com","internal-offline-whale-wave.alibaba-inc.com","internal-whale-wave.alibaba-inc.com"].some(N=>y.includes(N))&&(f.extend_fields={sessionId:this.config?.getSessionId()||""});let v=Date.now(),b=nEt(),S={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"user-agent":"iFlow-Cli","session-id":this.config?.getSessionId()||"","conversation-id":this.config?.getConversationId()||""};b&&(S={...S,traceparent:b}),A==="aone"&&(S={...S,"X-Client-Type":"iflow-cli","X-Client-Version":"0.4.2"}),BOe(this.config,new TX(this.baseUrl,this.modelName,JSON.stringify(f),r,JSON.stringify(e.contents)));let w=await fetch(`${y}/chat/completions`,{signal:e.config?.abortSignal,method:"POST",headers:S,body:JSON.stringify(f)}),R=Date.now()-v;if(!w.ok){o&&o(w.status);let N=await w.text();if(this.config)try{await DOe(this.config,new Error(N)),P3(this.config,new DA(this.modelName,N,R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"http_error",w.status,w.status,void 0))}catch(B){this.logTelemetryFailure("Telemetry error recording failed",B)}throw w.status===511?(this.config&&P3(this.config,new DA(this.modelName,"Content length exceeded",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",511,200,511)),new Error(O.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:b||w.headers.get("eagleeye-traceid")}))):w.status===514?(this.config&&P3(this.config,new DA(this.modelName,"model_error",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(O.t("openaiContentGenerator.errors.modelError",{traceId:b||w.headers.get("eagleeye-traceid")}))):w.status===429?(this.config&&P3(this.config,new DA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",429,200,429)),new Error(O.t("openaiContentGenerator.errors.modelRateLimitReached"))):new Error(O.t("openaiContentGenerator.errors.httpError",{status:w.status,body:N,traceId:b||w.headers.get("eagleeye-traceid")}))}let D;try{D=await w.json()}catch(N){throw B3(N),new Error(O.t("openaiContentGenerator.errors.responseFormatError",{traceId:b||w.headers.get("eagleeye-traceid")}))}if(D.error_code&&(D.error_code===511||D.error_code===413))throw this.config&&P3(this.config,new DA(this.modelName,"Content length exceeded",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",D.error_code,200,D.error_code)),new Error(O.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:b||w.headers.get("eagleeye-traceid")}));if(D.error_code&&D.error_code===514)throw this.config&&P3(this.config,new DA(this.modelName,"model_error",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(O.t("openaiContentGenerator.errors.modelError",{traceId:b||w.headers.get("eagleeye-traceid")}));if(D.status&&D.status==="439"||D.error_code&&D.error_code===439)throw this.config&&P3(this.config,new DA(this.modelName,"API token expired",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"token_expired",439,200,439)),new Error(O.t("openaiContentGenerator.errors.apiTokenExpired"));if(D.msg&&(D.msg.includes("invalid apiKey")||D.msg.includes("Invalid apiKey")))throw new Error(O.t("openaiContentGenerator.errors.invalidApiKey"));if(D.status&&(D.status==="434"||D.status===434))throw this.config&&P3(this.config,new DA(this.modelName,"Invalid API key",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"invalid_api_key",434,200,434)),new Error(O.t("openaiContentGenerator.errors.invalidApiKey"));if(D.status&&(D.status==="435"||D.status===435))throw this.config&&P3(this.config,new DA(this.modelName,"Model Not Support",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"Model Not Support",435,200,435)),new Error(O.t("openaiContentGenerator.errors.modelNotSupport"));if(D.status&&D.status==="429"||D.error_code&&(D.error_code===429||D.error_code===8211))throw this.config&&P3(this.config,new DA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",D.error_code||D.status||429,200,D.error_code||D.status||429)),new Error(O.t("openaiContentGenerator.errors.modelRateLimitReached"));if(D.status&&D.status==="449"||D.error_code&&D.error_code===449)throw this.config&&P3(this.config,new DA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",449,200,449)),new Error(O.t("openaiContentGenerator.errors.rateLimitReached"));if(e.config?.abortSignal?.aborted)throw new Error(O.t("openaiContentGenerator.errors.userCancel"));if(!D||!D.choices||!Array.isArray(D.choices)||D.choices.length===0){let N=b||w.headers.get("eagleeye-traceid");throw new Error(O.t("openaiContentGenerator.errors.invalidResponseFormat",{traceId:N}))}await this.logToPromptFile(D,"API RESPONSE"),D.usage&&(this.lastUsageMetadata={total_tokens:D.usage.total_tokens,prompt_tokens:D.usage.prompt_tokens,completion_tokens:D.usage.completion_tokens});let{response:M,hadJsonFixes:I}=await this.convertFromOpenAIResponse(D);if(a=I,o){let N=D.choices[0]?.finish_reason,B=D.error_code;o(200,B,N,D)}if(this.config)try{let N=D.choices[0]?.finish_reason;MOe(this.config,new IX(this.modelName,R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,D.usage?{promptTokenCount:D.usage.prompt_tokens||0,candidatesTokenCount:D.usage.completion_tokens||0,totalTokenCount:D.usage.total_tokens||0,cachedContentTokenCount:0,thoughtsTokenCount:0,toolUsePromptTokenCount:0}:void 0,JSON.stringify(D,null,2),void 0,N,200,void 0)),await she(this.config),z_t(this.config,!0,!1,a)}catch(N){this.logTelemetryFailure("Telemetry cleanup failed",N)}return M}catch(c){if(B3(c),this.config&&!(c instanceof Error&&c.message==="user cancel")&&c?.name!=="AbortError"&&(await DOe(this.config,c instanceof Error?c:new Error(String(c))),z_t(this.config,!1,!1,a,c instanceof Error?c.message:String(c))),c instanceof Error&&c.cause?.name?.includes("InvalidArgumentError"))throw new Error(O.t("openaiContentGenerator.errors.apiKeyError"));if(c instanceof Error&&c.message&&["iFlow Login expired","Your iFlow Login expired","Your API Token has expired","platform rate limit","platform concurrency limit","Your input has exceeded","the network is unavailable","\u60A8\u7684 iFlow \u767B\u5F55\u5DF2\u8FC7\u671F","\u767B\u5F55\u5DF2\u8FC7\u671F","API Token \u5DF2\u8FC7\u671F","API Token\u5DF2\u8FC7\u671F","\u5E73\u53F0\u901F\u7387\u9650\u5236","\u5E73\u53F0\u5E76\u53D1\u9650\u5236","\u60A8\u7684\u8F93\u5165\u8D85\u8FC7\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u957F\u5EA6","\u60A8\u7684\u8F93\u5165\u5DF2\u8D85\u51FA","\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"].some(f=>c.message.includes(f)))throw new Error(c.message);let u="";throw c instanceof Error?u=c.cause?`${c.message}:${c.cause.message}`:c.message:u=String(c),new Error(O.t("openaiContentGenerator.errors.generateDataError",{error:u}),{cause:c})}finally{s.end("OpenAI-GenerateContent-Total")}}async generateContentStream(e,r){let n=await this.generateContent(e,r);async function*o(){yield n}return o()}async countTokens(e,r=!1){let n=e.useCache??!0;if(!r&&this.lastUsageMetadata?.total_tokens)return{totalTokens:this.lastUsageMetadata.total_tokens};let o=this.extractTextFromRequest(e);return{totalTokens:Math.ceil(o.length/4)}}async calculateInputTokens(e){try{let r={model:this.modelName,contents:e.contents,config:{systemInstruction:e.config?.systemInstruction}};return(await this.countTokens(r)).totalTokens||0}catch{let n=this.extractTextFromRequest({model:this.modelName,contents:e.contents});return Math.ceil(n.length/4)}}async embedContent(e){try{let r=this.extractTextFromEmbedRequest(e),n=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl,o=await fetch(`${n}/v1/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.modelName,input:r})});if(!o.ok){let a=await o.text();throw new Error(`HTTP error! status: ${o.status}, body: ${a}`)}return{embeddings:[{values:(await o.json()).data[0].embedding}]}}catch(r){throw B3(r),new Error(O.t("openaiContentGenerator.errors.embedContentFailed",{error:r instanceof Error?r.message:String(r)}))}}async convertToOpenAIMessages(e){let r=[],n=new Set,o=new Map;if(e.contents){let s=Array.isArray(e.contents)?e.contents:[e.contents];for(let a of s)if(typeof a=="object"&&a!==null&&"parts"in a&&a.parts){let c=Array.isArray(a.parts)?a.parts:[a.parts];for(let u of c){if(u.functionCall){let d=u.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;n.add(d)}if(u.functionResponse){let d=u.functionResponse.id||u.functionResponse.name||"",f=u.functionResponse.response?.output??(u.functionResponse.response?JSON.stringify(u.functionResponse.response):"");o.set(d,{role:"tool",tool_call_id:d,content:f})}}}for(let[a]of o)n.has(a)||o.delete(a)}if(e.config?.systemInstruction){let s=this.extractSystemInstruction(e.config.systemInstruction);s&&r.push({role:"system",content:s})}if(e.contents){let s=Array.isArray(e.contents)?e.contents:[e.contents];for(let a of s){if(typeof a=="string"){r.push({role:"user",content:a});continue}if(typeof a=="object"&&a!==null&&"text"in a&&a.text){r.push({role:"user",content:a.text});continue}if(typeof a=="object"&&a!==null&&"parts"in a&&a.parts){let c=Array.isArray(a.parts)?a.parts:[a.parts];if(a.role==="model"){let u={role:"assistant",content:"",tool_calls:[]};for(let d of c)if(d.thought&&"text"in d&&d.text?u.reasoning_content=d.text:"text"in d&&d.text&&(u.content=d.text),d.functionCall){let f=d.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;u.tool_calls.push({id:f,function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})},type:"function"})}if((u.content||u.tool_calls.length>0)&&(u.tool_calls.length===0&&delete u.tool_calls,r.push(u),u.tool_calls&&u.tool_calls.length>0))for(let d of u.tool_calls){let f=o.get(d.id);f?r.push(f):r.push({role:"tool",tool_call_id:d.id,content:O.t("openaiContentGenerator.messages.toolNotExecuted")})}}else{let u=[];for(let d of c)if("text"in d&&d.text)u.push({type:"text",text:d.text});else if(d.inlineData){let f=d.inlineData;if(f.mimeType&&f.mimeType.startsWith("image/")){let p=this.authType===Yt.IFLOW||this.authType===Yt.LOGIN_WITH_IFLOW||this.baseUrl&&this.baseUrl.toLowerCase().includes("apis.iflow.cn"),h=this.authType===Yt.AONE||this.authType===Yt.LOGIN_WITH_AONE;if(!p&&!h&&X9.isMultimodalModel(this.modelName))r.push({role:"user",content:[{type:"image_url",image_url:{url:"data:"+f.mimeType+";base64,"+f.data}}]});else try{if(!f.data)throw new Error(O.t("openaiContentGenerator.errors.imageDataMissing"));let m=await this.multimodalHelper.generateImageDescription(f.data,f.mimeType);u.push({type:"text",text:`[Image Description]: ${m}`})}catch(m){B3(m),u.push({type:"text",text:O.t("openaiContentGenerator.errors.imageContentCannotParse",{error:m instanceof Error?m.message:String(m)})})}}}u.length>0&&r.push({role:"user",content:u})}}}}return r}createGeminiResponse(){let e=new Zz;return e.candidates=[{content:{parts:[],role:"model"}}],e}async convertFromOpenAIResponse(e){let r=e.choices[0],n=this.createGeminiResponse(),o=n.candidates?.[0],s=!1;if(!r||!r.message)return{response:n,hadJsonFixes:s};if(r.message.reasoning_content&&o?.content?.parts&&o.content.parts.push({thought:!0,text:r.message.reasoning_content}),r.message.reasoning&&o?.content?.parts&&o.content.parts.push({thought:!0,text:r.message.reasoning}),r.message.content&&r.message.content.trim()&&o?.content?.parts&&o.content.parts.push({text:r.message.content}),r.message.tool_calls&&Array.isArray(r.message.tool_calls))for(let a of r.message.tool_calls){let c;try{c=JSON.parse(a.function.arguments)}catch(u){if(B3(u),this.baseUrl==="https://apis.iflow.cn/v1"||this.baseUrl==="https://ducky.code.alibaba-inc.com/v1/openai")try{c=await this.fixInvalidJsonWithQwen(a.function.arguments),s=!0}catch(d){B3(d),console.error("Failed to fix JSON",d),c={}}else c={}}o?.content?.parts?.push({functionCall:{id:a.id,name:a.function.name,args:c}})}return o&&r.finish_reason!=="tool_calls"&&r.finish_reason&&(o.finishReason=this.mapFinishReason(r.finish_reason)),n.usageMetadata={promptTokenCount:e.usage?.prompt_tokens||0,candidatesTokenCount:e.usage?.completion_tokens||0,totalTokenCount:e.usage?.total_tokens||0},{response:n,hadJsonFixes:s}}async fixInvalidJsonWithQwen(e){let r=`
|
|
936
|
+
`;await PMr.appendFile(this.logFilePath,a,"utf-8")}catch(o){console.debug(O.t("openaiContentGenerator.errors.failedWriteDebugLog"),o)}}logTelemetryFailure(e,r){let n=r instanceof Error&&r.message?r.message:String(r);B3(new Error(`${e}: ${n}`))}async generateContent(e,r){let n={"model.name":this.modelName,"model.provider":"openai","api.endpoint":`${this.baseUrl}/chat/completions`};return mU("model_call",n,async()=>{let o=Date.now(),s={},a;try{let c=await this.generateContentInternal(e,r,d=>{s=d},(d,f,p,h)=>{a=h;let m=Au.getActiveSpan();if(m){let g=Date.now()-o,A={"request.model":s.model||this.modelName,"request.temperature":s.temperature,"request.max_tokens":s.max_tokens||s.max_new_tokens,"request.tools_count":s.tools?.length||0,"request.messages_count":s.messages?.length||0,"response.http_status":d||200,"response.business_error_code":f,"response.finish_reason":p||"unknown","response.duration_ms":g,"response.success":!0};try{A["request.full_body"]=this.safeStringify(s),a&&(A["response.full_body"]=this.safeStringify(a))}catch(y){console.error("Failed to serialize request/response data for telemetry:",y),A["request.body_serialization_error"]=!0,A.serialization_error_message=y instanceof Error?y.message:String(y)}try{m.setAttributes(A)}catch(y){console.error("Failed to set span attributes:",y)}}}),u=Au.getActiveSpan();if(u&&c.usageMetadata){let d={"response.prompt_tokens":c.usageMetadata.promptTokenCount,"response.completion_tokens":c.usageMetadata.candidatesTokenCount,"response.total_tokens":c.usageMetadata.totalTokenCount};try{d["request.full_body"]=this.safeStringify(s),a&&(d["response.full_body"]=this.safeStringify(a))}catch(f){console.error("Failed to serialize request/response data for telemetry:",f),d["request.body_serialization_error"]=!0,d.serialization_error_message=f instanceof Error?f.message:String(f)}try{u.setAttributes(d)}catch(f){console.error("Failed to set span attributes:",f)}}return c}catch(c){let u=Date.now()-o,d=c instanceof Error?c.message:String(c),f=Au.getActiveSpan();if(f){let p={"request.model":s.model||this.modelName,"request.temperature":s.temperature,"request.max_tokens":s.max_tokens||s.max_new_tokens,"request.tools_count":s.tools?.length||0,"request.messages_count":s.messages?.length||0,"response.duration_ms":u,"response.success":!1,"response.error_message":d};try{p["request.full_body"]=this.safeStringify(s),a&&(p["response.full_body"]=this.safeStringify(a))}catch(h){console.error("Failed to serialize request/response data for telemetry:",h),p["request.body_serialization_error"]=!0,p.serialization_error_message=h instanceof Error?h.message:String(h)}try{f.setAttributes(p)}catch(h){console.error("Failed to set span attributes:",h)}}throw c}})}safeStringify(e){let r=new WeakSet;return JSON.stringify(e,(n,o)=>{if(typeof o=="object"&&o!==null){if(r.has(o))return"[Circular Reference]";r.add(o)}return o})}async generateContentInternal(e,r,n,o){let s=J9.api;s.start("OpenAI-GenerateContent-Total");let a=!1;try{if((this.authType===Yt.LOGIN_WITH_IFLOW||this.authType===Yt.IFLOW)&&await Jz()){this.authType===Yt.LOGIN_WITH_IFLOW&&await dSe();let{getCachedApiKey:B}=await Promise.resolve().then(()=>(zR(),eft)),j=await B();j&&(this.apiKey=j)}let c=await this.convertToOpenAIMessages(e),u=DMr(c);if(this.config){let N=this.config.getConversationId();if(N)try{await ZEt(this.config,N,{model:this.modelName,tool:u})}catch(B){this.logTelemetryFailure("Telemetry initialization failed",B)}}let d=this.convertToOpenAITools(e.config?.tools),f={model:this.modelName,messages:c};(this.authType===Yt.LOGIN_WITH_IFLOW||this.authType===Yt.IFLOW)&&this.modelName==="glm-4.6"&&(f.model="glm-4.6-exp");let p=!1;this.config?.getTemperature()!==void 0&&this.config.getTemperature()!==-1?(f.temperature=this.config.getTemperature(),p=!0):e.config?.temperature!==void 0&&(this.config?.getTemperature()===void 0||this.config.getTemperature()!==-1)&&(f.temperature=e.config.temperature,p=!0),p||(this.config?.getTopP()!==void 0&&this.config.getTopP()!==-1?f.top_p=this.config.getTopP():e.config?.topP!==void 0&&(this.config?.getTopP()===void 0||this.config.getTopP()!==-1)&&(f.top_p=e.config.topP));let h=this.config?.getContentGeneratorConfig?.();h?.thinking&&h.thinking.maxTokens>0?(IU.configureThinkingRequest(f.model,f,h.thinking)||console.debug(`Model ${this.modelName} does not support thinking mode`),h.thinking=null):IU.configureNonThinkingRequest(f.model,f);let m=await this.calculateInputTokens(e),g=o6t(f.model,m),A="global";A==="aone"&&(f.max_tokens=g),this.modelName.includes("deepseek")&&(f.max_tokens=g),f.model==="glm-4.6-exp"&&(f.max_tokens=g,this.applyGlmRequestBodyTransform(f)),f.max_new_tokens=g,e.config?.stopSequences&&e.config.stopSequences.length>0&&(f.stop=e.config.stopSequences),d&&d.length>0&&(f.tools=d),await this.logToPromptFile(f,"INPUT REQUEST"),n&&n(f);let y=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl;["offline-whale-wave.alibaba-inc.com","whale.wave.vipserver.offline","whale-wave.alibaba-inc.com","pre-whale-wave.alibaba-inc.com","internal-offline-whale-wave.alibaba-inc.com","internal-whale-wave.alibaba-inc.com"].some(N=>y.includes(N))&&(f.extend_fields={sessionId:this.config?.getSessionId()||""});let v=Date.now(),b=nEt(),S={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"user-agent":"iFlow-Cli","session-id":this.config?.getSessionId()||"","conversation-id":this.config?.getConversationId()||""};b&&(S={...S,traceparent:b}),A==="aone"&&(S={...S,"X-Client-Type":"iflow-cli","X-Client-Version":"0.4.3"}),f.model==="glm-4.6-exp"&&(S={...S,"x-idealab-session-id":this.config?.getSessionId()||""}),BOe(this.config,new TX(this.baseUrl,this.modelName,JSON.stringify(f),r,JSON.stringify(e.contents)));let w=await fetch(`${y}/chat/completions`,{signal:e.config?.abortSignal,method:"POST",headers:S,body:JSON.stringify(f)}),R=Date.now()-v;if(!w.ok){o&&o(w.status);let N=await w.text();if(this.config)try{await DOe(this.config,new Error(N)),P3(this.config,new DA(this.modelName,N,R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"http_error",w.status,w.status,void 0))}catch(B){this.logTelemetryFailure("Telemetry error recording failed",B)}throw w.status===511?(this.config&&P3(this.config,new DA(this.modelName,"Content length exceeded",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",511,200,511)),new Error(O.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:b||w.headers.get("eagleeye-traceid")}))):w.status===514?(this.config&&P3(this.config,new DA(this.modelName,"model_error",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(O.t("openaiContentGenerator.errors.modelError",{traceId:b||w.headers.get("eagleeye-traceid")}))):w.status===429?(this.config&&P3(this.config,new DA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",429,200,429)),new Error(O.t("openaiContentGenerator.errors.modelRateLimitReached"))):new Error(O.t("openaiContentGenerator.errors.httpError",{status:w.status,body:N,traceId:b||w.headers.get("eagleeye-traceid")}))}let D;try{D=await w.json()}catch(N){throw B3(N),new Error(O.t("openaiContentGenerator.errors.responseFormatError",{traceId:b||w.headers.get("eagleeye-traceid")}))}if(D.error_code&&(D.error_code===511||D.error_code===413))throw this.config&&P3(this.config,new DA(this.modelName,"Content length exceeded",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",D.error_code,200,D.error_code)),new Error(O.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:b||w.headers.get("eagleeye-traceid")}));if(D.error_code&&D.error_code===514)throw this.config&&P3(this.config,new DA(this.modelName,"model_error",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(O.t("openaiContentGenerator.errors.modelError",{traceId:b||w.headers.get("eagleeye-traceid")}));if(D.status&&D.status==="439"||D.error_code&&D.error_code===439)throw this.config&&P3(this.config,new DA(this.modelName,"API token expired",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"token_expired",439,200,439)),new Error(O.t("openaiContentGenerator.errors.apiTokenExpired"));if(D.msg&&(D.msg.includes("invalid apiKey")||D.msg.includes("Invalid apiKey")))throw new Error(O.t("openaiContentGenerator.errors.invalidApiKey"));if(D.status&&(D.status==="434"||D.status===434))throw this.config&&P3(this.config,new DA(this.modelName,"Invalid API key",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"invalid_api_key",434,200,434)),new Error(O.t("openaiContentGenerator.errors.invalidApiKey"));if(D.status&&(D.status==="435"||D.status===435))throw this.config&&P3(this.config,new DA(this.modelName,"Model Not Support",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"Model Not Support",435,200,435)),new Error(O.t("openaiContentGenerator.errors.modelNotSupport"));if(D.status&&D.status==="429"||D.error_code&&(D.error_code===429||D.error_code===8211))throw this.config&&P3(this.config,new DA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",D.error_code||D.status||429,200,D.error_code||D.status||429)),new Error(O.t("openaiContentGenerator.errors.modelRateLimitReached"));if(D.status&&D.status==="449"||D.error_code&&D.error_code===449)throw this.config&&P3(this.config,new DA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",449,200,449)),new Error(O.t("openaiContentGenerator.errors.rateLimitReached"));if(e.config?.abortSignal?.aborted)throw new Error(O.t("openaiContentGenerator.errors.userCancel"));if(!D||!D.choices||!Array.isArray(D.choices)||D.choices.length===0){let N=b||w.headers.get("eagleeye-traceid");throw new Error(O.t("openaiContentGenerator.errors.invalidResponseFormat",{traceId:N}))}await this.logToPromptFile(D,"API RESPONSE"),D.usage&&(this.lastUsageMetadata={total_tokens:D.usage.total_tokens,prompt_tokens:D.usage.prompt_tokens,completion_tokens:D.usage.completion_tokens});let{response:M,hadJsonFixes:I}=await this.convertFromOpenAIResponse(D);if(a=I,o){let N=D.choices[0]?.finish_reason,B=D.error_code;o(200,B,N,D)}if(this.config)try{let N=D.choices[0]?.finish_reason;MOe(this.config,new IX(this.modelName,R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,D.usage?{promptTokenCount:D.usage.prompt_tokens||0,candidatesTokenCount:D.usage.completion_tokens||0,totalTokenCount:D.usage.total_tokens||0,cachedContentTokenCount:0,thoughtsTokenCount:0,toolUsePromptTokenCount:0}:void 0,JSON.stringify(D,null,2),void 0,N,200,void 0)),await she(this.config),z_t(this.config,!0,!1,a)}catch(N){this.logTelemetryFailure("Telemetry cleanup failed",N)}return M}catch(c){if(B3(c),this.config&&!(c instanceof Error&&c.message==="user cancel")&&c?.name!=="AbortError"&&(await DOe(this.config,c instanceof Error?c:new Error(String(c))),z_t(this.config,!1,!1,a,c instanceof Error?c.message:String(c))),c instanceof Error&&c.cause?.name?.includes("InvalidArgumentError"))throw new Error(O.t("openaiContentGenerator.errors.apiKeyError"));if(c instanceof Error&&c.message&&["iFlow Login expired","Your iFlow Login expired","Your API Token has expired","platform rate limit","platform concurrency limit","Your input has exceeded","the network is unavailable","\u60A8\u7684 iFlow \u767B\u5F55\u5DF2\u8FC7\u671F","\u767B\u5F55\u5DF2\u8FC7\u671F","API Token \u5DF2\u8FC7\u671F","API Token\u5DF2\u8FC7\u671F","\u5E73\u53F0\u901F\u7387\u9650\u5236","\u5E73\u53F0\u5E76\u53D1\u9650\u5236","\u60A8\u7684\u8F93\u5165\u8D85\u8FC7\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u957F\u5EA6","\u60A8\u7684\u8F93\u5165\u5DF2\u8D85\u51FA","\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"].some(f=>c.message.includes(f)))throw new Error(c.message);let u="";throw c instanceof Error?u=c.cause?`${c.message}:${c.cause.message}`:c.message:u=String(c),new Error(O.t("openaiContentGenerator.errors.generateDataError",{error:u}),{cause:c})}finally{s.end("OpenAI-GenerateContent-Total")}}async generateContentStream(e,r){let n=await this.generateContent(e,r);async function*o(){yield n}return o()}async countTokens(e,r=!1){let n=e.useCache??!0;if(!r&&this.lastUsageMetadata?.total_tokens)return{totalTokens:this.lastUsageMetadata.total_tokens};let o=this.extractTextFromRequest(e);return{totalTokens:Math.ceil(o.length/4)}}async calculateInputTokens(e){try{let r={model:this.modelName,contents:e.contents,config:{systemInstruction:e.config?.systemInstruction}};return(await this.countTokens(r)).totalTokens||0}catch{let n=this.extractTextFromRequest({model:this.modelName,contents:e.contents});return Math.ceil(n.length/4)}}async embedContent(e){try{let r=this.extractTextFromEmbedRequest(e),n=this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl,o=await fetch(`${n}/v1/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.modelName,input:r})});if(!o.ok){let a=await o.text();throw new Error(`HTTP error! status: ${o.status}, body: ${a}`)}return{embeddings:[{values:(await o.json()).data[0].embedding}]}}catch(r){throw B3(r),new Error(O.t("openaiContentGenerator.errors.embedContentFailed",{error:r instanceof Error?r.message:String(r)}))}}applyGlmPromptCacheFormat(e){let r=[],n=[];for(let s of e)s.role==="system"?r.push({type:"text",text:s.content||"",cache_control:{type:"ephemeral"}}):n.push(s);let o={};return r.length>0&&(o.system=r),{regularMessages:n,extendParams:o}}applyGlmRequestBodyTransform(e){let{regularMessages:r,extendParams:n}=this.applyGlmPromptCacheFormat(e.messages);e.messages=r,e.extendParams||(e.extendParams={});for(let[o,s]of Object.entries(n))o==="system"&&Array.isArray(s)?e.extendParams.system&&Array.isArray(e.extendParams.system)?e.extendParams.system=[...e.extendParams.system,...s]:e.extendParams.system=s:o in e.extendParams||(e.extendParams[o]=s)}async convertToOpenAIMessages(e){let r=[],n=new Set,o=new Map;if(e.contents){let s=Array.isArray(e.contents)?e.contents:[e.contents];for(let a of s)if(typeof a=="object"&&a!==null&&"parts"in a&&a.parts){let c=Array.isArray(a.parts)?a.parts:[a.parts];for(let u of c){if(u.functionCall){let d=u.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;n.add(d)}if(u.functionResponse){let d=u.functionResponse.id||u.functionResponse.name||"",f=u.functionResponse.response?.output??(u.functionResponse.response?JSON.stringify(u.functionResponse.response):"");o.set(d,{role:"tool",tool_call_id:d,content:f})}}}for(let[a]of o)n.has(a)||o.delete(a)}if(e.config?.systemInstruction){let s=this.extractSystemInstruction(e.config.systemInstruction);s&&r.push({role:"system",content:s})}if(e.contents){let s=Array.isArray(e.contents)?e.contents:[e.contents];for(let a of s){if(typeof a=="string"){r.push({role:"user",content:a});continue}if(typeof a=="object"&&a!==null&&"text"in a&&a.text){r.push({role:"user",content:a.text});continue}if(typeof a=="object"&&a!==null&&"parts"in a&&a.parts){let c=Array.isArray(a.parts)?a.parts:[a.parts];if(a.role==="model"){let u={role:"assistant",content:"",tool_calls:[]};for(let d of c)if(d.thought&&"text"in d&&d.text?u.reasoning_content=d.text:"text"in d&&d.text&&(u.content=d.text),d.functionCall){let f=d.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;u.tool_calls.push({id:f,function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})},type:"function"})}if((u.content||u.tool_calls.length>0)&&(u.tool_calls.length===0&&delete u.tool_calls,r.push(u),u.tool_calls&&u.tool_calls.length>0))for(let d of u.tool_calls){let f=o.get(d.id);f?r.push(f):r.push({role:"tool",tool_call_id:d.id,content:O.t("openaiContentGenerator.messages.toolNotExecuted")})}}else{let u=[];for(let d of c)if("text"in d&&d.text)u.push({type:"text",text:d.text});else if(d.inlineData){let f=d.inlineData;if(f.mimeType&&f.mimeType.startsWith("image/")){let p=this.authType===Yt.IFLOW||this.authType===Yt.LOGIN_WITH_IFLOW||this.baseUrl&&this.baseUrl.toLowerCase().includes("apis.iflow.cn"),h=this.authType===Yt.AONE||this.authType===Yt.LOGIN_WITH_AONE;if(!p&&!h&&X9.isMultimodalModel(this.modelName))r.push({role:"user",content:[{type:"image_url",image_url:{url:"data:"+f.mimeType+";base64,"+f.data}}]});else try{if(!f.data)throw new Error(O.t("openaiContentGenerator.errors.imageDataMissing"));let m=await this.multimodalHelper.generateImageDescription(f.data,f.mimeType);u.push({type:"text",text:`[Image Description]: ${m}`})}catch(m){B3(m),u.push({type:"text",text:O.t("openaiContentGenerator.errors.imageContentCannotParse",{error:m instanceof Error?m.message:String(m)})})}}}u.length>0&&r.push({role:"user",content:u})}}}}return r}createGeminiResponse(){let e=new Zz;return e.candidates=[{content:{parts:[],role:"model"}}],e}async convertFromOpenAIResponse(e){let r=e.choices[0],n=this.createGeminiResponse(),o=n.candidates?.[0],s=!1;if(!r||!r.message)return{response:n,hadJsonFixes:s};if(r.message.reasoning_content&&o?.content?.parts&&o.content.parts.push({thought:!0,text:r.message.reasoning_content}),r.message.reasoning&&o?.content?.parts&&o.content.parts.push({thought:!0,text:r.message.reasoning}),r.message.content&&r.message.content.trim()&&o?.content?.parts&&o.content.parts.push({text:r.message.content}),r.message.tool_calls&&Array.isArray(r.message.tool_calls))for(let a of r.message.tool_calls){let c;try{c=JSON.parse(a.function.arguments)}catch(u){if(B3(u),this.baseUrl==="https://apis.iflow.cn/v1"||this.baseUrl==="https://ducky.code.alibaba-inc.com/v1/openai")try{c=await this.fixInvalidJsonWithQwen(a.function.arguments),s=!0}catch(d){B3(d),console.error("Failed to fix JSON",d),c={}}else c={}}o?.content?.parts?.push({functionCall:{id:a.id,name:a.function.name,args:c}})}return o&&r.finish_reason!=="tool_calls"&&r.finish_reason&&(o.finishReason=this.mapFinishReason(r.finish_reason)),n.usageMetadata={promptTokenCount:e.usage?.prompt_tokens||0,candidatesTokenCount:e.usage?.completion_tokens||0,totalTokenCount:e.usage?.total_tokens||0},{response:n,hadJsonFixes:s}}async fixInvalidJsonWithQwen(e){let r=`
|
|
937
937
|
\u4F60\u662F\u4E00\u4E2Ajson\u683C\u5F0F\u4F18\u5316\u4E13\u5BB6\uFF0C\u4F60\u7684\u5DE5\u4F5C\u662F\u5C06\u4E00\u4E32\u6587\u672C\uFF0C\u6839\u636Ejson schema\u7684\u5B9A\u4E49\u8F93\u51FA\u6210\u4E00\u4E2Avalid\u7684json
|
|
938
938
|
\u8FD9\u4E2A\u662F\u9519\u8BEF\u7684json\u683C\u5F0F\uFF1A
|
|
939
939
|
${e}
|
|
@@ -946,7 +946,7 @@ Otherwise navigate to:
|
|
|
946
946
|
|
|
947
947
|
${e}
|
|
948
948
|
|
|
949
|
-
`);try{(await fA(e)).on("error",s=>{throw new Error(`BROWSER_LAUNCH_FAILED: Failed to open browser automatically: ${s.message}. Please navigate to the URL manually.`)})}catch(o){throw new Error(`BROWSER_LAUNCH_FAILED: An unexpected error occurred while trying to open the browser: ${o}. Please navigate to the URL manually.`)}console.log("Waiting for authentication...");let n=0;for(;n<r.maxRetries;){await sFr(r.pollInterval);let o=await aFr(t,r);if(o.isSuccess()){let s=o.getPrivateToken();return await Z9.savePrivateToken(s),console.log("Aone authentication successful!"),!0}o.getError()&&console.log(`Waiting for authentication... (${n+1}/${r.maxRetries})`),n++}throw new Error("Authentication timeout. Please try again.")}async function XOe(t=new cJ){return await Z9.hasValidToken()?(console.log("Using cached Aone authentication."),!0):await cFr(t)}async function Vx(){return await Z9.loadPrivateToken()}async function JOe(){await Z9.clearPrivateToken(),console.log("Aone authentication cleared.")}async function Ymo(){return await Z9.hasValidToken()}async function Kmo(t=new cJ){return await JOe(),await XOe(t)}var ZOe=te(()=>{"use strict";p6t();f9();nFr();iFr();oFr();});async function h6t(t,e,r,n,o){if(e===Yt.LOGIN_WITH_IFLOW){await WF(e,r,o);let s=await Y4();if(!s)throw new Error("No API key found. Please re-authenticate.");let a=r.getContentGeneratorConfig();return new DU({model:r.getModel(),apiKey:s,baseUrl:a?.baseUrl||dhe,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen3-vl-plus",config:r})}if(e===Yt.LOGIN_WITH_AONE){if(!await XOe())throw new Error("Aone authentication failed. Please try again.");let a=await Vx();if(!a)throw new Error("No Aone private token found. Please re-authenticate.");let c=r.getContentGeneratorConfig(),u=Buffer.from(a,"utf8").toString("base64");return new DU({model:r.getModel(),apiKey:u,baseUrl:c?.baseUrl||"https://ducky.code.alibaba-inc.com/v1/openai",authType:e,debugMode:r.getDebugMode(),multimodalModelName:c?.multimodalModelName,config:r})}if(e===Yt.CLOUD_SHELL){let s=await WF(e,r),a=await I0r(s);return new A9(s,a.projectId,t,n,a.userTier)}throw new Error(`Unsupported authType: ${e}`)}var m6t=te(()=>{"use strict";A_();zR();D0r();gSe();s6t();TC();ZOe();});function Xmo(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function Wx(t){let e=Xmo(t),r=`IFLOW_${t}`;if(process.env[r])return process.env[r];let n=`IFLOW_${e}`;if(process.env[n])return process.env[n];let o=`iflow_${t}`;if(process.env[o])return process.env[o];let s=`iflow_${e}`;if(process.env[s])return process.env[s]}function mhe(){return Wx("apiKey")}function ghe(){return Wx("baseUrl")||Wx("url")}function Ahe(){return Wx("modelName")||Wx("model")}function lFr(t){let e=Wx(t);if(e===void 0)return;let r=e.toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}function uFr(t){let e=Wx(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function dFr(t){let e=Wx(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function eke(){return!!(mhe()||ghe()||Ahe())}function g6t(){let t={},e=["theme","selectedAuthType","sandbox","toolDiscoveryCommand","toolCallCommand","mcpServerCommand","contextFileName","preferredEditor","apiKey","baseUrl","modelName","searchApiKey","multimodalModelName","memoryImportFormat"],r=["useExternalAuth","showMemoryUsage","usageStatisticsEnabled","autoConfigureMaxOldSpaceSize","hideWindowTitle","hideTips","hideBanner","vimMode","ideModeFeature","ideMode","disableAutoUpdate","skipNextSpeakerCheck","useRipgrep","debugKeystrokeLogging","pasteFromClipboard"],n=["maxSessionTurns","memoryDiscoveryMaxDirs","tokensLimit","compressionTokenThreshold","shellTimeout","temperature","topP"],o=["coreTools","excludeTools","allowMCPServers","excludeMCPServers"];return e.forEach(s=>{let a=Wx(s);a!==void 0&&(t[s]=a)}),r.forEach(s=>{let a=lFr(s);a!==void 0&&(t[s]=a)}),n.forEach(s=>{let a=uFr(s);a!==void 0&&(t[s]=a)}),o.forEach(s=>{let a=dFr(s);a!==void 0&&(t[s]=a)}),t}function Jmo(){return{apiKey:mhe(),baseUrl:ghe(),model:Ahe()}}var A6t=te(()=>{"use strict";});async function y6t(t,e,r){if(await Jz())try{await fSe()||console.log("OAuth2 credentials cleared due to expiration. Please authenticate when prompted.")}catch(p){throw p instanceof Error&&p.message.includes("SERVER_OAUTH2_REQUIRED"),p}let o=mhe(),s=ghe(),a=Ahe(),c=r?.apiKey||o,u=r?.baseUrl||s||Zmo[e],d=r?.modelName||t.getModel()||a||N_,f={model:d,authType:e,proxy:t?.getProxy(),debugMode:t?.getDebugMode(),config:t};return e===Yt.CLOUD_SHELL?f:e===Yt.LOGIN_WITH_IFLOW?(f.baseUrl=u||dhe,f.multimodalModelName="qwen3-vl-plus",c&&(f.apiKey=c),f):([...O_,Yt.OPENAI_COMPATIBLE].includes(e)&&c&&(f.apiKey=c,f.baseUrl=u,f.model=d),f)}async function _6t(t,e,r,n){let s={headers:{"User-Agent":`iFlowCLI/0.4.2 (${process.platform}; ${process.arch})`}};if(t.authType&&[...O_,Yt.IDEA_LAB].includes(t.authType)||t.authType===Yt.OPENAI_COMPATIBLE)return new DU({...t,config:e});if(t.authType===Yt.LOGIN_WITH_IFLOW||t.authType===Yt.LOGIN_WITH_AONE||t.authType===Yt.CLOUD_SHELL)return h6t(s,t.authType,e,r,n);throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var Yt,O_,Zmo,A_=te(()=>{"use strict";m6t();TC();s6t();A6t();zR();(function(t){t.LOGIN_WITH_IFLOW="oauth-iflow",t.LOGIN_WITH_AONE="oauth-aone",t.CLOUD_SHELL="cloud-shell",t.IFLOW="iflow",t.AONE="aone",t.IDEA_LAB="idealab",t.OPENAI_COMPATIBLE="openai-compatible"})(Yt||(Yt={}));O_=[Yt.IFLOW,Yt.AONE],Zmo={[Yt.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[Yt.IFLOW]:dhe,[Yt.AONE]:FMr}});var tke,fFr=te(()=>{"use strict";tke=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let r=`${e.serverName}_${e.name}`;console.warn(`Prompt with name "${e.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...e,name:r})}else this.prompts.set(e.name,e)}getAllPrompts(){return Array.from(this.prompts.values()).sort((e,r)=>e.name.localeCompare(r.name))}getPrompt(e){return this.prompts.get(e)}getPromptsByServer(e){let r=[];for(let n of this.prompts.values())n.serverName===e&&r.push(n);return r.sort((n,o)=>n.name.localeCompare(o.name))}clear(){this.prompts.clear()}removePromptsByServer(e){for(let[r,n]of this.prompts.entries())n.serverName===e&&this.prompts.delete(r)}}});var wn,Ev=te(()=>{"use strict";(function(t){t.INVALID_TOOL_PARAMS="invalid_tool_params",t.UNKNOWN="unknown",t.UNHANDLED_EXCEPTION="unhandled_exception",t.TOOL_NOT_REGISTERED="tool_not_registered",t.EXECUTION_FAILED="execution_failed",t.FILE_NOT_FOUND="file_not_found",t.FILE_WRITE_FAILURE="file_write_failure",t.READ_CONTENT_FAILURE="read_content_failure",t.ATTEMPT_TO_CREATE_EXISTING_FILE="attempt_to_create_existing_file",t.FILE_TOO_LARGE="file_too_large",t.PERMISSION_DENIED="permission_denied",t.NO_SPACE_LEFT="no_space_left",t.TARGET_IS_DIRECTORY="target_is_directory",t.PATH_NOT_IN_WORKSPACE="path_not_in_workspace",t.SEARCH_PATH_NOT_FOUND="search_path_not_found",t.SEARCH_PATH_NOT_A_DIRECTORY="search_path_not_a_directory",t.EDIT_PREPARATION_FAILURE="edit_preparation_failure",t.EDIT_NO_OCCURRENCE_FOUND="edit_no_occurrence_found",t.EDIT_EXPECTED_OCCURRENCE_MISMATCH="edit_expected_occurrence_mismatch",t.EDIT_NO_CHANGE="edit_no_change",t.GLOB_EXECUTION_ERROR="glob_execution_error",t.GREP_EXECUTION_ERROR="grep_execution_error",t.LS_EXECUTION_ERROR="ls_execution_error",t.PATH_IS_NOT_A_DIRECTORY="path_is_not_a_directory",t.MCP_TOOL_ERROR="mcp_tool_error",t.MEMORY_TOOL_EXECUTION_ERROR="memory_tool_execution_error",t.READ_MANY_FILES_SEARCH_ERROR="read_many_files_search_error",t.DISCOVERED_TOOL_EXECUTION_ERROR="discovered_tool_execution_error",t.WEB_FETCH_NO_URL_IN_PROMPT="web_fetch_no_url_in_prompt",t.WEB_FETCH_FALLBACK_FAILED="web_fetch_fallback_failed",t.WEB_FETCH_PROCESSING_ERROR="web_fetch_processing_error",t.WEB_SEARCH_FAILED="web_search_failed",t.HOOK_BLOCKED="hook_blocked"})(wn||(wn={}))});var ra,E6t,Un,zx,yhe=te(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let a of o)s[a]=a;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of s)a[c]=o[c];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},t.find=(o,s)=>{for(let a of o)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ra||(ra={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(E6t||(E6t={}));Un=ra.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zx=t=>{switch(typeof t){case"undefined":return Un.undefined;case"string":return Un.string;case"number":return Number.isNaN(t)?Un.nan:Un.number;case"boolean":return Un.boolean;case"function":return Un.function;case"bigint":return Un.bigint;case"symbol":return Un.symbol;case"object":return Array.isArray(t)?Un.array:t===null?Un.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Un.promise:typeof Map<"u"&&t instanceof Map?Un.map:typeof Set<"u"&&t instanceof Set?Un.set:typeof Date<"u"&&t instanceof Date?Un.date:Un.object;default:return Un.unknown}}});var zr,ego,M3,rke=te(()=>{yhe();zr=ra.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"]),ego=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),M3=class t 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 r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let a of s.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(r(a));else{let c=n,u=0;for(;u<a.path.length;){let d=a.path[u];u===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(r(a))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ra.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};M3.create=t=>new M3(t)});var tgo,e7,v6t=te(()=>{rke();yhe();tgo=(t,e)=>{let r;switch(t.code){case zr.invalid_type:t.received===Un.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case zr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ra.jsonStringifyReplacer)}`;break;case zr.unrecognized_keys:r=`Unrecognized key(s) in object: ${ra.joinValues(t.keys,", ")}`;break;case zr.invalid_union:r="Invalid input";break;case zr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ra.joinValues(t.options)}`;break;case zr.invalid_enum_value:r=`Invalid enum value. Expected ${ra.joinValues(t.options)}, received '${t.received}'`;break;case zr.invalid_arguments:r="Invalid function arguments";break;case zr.invalid_return_type:r="Invalid function return type";break;case zr.invalid_date:r="Invalid date";break;case zr.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ra.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case zr.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case zr.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case zr.custom:r="Invalid input";break;case zr.invalid_intersection_types:r="Intersection results could not be merged";break;case zr.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case zr.not_finite:r="Number must be finite";break;default:r=e.defaultError,ra.assertNever(t)}return{message:r}},e7=tgo});function rgo(t){pFr=t}function lJ(){return pFr}var pFr,nke=te(()=>{v6t();pFr=e7});function En(t,e){let r=lJ(),n=_he({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===e7?void 0:e7].filter(o=>!!o)});t.common.issues.push(n)}var _he,ngo,l0,Xi,RU,OA,ike,oke,AO,uJ,b6t=te(()=>{nke();v6t();_he=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="",u=n.filter(d=>!!d).slice().reverse();for(let d of u)c=d(a,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},ngo=[];l0=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return Xi;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,a=await o.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return Xi;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},Xi=Object.freeze({status:"aborted"}),RU=t=>({status:"dirty",value:t}),OA=t=>({status:"valid",value:t}),ike=t=>t.status==="aborted",oke=t=>t.status==="dirty",AO=t=>t.status==="valid",uJ=t=>typeof Promise<"u"&&t instanceof Promise});var hFr=te(()=>{});var Ei,mFr=te(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Ei||(Ei={}))});function ds(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,c)=>{let{message:u}=t;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:u??n??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:u??r??c.defaultError}},description:o}}function _Fr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Ego(t){return new RegExp(`^${_Fr(t)}$`)}function EFr(t){let e=`${yFr}T${_Fr(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vgo(t,e){return!!((e==="v4"||!e)&&pgo.test(t)||(e==="v6"||!e)&&mgo.test(t))}function bgo(t,e){if(!lgo.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Cgo(t,e){return!!((e==="v4"||!e)&&hgo.test(t)||(e==="v6"||!e)&&ggo.test(t))}function Sgo(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}function dJ(t){if(t instanceof F3){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=vv.create(dJ(n))}return new F3({...t._def,shape:()=>e})}else return t instanceof n7?new n7({...t._def,type:dJ(t.element)}):t instanceof vv?vv.create(dJ(t.unwrap())):t instanceof Kx?Kx.create(dJ(t.unwrap())):t instanceof Yx?Yx.create(t.items.map(e=>dJ(e))):t}function S6t(t,e){let r=zx(t),n=zx(e);if(t===e)return{valid:!0,data:t};if(r===Un.object&&n===Un.object){let o=ra.objectKeys(e),s=ra.objectKeys(t).filter(c=>o.indexOf(c)!==-1),a={...t,...e};for(let c of s){let u=S6t(t[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(r===Un.array&&n===Un.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let a=t[s],c=e[s],u=S6t(a,c);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return r===Un.date&&n===Un.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function vFr(t,e){return new jU({values:t,typeName:oo.ZodEnum,...ds(e)})}function AFr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function bFr(t,e={},r){return t?_O.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let c=AFr(e,n),u=c.fatal??r??!0;o.addIssue({code:"custom",...c,fatal:u})}});if(!s){let a=AFr(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}}):_O.create()}var bv,gFr,Ts,igo,ogo,sgo,ago,cgo,lgo,ugo,dgo,fgo,C6t,pgo,hgo,mgo,ggo,Ago,ygo,yFr,_go,yO,NU,OU,kU,BU,fJ,PU,MU,_O,r7,IC,pJ,n7,F3,FU,t7,ske,LU,Yx,ake,hJ,mJ,cke,UU,QU,jU,GU,EO,Cv,vv,Kx,$U,qU,gJ,xgo,Ehe,vhe,HU,wgo,oo,Tgo,CFr,SFr,Igo,Dgo,xFr,Rgo,Ngo,Ogo,kgo,Bgo,Pgo,Mgo,Fgo,Lgo,Ugo,Qgo,jgo,Ggo,$go,qgo,Hgo,Vgo,Wgo,zgo,Ygo,Kgo,Xgo,Jgo,Zgo,e0o,t0o,r0o,n0o,i0o,o0o,s0o,a0o,c0o,l0o,wFr=te(()=>{rke();nke();mFr();b6t();yhe();bv=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},gFr=(t,e)=>{if(AO(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new M3(t.common.issues);return this._error=r,this._error}}};Ts=class{get description(){return this._def.description}_getType(e){return zx(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:zx(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new l0,ctx:{common:e.parent.common,data:e.data,parsedType:zx(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(uJ(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zx(e)},o=this._parseSync({data:e,path:n.path,parent:n});return gFr(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zx(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return AO(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>AO(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zx(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(uJ(o)?o:Promise.resolve(o));return gFr(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let a=e(o),c=()=>s.addIssue({code:zr.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Cv({schema:this,typeName:oo.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:r=>this["~validate"](r)}}optional(){return vv.create(this,this._def)}nullable(){return Kx.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return n7.create(this)}promise(){return EO.create(this,this._def)}or(e){return FU.create([this,e],this._def)}and(e){return LU.create(this,e,this._def)}transform(e){return new Cv({...ds(this._def),schema:this,typeName:oo.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new $U({...ds(this._def),innerType:this,defaultValue:r,typeName:oo.ZodDefault})}brand(){return new Ehe({typeName:oo.ZodBranded,type:this,...ds(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new qU({...ds(this._def),innerType:this,catchValue:r,typeName:oo.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vhe.create(this,e)}readonly(){return HU.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},igo=/^c[^\s-]{8,}$/i,ogo=/^[0-9a-z]+$/,sgo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ago=/^[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,cgo=/^[a-z0-9_-]{21}$/i,lgo=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ugo=/^[-+]?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)?)??$/,dgo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fgo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pgo=/^(?:(?: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])$/,hgo=/^(?:(?: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])$/,mgo=/^(([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]))$/,ggo=/^(([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])$/,Ago=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ygo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yFr="((\\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])))",_go=new RegExp(`^${yFr}$`);yO=class t extends Ts{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Un.string){let s=this._getOrReturnCtx(e);return En(s,{code:zr.invalid_type,expected:Un.string,received:s.parsedType}),Xi}let n=new l0,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),En(o,{code:zr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),En(o,{code:zr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,c=e.data.length<s.value;(a||c)&&(o=this._getOrReturnCtx(e,o),a?En(o,{code:zr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&En(o,{code:zr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")dgo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"email",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")C6t||(C6t=new RegExp(fgo,"u")),C6t.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"emoji",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")ago.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"uuid",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")cgo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"nanoid",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")igo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"cuid",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")ogo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"cuid2",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")sgo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"ulid",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),En(o,{validation:"url",code:zr.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"regex",code:zr.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?EFr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?_go.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Ego(s).test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ugo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"duration",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?vgo(e.data,s.version)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"ip",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?bgo(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"jwt",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Cgo(e.data,s.version)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"cidr",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Ago.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"base64",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ygo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"base64url",code:zr.invalid_string,message:s.message}),n.dirty()):ra.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:zr.invalid_string,...Ei.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Ei.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ei.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ei.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ei.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ei.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ei.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ei.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ei.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ei.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ei.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ei.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ei.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ei.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Ei.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Ei.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Ei.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Ei.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...Ei.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Ei.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Ei.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Ei.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Ei.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Ei.errToObj(r)})}nonempty(e){return this.min(1,Ei.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};yO.create=t=>new yO({checks:[],typeName:oo.ZodString,coerce:t?.coerce??!1,...ds(t)});NU=class t extends Ts{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)),this._getType(e)!==Un.number){let s=this._getOrReturnCtx(e);return En(s,{code:zr.invalid_type,expected:Un.number,received:s.parsedType}),Xi}let n,o=new l0;for(let s of this._def.checks)s.kind==="int"?ra.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),En(n,{code:zr.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Sgo(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),En(n,{code:zr.not_finite,message:s.message}),o.dirty()):ra.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Ei.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Ei.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Ei.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Ei.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Ei.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Ei.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ei.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ei.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ei.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ei.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Ei.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Ei.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ei.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ei.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ra.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};NU.create=t=>new NU({checks:[],typeName:oo.ZodNumber,coerce:t?.coerce||!1,...ds(t)});OU=class t extends Ts{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)!==Un.bigint)return this._getInvalidInput(e);let n,o=new l0;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ra.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return En(r,{code:zr.invalid_type,expected:Un.bigint,received:r.parsedType}),Xi}gte(e,r){return this.setLimit("min",e,!0,Ei.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Ei.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Ei.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Ei.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Ei.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ei.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ei.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ei.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ei.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Ei.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};OU.create=t=>new OU({checks:[],typeName:oo.ZodBigInt,coerce:t?.coerce??!1,...ds(t)});kU=class extends Ts{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Un.boolean){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.boolean,received:n.parsedType}),Xi}return OA(e.data)}};kU.create=t=>new kU({typeName:oo.ZodBoolean,coerce:t?.coerce||!1,...ds(t)});BU=class t extends Ts{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Un.date){let s=this._getOrReturnCtx(e);return En(s,{code:zr.invalid_type,expected:Un.date,received:s.parsedType}),Xi}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return En(s,{code:zr.invalid_date}),Xi}let n=new l0,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),En(o,{code:zr.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),En(o,{code:zr.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ra.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Ei.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Ei.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};BU.create=t=>new BU({checks:[],coerce:t?.coerce||!1,typeName:oo.ZodDate,...ds(t)});fJ=class extends Ts{_parse(e){if(this._getType(e)!==Un.symbol){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.symbol,received:n.parsedType}),Xi}return OA(e.data)}};fJ.create=t=>new fJ({typeName:oo.ZodSymbol,...ds(t)});PU=class extends Ts{_parse(e){if(this._getType(e)!==Un.undefined){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.undefined,received:n.parsedType}),Xi}return OA(e.data)}};PU.create=t=>new PU({typeName:oo.ZodUndefined,...ds(t)});MU=class extends Ts{_parse(e){if(this._getType(e)!==Un.null){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.null,received:n.parsedType}),Xi}return OA(e.data)}};MU.create=t=>new MU({typeName:oo.ZodNull,...ds(t)});_O=class extends Ts{constructor(){super(...arguments),this._any=!0}_parse(e){return OA(e.data)}};_O.create=t=>new _O({typeName:oo.ZodAny,...ds(t)});r7=class extends Ts{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OA(e.data)}};r7.create=t=>new r7({typeName:oo.ZodUnknown,...ds(t)});IC=class extends Ts{_parse(e){let r=this._getOrReturnCtx(e);return En(r,{code:zr.invalid_type,expected:Un.never,received:r.parsedType}),Xi}};IC.create=t=>new IC({typeName:oo.ZodNever,...ds(t)});pJ=class extends Ts{_parse(e){if(this._getType(e)!==Un.undefined){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.void,received:n.parsedType}),Xi}return OA(e.data)}};pJ.create=t=>new pJ({typeName:oo.ZodVoid,...ds(t)});n7=class t extends Ts{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==Un.array)return En(r,{code:zr.invalid_type,expected:Un.array,received:r.parsedType}),Xi;if(o.exactLength!==null){let a=r.data.length>o.exactLength.value,c=r.data.length<o.exactLength.value;(a||c)&&(En(r,{code:a?zr.too_big:zr.too_small,minimum:c?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&&r.data.length<o.minLength.value&&(En(r,{code:zr.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(En(r,{code:zr.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,c)=>o.type._parseAsync(new bv(r,a,r.path,c)))).then(a=>l0.mergeArray(n,a));let s=[...r.data].map((a,c)=>o.type._parseSync(new bv(r,a,r.path,c)));return l0.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:Ei.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:Ei.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:Ei.toString(r)}})}nonempty(e){return this.min(1,e)}};n7.create=(t,e)=>new n7({type:t,minLength:null,maxLength:null,exactLength:null,typeName:oo.ZodArray,...ds(e)});F3=class t extends Ts{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(),r=ra.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==Un.object){let d=this._getOrReturnCtx(e);return En(d,{code:zr.invalid_type,expected:Un.object,received:d.parsedType}),Xi}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof IC&&this._def.unknownKeys==="strip"))for(let d in o.data)a.includes(d)||c.push(d);let u=[];for(let d of a){let f=s[d],p=o.data[d];u.push({key:{status:"valid",value:d},value:f._parse(new bv(o,p,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof IC){let d=this._def.unknownKeys;if(d==="passthrough")for(let f of c)u.push({key:{status:"valid",value:f},value:{status:"valid",value:o.data[f]}});else if(d==="strict")c.length>0&&(En(o,{code:zr.unrecognized_keys,keys:c}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let f of c){let p=o.data[f];u.push({key:{status:"valid",value:f},value:d._parse(new bv(o,p,o.path,f)),alwaysSet:f in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let d=[];for(let f of u){let p=await f.key,h=await f.value;d.push({key:p,value:h,alwaysSet:f.alwaysSet})}return d}).then(d=>l0.mergeObjectSync(n,d)):l0.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return Ei.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Ei.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:oo.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ra.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ra.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return dJ(this)}partial(e){let r={};for(let n of ra.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ra.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof vv;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return vFr(ra.objectKeys(this.shape))}};F3.create=(t,e)=>new F3({shape:()=>t,unknownKeys:"strip",catchall:IC.create(),typeName:oo.ZodObject,...ds(e)});F3.strictCreate=(t,e)=>new F3({shape:()=>t,unknownKeys:"strict",catchall:IC.create(),typeName:oo.ZodObject,...ds(e)});F3.lazycreate=(t,e)=>new F3({shape:t,unknownKeys:"strip",catchall:IC.create(),typeName:oo.ZodObject,...ds(e)});FU=class extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;let a=s.map(c=>new M3(c.ctx.common.issues));return En(r,{code:zr.invalid_union,unionErrors:a}),Xi}if(r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s,a=[];for(let u of n){let d={...r,common:{...r.common,issues:[]},parent:null},f=u._parseSync({data:r.data,path:r.path,parent:d});if(f.status==="valid")return f;f.status==="dirty"&&!s&&(s={result:f,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let c=a.map(u=>new M3(u));return En(r,{code:zr.invalid_union,unionErrors:c}),Xi}}get options(){return this._def.options}};FU.create=(t,e)=>new FU({options:t,typeName:oo.ZodUnion,...ds(e)});t7=t=>t instanceof UU?t7(t.schema):t instanceof Cv?t7(t.innerType()):t instanceof QU?[t.value]:t instanceof jU?t.options:t instanceof GU?ra.objectValues(t.enum):t instanceof $U?t7(t._def.innerType):t instanceof PU?[void 0]:t instanceof MU?[null]:t instanceof vv?[void 0,...t7(t.unwrap())]:t instanceof Kx?[null,...t7(t.unwrap())]:t instanceof Ehe||t instanceof HU?t7(t.unwrap()):t instanceof qU?t7(t._def.innerType):[],ske=class t extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Un.object)return En(r,{code:zr.invalid_type,expected:Un.object,received:r.parsedType}),Xi;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(En(r,{code:zr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Xi)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let a=t7(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,s)}}return new t({typeName:oo.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ds(n)})}};LU=class extends Ts{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,a)=>{if(ike(s)||ike(a))return Xi;let c=S6t(s.value,a.value);return c.valid?((oke(s)||oke(a))&&r.dirty(),{status:r.value,value:c.data}):(En(n,{code:zr.invalid_intersection_types}),Xi)};return n.common.async?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(([s,a])=>o(s,a)):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}))}};LU.create=(t,e,r)=>new LU({left:t,right:e,typeName:oo.ZodIntersection,...ds(r)});Yx=class t extends Ts{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Un.array)return En(n,{code:zr.invalid_type,expected:Un.array,received:n.parsedType}),Xi;if(n.data.length<this._def.items.length)return En(n,{code:zr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Xi;!this._def.rest&&n.data.length>this._def.items.length&&(En(n,{code:zr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,c)=>{let u=this._def.items[c]||this._def.rest;return u?u._parse(new bv(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>l0.mergeArray(r,a)):l0.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Yx.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Yx({items:t,typeName:oo.ZodTuple,rest:null,...ds(e)})};ake=class t extends Ts{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Un.object)return En(n,{code:zr.invalid_type,expected:Un.object,received:n.parsedType}),Xi;let o=[],s=this._def.keyType,a=this._def.valueType;for(let c in n.data)o.push({key:s._parse(new bv(n,c,n.path,c)),value:a._parse(new bv(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?l0.mergeObjectAsync(r,o):l0.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ts?new t({keyType:e,valueType:r,typeName:oo.ZodRecord,...ds(n)}):new t({keyType:yO.create(),valueType:e,typeName:oo.ZodRecord,...ds(r)})}},hJ=class extends Ts{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Un.map)return En(n,{code:zr.invalid_type,expected:Un.map,received:n.parsedType}),Xi;let o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([c,u],d)=>({key:o._parse(new bv(n,c,n.path,[d,"key"])),value:s._parse(new bv(n,u,n.path,[d,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let u of a){let d=await u.key,f=await u.value;if(d.status==="aborted"||f.status==="aborted")return Xi;(d.status==="dirty"||f.status==="dirty")&&r.dirty(),c.set(d.value,f.value)}return{status:r.value,value:c}})}else{let c=new Map;for(let u of a){let d=u.key,f=u.value;if(d.status==="aborted"||f.status==="aborted")return Xi;(d.status==="dirty"||f.status==="dirty")&&r.dirty(),c.set(d.value,f.value)}return{status:r.value,value:c}}}};hJ.create=(t,e,r)=>new hJ({valueType:e,keyType:t,typeName:oo.ZodMap,...ds(r)});mJ=class t extends Ts{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Un.set)return En(n,{code:zr.invalid_type,expected:Un.set,received:n.parsedType}),Xi;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(En(n,{code:zr.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(En(n,{code:zr.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function a(u){let d=new Set;for(let f of u){if(f.status==="aborted")return Xi;f.status==="dirty"&&r.dirty(),d.add(f.value)}return{status:r.value,value:d}}let c=[...n.data.values()].map((u,d)=>s._parse(new bv(n,u,n.path,d)));return n.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,r){return new t({...this._def,minSize:{value:e,message:Ei.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:Ei.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};mJ.create=(t,e)=>new mJ({valueType:t,minSize:null,maxSize:null,typeName:oo.ZodSet,...ds(e)});cke=class t extends Ts{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Un.function)return En(r,{code:zr.invalid_type,expected:Un.function,received:r.parsedType}),Xi;function n(c,u){return _he({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lJ(),e7].filter(d=>!!d),issueData:{code:zr.invalid_arguments,argumentsError:u}})}function o(c,u){return _he({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lJ(),e7].filter(d=>!!d),issueData:{code:zr.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof EO){let c=this;return OA(async function(...u){let d=new M3([]),f=await c._def.args.parseAsync(u,s).catch(m=>{throw d.addIssue(n(u,m)),d}),p=await Reflect.apply(a,this,f);return await c._def.returns._def.type.parseAsync(p,s).catch(m=>{throw d.addIssue(o(p,m)),d})})}else{let c=this;return OA(function(...u){let d=c._def.args.safeParse(u,s);if(!d.success)throw new M3([n(u,d.error)]);let f=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(f,s);if(!p.success)throw new M3([o(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Yx.create(e).rest(r7.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Yx.create([]).rest(r7.create()),returns:r||r7.create(),typeName:oo.ZodFunction,...ds(n)})}},UU=class extends Ts{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};UU.create=(t,e)=>new UU({getter:t,typeName:oo.ZodLazy,...ds(e)});QU=class extends Ts{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return En(r,{received:r.data,code:zr.invalid_literal,expected:this._def.value}),Xi}return{status:"valid",value:e.data}}get value(){return this._def.value}};QU.create=(t,e)=>new QU({value:t,typeName:oo.ZodLiteral,...ds(e)});jU=class t extends Ts{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return En(r,{expected:ra.joinValues(n),received:r.parsedType,code:zr.invalid_type}),Xi}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return En(r,{received:r.data,code:zr.invalid_enum_value,options:n}),Xi}return OA(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};jU.create=vFr;GU=class extends Ts{_parse(e){let r=ra.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Un.string&&n.parsedType!==Un.number){let o=ra.objectValues(r);return En(n,{expected:ra.joinValues(o),received:n.parsedType,code:zr.invalid_type}),Xi}if(this._cache||(this._cache=new Set(ra.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ra.objectValues(r);return En(n,{received:n.data,code:zr.invalid_enum_value,options:o}),Xi}return OA(e.data)}get enum(){return this._def.values}};GU.create=(t,e)=>new GU({values:t,typeName:oo.ZodNativeEnum,...ds(e)});EO=class extends Ts{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Un.promise&&r.common.async===!1)return En(r,{code:zr.invalid_type,expected:Un.promise,received:r.parsedType}),Xi;let n=r.parsedType===Un.promise?r.data:Promise.resolve(r.data);return OA(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};EO.create=(t,e)=>new EO({type:t,typeName:oo.ZodPromise,...ds(e)});Cv=class extends Ts{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oo.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:a=>{En(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async c=>{if(r.value==="aborted")return Xi;let u=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return u.status==="aborted"?Xi:u.status==="dirty"?RU(u.value):r.value==="dirty"?RU(u.value):u});{if(r.value==="aborted")return Xi;let c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?Xi:c.status==="dirty"?RU(c.value):r.value==="dirty"?RU(c.value):c}}if(o.type==="refinement"){let a=c=>{let u=o.refinement(c,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?Xi:(c.status==="dirty"&&r.dirty(),a(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?Xi:(c.status==="dirty"&&r.dirty(),a(c.value).then(()=>({status:r.value,value:c.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(!AO(a))return Xi;let c=o.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>AO(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:r.value,value:c})):Xi);ra.assertNever(o)}};Cv.create=(t,e,r)=>new Cv({schema:t,typeName:oo.ZodEffects,effect:e,...ds(r)});Cv.createWithPreprocess=(t,e,r)=>new Cv({schema:e,effect:{type:"preprocess",transform:t},typeName:oo.ZodEffects,...ds(r)});vv=class extends Ts{_parse(e){return this._getType(e)===Un.undefined?OA(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vv.create=(t,e)=>new vv({innerType:t,typeName:oo.ZodOptional,...ds(e)});Kx=class extends Ts{_parse(e){return this._getType(e)===Un.null?OA(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Kx.create=(t,e)=>new Kx({innerType:t,typeName:oo.ZodNullable,...ds(e)});$U=class extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===Un.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};$U.create=(t,e)=>new $U({innerType:t,typeName:oo.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ds(e)});qU=class extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return uJ(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new M3(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new M3(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};qU.create=(t,e)=>new qU({innerType:t,typeName:oo.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ds(e)});gJ=class extends Ts{_parse(e){if(this._getType(e)!==Un.nan){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.nan,received:n.parsedType}),Xi}return{status:"valid",value:e.data}}};gJ.create=t=>new gJ({typeName:oo.ZodNaN,...ds(t)});xgo=Symbol("zod_brand"),Ehe=class extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vhe=class t extends Ts{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Xi:s.status==="dirty"?(r.dirty(),RU(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Xi:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:oo.ZodPipeline})}},HU=class extends Ts{_parse(e){let r=this._def.innerType._parse(e),n=o=>(AO(o)&&(o.value=Object.freeze(o.value)),o);return uJ(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};HU.create=(t,e)=>new HU({innerType:t,typeName:oo.ZodReadonly,...ds(e)});wgo={object:F3.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(oo||(oo={}));Tgo=(t,e={message:`Input not instance of ${t.name}`})=>bFr(r=>r instanceof t,e),CFr=yO.create,SFr=NU.create,Igo=gJ.create,Dgo=OU.create,xFr=kU.create,Rgo=BU.create,Ngo=fJ.create,Ogo=PU.create,kgo=MU.create,Bgo=_O.create,Pgo=r7.create,Mgo=IC.create,Fgo=pJ.create,Lgo=n7.create,Ugo=F3.create,Qgo=F3.strictCreate,jgo=FU.create,Ggo=ske.create,$go=LU.create,qgo=Yx.create,Hgo=ake.create,Vgo=hJ.create,Wgo=mJ.create,zgo=cke.create,Ygo=UU.create,Kgo=QU.create,Xgo=jU.create,Jgo=GU.create,Zgo=EO.create,e0o=Cv.create,t0o=vv.create,r0o=Kx.create,n0o=Cv.createWithPreprocess,i0o=vhe.create,o0o=()=>CFr().optional(),s0o=()=>SFr().optional(),a0o=()=>xFr().optional(),c0o={string:(t=>yO.create({...t,coerce:!0})),number:(t=>NU.create({...t,coerce:!0})),boolean:(t=>kU.create({...t,coerce:!0})),bigint:(t=>OU.create({...t,coerce:!0})),date:(t=>BU.create({...t,coerce:!0}))},l0o=Xi});var se={};Ws(se,{BRAND:()=>xgo,DIRTY:()=>RU,EMPTY_PATH:()=>ngo,INVALID:()=>Xi,NEVER:()=>l0o,OK:()=>OA,ParseStatus:()=>l0,Schema:()=>Ts,ZodAny:()=>_O,ZodArray:()=>n7,ZodBigInt:()=>OU,ZodBoolean:()=>kU,ZodBranded:()=>Ehe,ZodCatch:()=>qU,ZodDate:()=>BU,ZodDefault:()=>$U,ZodDiscriminatedUnion:()=>ske,ZodEffects:()=>Cv,ZodEnum:()=>jU,ZodError:()=>M3,ZodFirstPartyTypeKind:()=>oo,ZodFunction:()=>cke,ZodIntersection:()=>LU,ZodIssueCode:()=>zr,ZodLazy:()=>UU,ZodLiteral:()=>QU,ZodMap:()=>hJ,ZodNaN:()=>gJ,ZodNativeEnum:()=>GU,ZodNever:()=>IC,ZodNull:()=>MU,ZodNullable:()=>Kx,ZodNumber:()=>NU,ZodObject:()=>F3,ZodOptional:()=>vv,ZodParsedType:()=>Un,ZodPipeline:()=>vhe,ZodPromise:()=>EO,ZodReadonly:()=>HU,ZodRecord:()=>ake,ZodSchema:()=>Ts,ZodSet:()=>mJ,ZodString:()=>yO,ZodSymbol:()=>fJ,ZodTransformer:()=>Cv,ZodTuple:()=>Yx,ZodType:()=>Ts,ZodUndefined:()=>PU,ZodUnion:()=>FU,ZodUnknown:()=>r7,ZodVoid:()=>pJ,addIssueToContext:()=>En,any:()=>Bgo,array:()=>Lgo,bigint:()=>Dgo,boolean:()=>xFr,coerce:()=>c0o,custom:()=>bFr,date:()=>Rgo,datetimeRegex:()=>EFr,defaultErrorMap:()=>e7,discriminatedUnion:()=>Ggo,effect:()=>e0o,enum:()=>Xgo,function:()=>zgo,getErrorMap:()=>lJ,getParsedType:()=>zx,instanceof:()=>Tgo,intersection:()=>$go,isAborted:()=>ike,isAsync:()=>uJ,isDirty:()=>oke,isValid:()=>AO,late:()=>wgo,lazy:()=>Ygo,literal:()=>Kgo,makeIssue:()=>_he,map:()=>Vgo,nan:()=>Igo,nativeEnum:()=>Jgo,never:()=>Mgo,null:()=>kgo,nullable:()=>r0o,number:()=>SFr,object:()=>Ugo,objectUtil:()=>E6t,oboolean:()=>a0o,onumber:()=>s0o,optional:()=>t0o,ostring:()=>o0o,pipeline:()=>i0o,preprocess:()=>n0o,promise:()=>Zgo,quotelessJson:()=>ego,record:()=>Hgo,set:()=>Wgo,setErrorMap:()=>rgo,strictObject:()=>Qgo,string:()=>CFr,symbol:()=>Ngo,transformer:()=>e0o,tuple:()=>qgo,undefined:()=>Ogo,union:()=>jgo,unknown:()=>Pgo,util:()=>ra,void:()=>Fgo});var x6t=te(()=>{nke();b6t();hFr();yhe();wFr();rke()});var vO=te(()=>{x6t();x6t()});var AJ,TFr,lke,IFr,DFr,u0o,wv,L3,bhe,Xx,Tv,uke,RFr,dke,NFr,OFr,kFr,Che,Sv,BFr,PFr,bO,VU,fke,d0o,She,xhe,MFr,f0o,p0o,h0o,w6t,FFr,LFr,pke,m0o,hke,mke,gke,UFr,QFr,T6t,jFr,GFr,g0o,A0o,I6t,y0o,D6t,_0o,R6t,E0o,v0o,b0o,C0o,S0o,x0o,w0o,whe,T0o,N6t,O6t,k6t,I0o,D0o,$Fr,R0o,The,N0o,O0o,k0o,B0o,B6t,Ake,FGa,P0o,M0o,qFr,F0o,L0o,U0o,Q0o,j0o,G0o,$0o,q0o,H0o,V0o,W0o,z0o,Y0o,K0o,X0o,J0o,Z0o,P6t,eAo,yke,tAo,rAo,LGa,UGa,QGa,jGa,GGa,$Ga,xv,CO=te(()=>{vO();AJ="2025-06-18",TFr=[AJ,"2025-03-26","2024-11-05","2024-10-07"],lke="2.0",IFr=se.union([se.string(),se.number().int()]),DFr=se.string(),u0o=se.object({progressToken:se.optional(IFr)}).passthrough(),wv=se.object({_meta:se.optional(u0o)}).passthrough(),L3=se.object({method:se.string(),params:se.optional(wv)}),bhe=se.object({_meta:se.optional(se.object({}).passthrough())}).passthrough(),Xx=se.object({method:se.string(),params:se.optional(bhe)}),Tv=se.object({_meta:se.optional(se.object({}).passthrough())}).passthrough(),uke=se.union([se.string(),se.number().int()]),RFr=se.object({jsonrpc:se.literal(lke),id:uke}).merge(L3).strict(),dke=t=>RFr.safeParse(t).success,NFr=se.object({jsonrpc:se.literal(lke)}).merge(Xx).strict(),OFr=t=>NFr.safeParse(t).success,kFr=se.object({jsonrpc:se.literal(lke),id:uke,result:Tv}).strict(),Che=t=>kFr.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(Sv||(Sv={}));BFr=se.object({jsonrpc:se.literal(lke),id:uke,error:se.object({code:se.number().int(),message:se.string(),data:se.optional(se.unknown())})}).strict(),PFr=t=>BFr.safeParse(t).success,bO=se.union([RFr,NFr,kFr,BFr]),VU=Tv.strict(),fke=Xx.extend({method:se.literal("notifications/cancelled"),params:bhe.extend({requestId:uke,reason:se.string().optional()})}),d0o=se.object({src:se.string(),mimeType:se.optional(se.string()),sizes:se.optional(se.array(se.string()))}).passthrough(),She=se.object({icons:se.array(d0o).optional()}).passthrough(),xhe=se.object({name:se.string(),title:se.optional(se.string())}).passthrough(),MFr=xhe.extend({version:se.string(),websiteUrl:se.optional(se.string())}).merge(She),f0o=se.object({experimental:se.optional(se.object({}).passthrough()),sampling:se.optional(se.object({}).passthrough()),elicitation:se.optional(se.object({}).passthrough()),roots:se.optional(se.object({listChanged:se.optional(se.boolean())}).passthrough())}).passthrough(),p0o=L3.extend({method:se.literal("initialize"),params:wv.extend({protocolVersion:se.string(),capabilities:f0o,clientInfo:MFr})}),h0o=se.object({experimental:se.optional(se.object({}).passthrough()),logging:se.optional(se.object({}).passthrough()),completions:se.optional(se.object({}).passthrough()),prompts:se.optional(se.object({listChanged:se.optional(se.boolean())}).passthrough()),resources:se.optional(se.object({subscribe:se.optional(se.boolean()),listChanged:se.optional(se.boolean())}).passthrough()),tools:se.optional(se.object({listChanged:se.optional(se.boolean())}).passthrough())}).passthrough(),w6t=Tv.extend({protocolVersion:se.string(),capabilities:h0o,serverInfo:MFr,instructions:se.optional(se.string())}),FFr=Xx.extend({method:se.literal("notifications/initialized")}),LFr=t=>FFr.safeParse(t).success,pke=L3.extend({method:se.literal("ping")}),m0o=se.object({progress:se.number(),total:se.optional(se.number()),message:se.optional(se.string())}).passthrough(),hke=Xx.extend({method:se.literal("notifications/progress"),params:bhe.merge(m0o).extend({progressToken:IFr})}),mke=L3.extend({params:wv.extend({cursor:se.optional(DFr)}).optional()}),gke=Tv.extend({nextCursor:se.optional(DFr)}),UFr=se.object({uri:se.string(),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).passthrough(),QFr=UFr.extend({text:se.string()}),T6t=se.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),jFr=UFr.extend({blob:T6t}),GFr=xhe.extend({uri:se.string(),description:se.optional(se.string()),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).merge(She),g0o=xhe.extend({uriTemplate:se.string(),description:se.optional(se.string()),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).merge(She),A0o=mke.extend({method:se.literal("resources/list")}),I6t=gke.extend({resources:se.array(GFr)}),y0o=mke.extend({method:se.literal("resources/templates/list")}),D6t=gke.extend({resourceTemplates:se.array(g0o)}),_0o=L3.extend({method:se.literal("resources/read"),params:wv.extend({uri:se.string()})}),R6t=Tv.extend({contents:se.array(se.union([QFr,jFr]))}),E0o=Xx.extend({method:se.literal("notifications/resources/list_changed")}),v0o=L3.extend({method:se.literal("resources/subscribe"),params:wv.extend({uri:se.string()})}),b0o=L3.extend({method:se.literal("resources/unsubscribe"),params:wv.extend({uri:se.string()})}),C0o=Xx.extend({method:se.literal("notifications/resources/updated"),params:bhe.extend({uri:se.string()})}),S0o=se.object({name:se.string(),description:se.optional(se.string()),required:se.optional(se.boolean())}).passthrough(),x0o=xhe.extend({description:se.optional(se.string()),arguments:se.optional(se.array(S0o)),_meta:se.optional(se.object({}).passthrough())}).merge(She),w0o=mke.extend({method:se.literal("prompts/list")}),whe=gke.extend({prompts:se.array(x0o)}),T0o=L3.extend({method:se.literal("prompts/get"),params:wv.extend({name:se.string(),arguments:se.optional(se.record(se.string()))})}),N6t=se.object({type:se.literal("text"),text:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),O6t=se.object({type:se.literal("image"),data:T6t,mimeType:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),k6t=se.object({type:se.literal("audio"),data:T6t,mimeType:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),I0o=se.object({type:se.literal("resource"),resource:se.union([QFr,jFr]),_meta:se.optional(se.object({}).passthrough())}).passthrough(),D0o=GFr.extend({type:se.literal("resource_link")}),$Fr=se.union([N6t,O6t,k6t,D0o,I0o]),R0o=se.object({role:se.enum(["user","assistant"]),content:$Fr}).passthrough(),The=Tv.extend({description:se.optional(se.string()),messages:se.array(R0o)}),N0o=Xx.extend({method:se.literal("notifications/prompts/list_changed")}),O0o=se.object({title:se.optional(se.string()),readOnlyHint:se.optional(se.boolean()),destructiveHint:se.optional(se.boolean()),idempotentHint:se.optional(se.boolean()),openWorldHint:se.optional(se.boolean())}).passthrough(),k0o=xhe.extend({description:se.optional(se.string()),inputSchema:se.object({type:se.literal("object"),properties:se.optional(se.object({}).passthrough()),required:se.optional(se.array(se.string()))}).passthrough(),outputSchema:se.optional(se.object({type:se.literal("object"),properties:se.optional(se.object({}).passthrough()),required:se.optional(se.array(se.string()))}).passthrough()),annotations:se.optional(O0o),_meta:se.optional(se.object({}).passthrough())}).merge(She),B0o=mke.extend({method:se.literal("tools/list")}),B6t=gke.extend({tools:se.array(k0o)}),Ake=Tv.extend({content:se.array($Fr).default([]),structuredContent:se.object({}).passthrough().optional(),isError:se.optional(se.boolean())}),FGa=Ake.or(Tv.extend({toolResult:se.unknown()})),P0o=L3.extend({method:se.literal("tools/call"),params:wv.extend({name:se.string(),arguments:se.optional(se.record(se.unknown()))})}),M0o=Xx.extend({method:se.literal("notifications/tools/list_changed")}),qFr=se.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),F0o=L3.extend({method:se.literal("logging/setLevel"),params:wv.extend({level:qFr})}),L0o=Xx.extend({method:se.literal("notifications/message"),params:bhe.extend({level:qFr,logger:se.optional(se.string()),data:se.unknown()})}),U0o=se.object({name:se.string().optional()}).passthrough(),Q0o=se.object({hints:se.optional(se.array(U0o)),costPriority:se.optional(se.number().min(0).max(1)),speedPriority:se.optional(se.number().min(0).max(1)),intelligencePriority:se.optional(se.number().min(0).max(1))}).passthrough(),j0o=se.object({role:se.enum(["user","assistant"]),content:se.union([N6t,O6t,k6t])}).passthrough(),G0o=L3.extend({method:se.literal("sampling/createMessage"),params:wv.extend({messages:se.array(j0o),systemPrompt:se.optional(se.string()),includeContext:se.optional(se.enum(["none","thisServer","allServers"])),temperature:se.optional(se.number()),maxTokens:se.number().int(),stopSequences:se.optional(se.array(se.string())),metadata:se.optional(se.object({}).passthrough()),modelPreferences:se.optional(Q0o)})}),$0o=Tv.extend({model:se.string(),stopReason:se.optional(se.enum(["endTurn","stopSequence","maxTokens"]).or(se.string())),role:se.enum(["user","assistant"]),content:se.discriminatedUnion("type",[N6t,O6t,k6t])}),q0o=se.object({type:se.literal("boolean"),title:se.optional(se.string()),description:se.optional(se.string()),default:se.optional(se.boolean())}).passthrough(),H0o=se.object({type:se.literal("string"),title:se.optional(se.string()),description:se.optional(se.string()),minLength:se.optional(se.number()),maxLength:se.optional(se.number()),format:se.optional(se.enum(["email","uri","date","date-time"]))}).passthrough(),V0o=se.object({type:se.enum(["number","integer"]),title:se.optional(se.string()),description:se.optional(se.string()),minimum:se.optional(se.number()),maximum:se.optional(se.number())}).passthrough(),W0o=se.object({type:se.literal("string"),title:se.optional(se.string()),description:se.optional(se.string()),enum:se.array(se.string()),enumNames:se.optional(se.array(se.string()))}).passthrough(),z0o=se.union([q0o,H0o,V0o,W0o]),Y0o=L3.extend({method:se.literal("elicitation/create"),params:wv.extend({message:se.string(),requestedSchema:se.object({type:se.literal("object"),properties:se.record(se.string(),z0o),required:se.optional(se.array(se.string()))}).passthrough()})}),K0o=Tv.extend({action:se.enum(["accept","decline","cancel"]),content:se.optional(se.record(se.string(),se.unknown()))}),X0o=se.object({type:se.literal("ref/resource"),uri:se.string()}).passthrough(),J0o=se.object({type:se.literal("ref/prompt"),name:se.string()}).passthrough(),Z0o=L3.extend({method:se.literal("completion/complete"),params:wv.extend({ref:se.union([J0o,X0o]),argument:se.object({name:se.string(),value:se.string()}).passthrough(),context:se.optional(se.object({arguments:se.optional(se.record(se.string(),se.string()))}))})}),P6t=Tv.extend({completion:se.object({values:se.array(se.string()).max(100),total:se.optional(se.number().int()),hasMore:se.optional(se.boolean())}).passthrough()}),eAo=se.object({uri:se.string().startsWith("file://"),name:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).passthrough(),yke=L3.extend({method:se.literal("roots/list")}),tAo=Tv.extend({roots:se.array(eAo)}),rAo=Xx.extend({method:se.literal("notifications/roots/list_changed")}),LGa=se.union([pke,p0o,Z0o,F0o,T0o,w0o,A0o,y0o,_0o,v0o,b0o,P0o,B0o]),UGa=se.union([fke,hke,FFr,rAo]),QGa=se.union([VU,$0o,K0o,tAo]),jGa=se.union([pke,G0o,Y0o,yke]),GGa=se.union([fke,hke,L0o,C0o,E0o,M0o,N0o]),$Ga=se.union([VU,w6t,P6t,The,whe,I6t,D6t,R6t,Ake,B6t]),xv=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}}});function HFr(t,e){return Object.entries(e).reduce((r,[n,o])=>(o&&typeof o=="object"?r[n]=r[n]?{...r[n],...o}:o:r[n]=o,r),{...t})}var nAo,_ke,VFr=te(()=>{CO();nAo=6e4,_ke=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(fke,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(hke,r=>{this._onprogress(r)}),this.setRequestHandler(pke,r=>({}))}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new xv(Sv.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,o;this._transport=e;let s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};let a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=u=>{a?.(u),this._onerror(u)};let c=(o=this._transport)===null||o===void 0?void 0:o.onmessage;this._transport.onmessage=(u,d)=>{c?.(u,d),Che(u)||PFr(u)?this._onresponse(u):dke(u)?this._onrequest(u,d):OFr(u)?this._onnotification(u):this._onerror(new Error(`Unknown message type: ${JSON.stringify(u)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new xv(Sv.ConnectionClosed,"Connection closed");for(let o of r.values())o(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){var n,o;let s=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,a=this._transport;if(s===void 0){a?.send({jsonrpc:"2.0",id:e.id,error:{code:Sv.MethodNotFound,message:"Method not found"}}).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let c=new AbortController;this._requestHandlerAbortControllers.set(e.id,c);let u={signal:c.signal,sessionId:a?.sessionId,_meta:(o=e.params)===null||o===void 0?void 0:o._meta,sendNotification:d=>this.notification(d,{relatedRequestId:e.id}),sendRequest:(d,f,p)=>this.request(d,f,{...p,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>s(e,u)).then(d=>{if(!c.signal.aborted)return a?.send({result:d,jsonrpc:"2.0",id:e.id})},d=>{var f;if(!c.signal.aborted)return a?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:Sv.InternalError,message:(f=d.message)!==null&&f!==void 0?f:"Internal error"}})}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),c=this._timeoutInfo.get(o);if(c&&a&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(u){a(u);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Che(e))n(e);else{let o=new xv(e.error.code,e.error.message,e.error.data);n(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}=n??{};return new Promise((c,u)=>{var d,f,p,h,m,g;if(!this._transport){u(new Error("Not connected"));return}((d=this._options)===null||d===void 0?void 0:d.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=n?.signal)===null||f===void 0||f.throwIfAborted();let A=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:A};n?.onprogress&&(this._progressHandlers.set(A,n.onprogress),y.params={...e.params,_meta:{...((p=e.params)===null||p===void 0?void 0:p._meta)||{},progressToken:A}});let E=S=>{var w;this._responseHandlers.delete(A),this._progressHandlers.delete(A),this._cleanupTimeout(A),(w=this._transport)===null||w===void 0||w.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:A,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`))),u(S)};this._responseHandlers.set(A,S=>{var w;if(!(!((w=n?.signal)===null||w===void 0)&&w.aborted)){if(S instanceof Error)return u(S);try{let R=r.parse(S.result);c(R)}catch(R){u(R)}}}),(h=n?.signal)===null||h===void 0||h.addEventListener("abort",()=>{var S;E((S=n?.signal)===null||S===void 0?void 0:S.reason)});let v=(m=n?.timeout)!==null&&m!==void 0?m:nAo,b=()=>E(new xv(Sv.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(A,v,n?.maxTotalTimeout,b,(g=n?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(S=>{this._cleanupTimeout(A),u(S)})})}async notification(e,r){var n,o;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((o=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&o!==void 0?o:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var u;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let d={...e,jsonrpc:"2.0"};(u=this._transport)===null||u===void 0||u.send(d,r).catch(f=>this._onerror(f))});return}let c={...e,jsonrpc:"2.0"};await this._transport.send(c,r)}setRequestHandler(e,r){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>Promise.resolve(r(e.parse(o),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(r(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}});var Rhe=T(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.regexpCode=Va.getEsmExportName=Va.getProperty=Va.safeStringify=Va.stringify=Va.strConcat=Va.addCodeArg=Va.str=Va._=Va.nil=Va._Code=Va.Name=Va.IDENTIFIER=Va._CodeOrName=void 0;var Ihe=class{};Va._CodeOrName=Ihe;Va.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var WU=class extends Ihe{constructor(e){if(super(),!Va.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Va.Name=WU;var Iv=class extends Ihe{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof WU&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Va._Code=Iv;Va.nil=new Iv("");function WFr(t,...e){let r=[t[0]],n=0;for(;n<e.length;)F6t(r,e[n]),r.push(t[++n]);return new Iv(r)}Va._=WFr;var M6t=new Iv("+");function zFr(t,...e){let r=[Dhe(t[0])],n=0;for(;n<e.length;)r.push(M6t),F6t(r,e[n]),r.push(M6t,Dhe(t[++n]));return iAo(r),new Iv(r)}Va.str=zFr;function F6t(t,e){e instanceof Iv?t.push(...e._items):e instanceof WU?t.push(e):t.push(aAo(e))}Va.addCodeArg=F6t;function iAo(t){let e=1;for(;e<t.length-1;){if(t[e]===M6t){let r=oAo(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function oAo(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof WU||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof WU))return`"${t}${e.slice(1)}`}function sAo(t,e){return e.emptyStr()?t:t.emptyStr()?e:zFr`${t}${e}`}Va.strConcat=sAo;function aAo(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Dhe(Array.isArray(t)?t.join(","):t)}function cAo(t){return new Iv(Dhe(t))}Va.stringify=cAo;function Dhe(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Va.safeStringify=Dhe;function lAo(t){return typeof t=="string"&&Va.IDENTIFIER.test(t)?new Iv(`.${t}`):WFr`[${t}]`}Va.getProperty=lAo;function uAo(t){if(typeof t=="string"&&Va.IDENTIFIER.test(t))return new Iv(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Va.getEsmExportName=uAo;function dAo(t){return new Iv(t.toString())}Va.regexpCode=dAo});var Q6t=T(Q3=>{"use strict";Object.defineProperty(Q3,"__esModule",{value:!0});Q3.ValueScope=Q3.ValueScopeName=Q3.Scope=Q3.varKinds=Q3.UsedValueState=void 0;var U3=Rhe(),L6t=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Eke;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Eke||(Q3.UsedValueState=Eke={}));Q3.varKinds={const:new U3.Name("const"),let:new U3.Name("let"),var:new U3.Name("var")};var vke=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof U3.Name?e:this.name(e)}name(e){return new U3.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Q3.Scope=vke;var bke=class extends U3.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,U3._)`.${new U3.Name(r)}[${n}]`}};Q3.ValueScopeName=bke;var fAo=(0,U3._)`\n`,U6t=class extends vke{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fAo:U3.nil}}get(){return this._scope}name(e){return new bke(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,a=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[s];if(c){let f=c.get(a);if(f)return f}else c=this._values[s]=new Map;c.set(a,o);let u=this._scope[s]||(this._scope[s]=[]),d=u.length;return u[d]=r.ref,o.setValue(r,{property:s,itemIndex:d}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,U3._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=U3.nil;for(let a in e){let c=e[a];if(!c)continue;let u=n[a]=n[a]||new Map;c.forEach(d=>{if(u.has(d))return;u.set(d,Eke.Started);let f=r(d);if(f){let p=this.opts.es5?Q3.varKinds.var:Q3.varKinds.const;s=(0,U3._)`${s}${p} ${d} = ${f};${this.opts._n}`}else if(f=o?.(d))s=(0,U3._)`${s}${f}${this.opts._n}`;else throw new L6t(d);u.set(d,Eke.Completed)})}return s}};Q3.ValueScope=U6t});var Is=T(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.or=Gs.and=Gs.not=Gs.CodeGen=Gs.operators=Gs.varKinds=Gs.ValueScopeName=Gs.ValueScope=Gs.Scope=Gs.Name=Gs.regexpCode=Gs.stringify=Gs.getProperty=Gs.nil=Gs.strConcat=Gs.str=Gs._=void 0;var ba=Rhe(),DC=Q6t(),SO=Rhe();Object.defineProperty(Gs,"_",{enumerable:!0,get:function(){return SO._}});Object.defineProperty(Gs,"str",{enumerable:!0,get:function(){return SO.str}});Object.defineProperty(Gs,"strConcat",{enumerable:!0,get:function(){return SO.strConcat}});Object.defineProperty(Gs,"nil",{enumerable:!0,get:function(){return SO.nil}});Object.defineProperty(Gs,"getProperty",{enumerable:!0,get:function(){return SO.getProperty}});Object.defineProperty(Gs,"stringify",{enumerable:!0,get:function(){return SO.stringify}});Object.defineProperty(Gs,"regexpCode",{enumerable:!0,get:function(){return SO.regexpCode}});Object.defineProperty(Gs,"Name",{enumerable:!0,get:function(){return SO.Name}});var wke=Q6t();Object.defineProperty(Gs,"Scope",{enumerable:!0,get:function(){return wke.Scope}});Object.defineProperty(Gs,"ValueScope",{enumerable:!0,get:function(){return wke.ValueScope}});Object.defineProperty(Gs,"ValueScopeName",{enumerable:!0,get:function(){return wke.ValueScopeName}});Object.defineProperty(Gs,"varKinds",{enumerable:!0,get:function(){return wke.varKinds}});Gs.operators={GT:new ba._Code(">"),GTE:new ba._Code(">="),LT:new ba._Code("<"),LTE:new ba._Code("<="),EQ:new ba._Code("==="),NEQ:new ba._Code("!=="),NOT:new ba._Code("!"),OR:new ba._Code("||"),AND:new ba._Code("&&"),ADD:new ba._Code("+")};var i7=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},j6t=class extends i7{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?DC.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=_J(this.rhs,e,r)),this}get names(){return this.rhs instanceof ba._CodeOrName?this.rhs.names:{}}},Cke=class extends i7{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ba.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=_J(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ba.Name?{}:{...this.lhs.names};return xke(e,this.rhs)}},G6t=class extends Cke{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},$6t=class extends i7{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},q6t=class extends i7{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},H6t=class extends i7{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},V6t=class extends i7{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=_J(this.code,e,r),this}get names(){return this.code instanceof ba._CodeOrName?this.code.names:{}}},Nhe=class extends i7{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(pAo(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>KU(e,r.names),{})}},o7=class extends Nhe{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},W6t=class extends Nhe{},yJ=class extends o7{};yJ.kind="else";var zU=class t extends o7{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new yJ(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(YFr(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=_J(this.condition,e,r),this}get names(){let e=super.names;return xke(e,this.condition),this.else&&KU(e,this.else.names),e}};zU.kind="if";var YU=class extends o7{};YU.kind="for";var z6t=class extends YU{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=_J(this.iteration,e,r),this}get names(){return KU(super.names,this.iteration.names)}},Y6t=class extends YU{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?DC.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=xke(super.names,this.from);return xke(e,this.to)}},Ske=class extends YU{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=_J(this.iterable,e,r),this}get names(){return KU(super.names,this.iterable.names)}},Ohe=class extends o7{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ohe.kind="func";var khe=class extends Nhe{render(e){return"return "+super.render(e)}};khe.kind="return";var K6t=class extends o7{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&KU(e,this.catch.names),this.finally&&KU(e,this.finally.names),e}},Bhe=class extends o7{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Bhe.kind="catch";var Phe=class extends o7{render(e){return"finally"+super.render(e)}};Phe.kind="finally";var X6t=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
949
|
+
`);try{(await fA(e)).on("error",s=>{throw new Error(`BROWSER_LAUNCH_FAILED: Failed to open browser automatically: ${s.message}. Please navigate to the URL manually.`)})}catch(o){throw new Error(`BROWSER_LAUNCH_FAILED: An unexpected error occurred while trying to open the browser: ${o}. Please navigate to the URL manually.`)}console.log("Waiting for authentication...");let n=0;for(;n<r.maxRetries;){await sFr(r.pollInterval);let o=await aFr(t,r);if(o.isSuccess()){let s=o.getPrivateToken();return await Z9.savePrivateToken(s),console.log("Aone authentication successful!"),!0}o.getError()&&console.log(`Waiting for authentication... (${n+1}/${r.maxRetries})`),n++}throw new Error("Authentication timeout. Please try again.")}async function XOe(t=new cJ){return await Z9.hasValidToken()?(console.log("Using cached Aone authentication."),!0):await cFr(t)}async function Vx(){return await Z9.loadPrivateToken()}async function JOe(){await Z9.clearPrivateToken(),console.log("Aone authentication cleared.")}async function Ymo(){return await Z9.hasValidToken()}async function Kmo(t=new cJ){return await JOe(),await XOe(t)}var ZOe=te(()=>{"use strict";p6t();f9();nFr();iFr();oFr();});async function h6t(t,e,r,n,o){if(e===Yt.LOGIN_WITH_IFLOW){await WF(e,r,o);let s=await Y4();if(!s)throw new Error("No API key found. Please re-authenticate.");let a=r.getContentGeneratorConfig();return new DU({model:r.getModel(),apiKey:s,baseUrl:a?.baseUrl||dhe,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen3-vl-plus",config:r})}if(e===Yt.LOGIN_WITH_AONE){if(!await XOe())throw new Error("Aone authentication failed. Please try again.");let a=await Vx();if(!a)throw new Error("No Aone private token found. Please re-authenticate.");let c=r.getContentGeneratorConfig(),u=Buffer.from(a,"utf8").toString("base64");return new DU({model:r.getModel(),apiKey:u,baseUrl:c?.baseUrl||"https://ducky.code.alibaba-inc.com/v1/openai",authType:e,debugMode:r.getDebugMode(),multimodalModelName:c?.multimodalModelName,config:r})}if(e===Yt.CLOUD_SHELL){let s=await WF(e,r),a=await I0r(s);return new A9(s,a.projectId,t,n,a.userTier)}throw new Error(`Unsupported authType: ${e}`)}var m6t=te(()=>{"use strict";A_();zR();D0r();gSe();s6t();TC();ZOe();});function Xmo(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function Wx(t){let e=Xmo(t),r=`IFLOW_${t}`;if(process.env[r])return process.env[r];let n=`IFLOW_${e}`;if(process.env[n])return process.env[n];let o=`iflow_${t}`;if(process.env[o])return process.env[o];let s=`iflow_${e}`;if(process.env[s])return process.env[s]}function mhe(){return Wx("apiKey")}function ghe(){return Wx("baseUrl")||Wx("url")}function Ahe(){return Wx("modelName")||Wx("model")}function lFr(t){let e=Wx(t);if(e===void 0)return;let r=e.toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}function uFr(t){let e=Wx(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function dFr(t){let e=Wx(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function eke(){return!!(mhe()||ghe()||Ahe())}function g6t(){let t={},e=["theme","selectedAuthType","sandbox","toolDiscoveryCommand","toolCallCommand","mcpServerCommand","contextFileName","preferredEditor","apiKey","baseUrl","modelName","searchApiKey","multimodalModelName","memoryImportFormat"],r=["useExternalAuth","showMemoryUsage","usageStatisticsEnabled","autoConfigureMaxOldSpaceSize","hideWindowTitle","hideTips","hideBanner","vimMode","ideModeFeature","ideMode","disableAutoUpdate","skipNextSpeakerCheck","useRipgrep","debugKeystrokeLogging","pasteFromClipboard"],n=["maxSessionTurns","memoryDiscoveryMaxDirs","tokensLimit","compressionTokenThreshold","shellTimeout","temperature","topP"],o=["coreTools","excludeTools","allowMCPServers","excludeMCPServers"];return e.forEach(s=>{let a=Wx(s);a!==void 0&&(t[s]=a)}),r.forEach(s=>{let a=lFr(s);a!==void 0&&(t[s]=a)}),n.forEach(s=>{let a=uFr(s);a!==void 0&&(t[s]=a)}),o.forEach(s=>{let a=dFr(s);a!==void 0&&(t[s]=a)}),t}function Jmo(){return{apiKey:mhe(),baseUrl:ghe(),model:Ahe()}}var A6t=te(()=>{"use strict";});async function y6t(t,e,r){if(await Jz())try{await fSe()||console.log("OAuth2 credentials cleared due to expiration. Please authenticate when prompted.")}catch(p){throw p instanceof Error&&p.message.includes("SERVER_OAUTH2_REQUIRED"),p}let o=mhe(),s=ghe(),a=Ahe(),c=r?.apiKey||o,u=r?.baseUrl||s||Zmo[e],d=r?.modelName||t.getModel()||a||N_,f={model:d,authType:e,proxy:t?.getProxy(),debugMode:t?.getDebugMode(),config:t};return e===Yt.CLOUD_SHELL?f:e===Yt.LOGIN_WITH_IFLOW?(f.baseUrl=u||dhe,f.multimodalModelName="qwen3-vl-plus",c&&(f.apiKey=c),f):([...O_,Yt.OPENAI_COMPATIBLE].includes(e)&&c&&(f.apiKey=c,f.baseUrl=u,f.model=d),f)}async function _6t(t,e,r,n){let s={headers:{"User-Agent":`iFlowCLI/0.4.3 (${process.platform}; ${process.arch})`}};if(t.authType&&[...O_,Yt.IDEA_LAB].includes(t.authType)||t.authType===Yt.OPENAI_COMPATIBLE)return new DU({...t,config:e});if(t.authType===Yt.LOGIN_WITH_IFLOW||t.authType===Yt.LOGIN_WITH_AONE||t.authType===Yt.CLOUD_SHELL)return h6t(s,t.authType,e,r,n);throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var Yt,O_,Zmo,A_=te(()=>{"use strict";m6t();TC();s6t();A6t();zR();(function(t){t.LOGIN_WITH_IFLOW="oauth-iflow",t.LOGIN_WITH_AONE="oauth-aone",t.CLOUD_SHELL="cloud-shell",t.IFLOW="iflow",t.AONE="aone",t.IDEA_LAB="idealab",t.OPENAI_COMPATIBLE="openai-compatible"})(Yt||(Yt={}));O_=[Yt.IFLOW,Yt.AONE],Zmo={[Yt.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[Yt.IFLOW]:dhe,[Yt.AONE]:FMr}});var tke,fFr=te(()=>{"use strict";tke=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let r=`${e.serverName}_${e.name}`;console.warn(`Prompt with name "${e.name}" is already registered. Renaming to "${r}".`),this.prompts.set(r,{...e,name:r})}else this.prompts.set(e.name,e)}getAllPrompts(){return Array.from(this.prompts.values()).sort((e,r)=>e.name.localeCompare(r.name))}getPrompt(e){return this.prompts.get(e)}getPromptsByServer(e){let r=[];for(let n of this.prompts.values())n.serverName===e&&r.push(n);return r.sort((n,o)=>n.name.localeCompare(o.name))}clear(){this.prompts.clear()}removePromptsByServer(e){for(let[r,n]of this.prompts.entries())n.serverName===e&&this.prompts.delete(r)}}});var wn,Ev=te(()=>{"use strict";(function(t){t.INVALID_TOOL_PARAMS="invalid_tool_params",t.UNKNOWN="unknown",t.UNHANDLED_EXCEPTION="unhandled_exception",t.TOOL_NOT_REGISTERED="tool_not_registered",t.EXECUTION_FAILED="execution_failed",t.FILE_NOT_FOUND="file_not_found",t.FILE_WRITE_FAILURE="file_write_failure",t.READ_CONTENT_FAILURE="read_content_failure",t.ATTEMPT_TO_CREATE_EXISTING_FILE="attempt_to_create_existing_file",t.FILE_TOO_LARGE="file_too_large",t.PERMISSION_DENIED="permission_denied",t.NO_SPACE_LEFT="no_space_left",t.TARGET_IS_DIRECTORY="target_is_directory",t.PATH_NOT_IN_WORKSPACE="path_not_in_workspace",t.SEARCH_PATH_NOT_FOUND="search_path_not_found",t.SEARCH_PATH_NOT_A_DIRECTORY="search_path_not_a_directory",t.EDIT_PREPARATION_FAILURE="edit_preparation_failure",t.EDIT_NO_OCCURRENCE_FOUND="edit_no_occurrence_found",t.EDIT_EXPECTED_OCCURRENCE_MISMATCH="edit_expected_occurrence_mismatch",t.EDIT_NO_CHANGE="edit_no_change",t.GLOB_EXECUTION_ERROR="glob_execution_error",t.GREP_EXECUTION_ERROR="grep_execution_error",t.LS_EXECUTION_ERROR="ls_execution_error",t.PATH_IS_NOT_A_DIRECTORY="path_is_not_a_directory",t.MCP_TOOL_ERROR="mcp_tool_error",t.MEMORY_TOOL_EXECUTION_ERROR="memory_tool_execution_error",t.READ_MANY_FILES_SEARCH_ERROR="read_many_files_search_error",t.DISCOVERED_TOOL_EXECUTION_ERROR="discovered_tool_execution_error",t.WEB_FETCH_NO_URL_IN_PROMPT="web_fetch_no_url_in_prompt",t.WEB_FETCH_FALLBACK_FAILED="web_fetch_fallback_failed",t.WEB_FETCH_PROCESSING_ERROR="web_fetch_processing_error",t.WEB_SEARCH_FAILED="web_search_failed",t.HOOK_BLOCKED="hook_blocked"})(wn||(wn={}))});var ra,E6t,Un,zx,yhe=te(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let a of o)s[a]=a;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of s)a[c]=o[c];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},t.find=(o,s)=>{for(let a of o)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ra||(ra={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(E6t||(E6t={}));Un=ra.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zx=t=>{switch(typeof t){case"undefined":return Un.undefined;case"string":return Un.string;case"number":return Number.isNaN(t)?Un.nan:Un.number;case"boolean":return Un.boolean;case"function":return Un.function;case"bigint":return Un.bigint;case"symbol":return Un.symbol;case"object":return Array.isArray(t)?Un.array:t===null?Un.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Un.promise:typeof Map<"u"&&t instanceof Map?Un.map:typeof Set<"u"&&t instanceof Set?Un.set:typeof Date<"u"&&t instanceof Date?Un.date:Un.object;default:return Un.unknown}}});var zr,ego,M3,rke=te(()=>{yhe();zr=ra.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"]),ego=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),M3=class t 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 r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let a of s.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(r(a));else{let c=n,u=0;for(;u<a.path.length;){let d=a.path[u];u===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(r(a))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ra.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};M3.create=t=>new M3(t)});var tgo,e7,v6t=te(()=>{rke();yhe();tgo=(t,e)=>{let r;switch(t.code){case zr.invalid_type:t.received===Un.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case zr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ra.jsonStringifyReplacer)}`;break;case zr.unrecognized_keys:r=`Unrecognized key(s) in object: ${ra.joinValues(t.keys,", ")}`;break;case zr.invalid_union:r="Invalid input";break;case zr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ra.joinValues(t.options)}`;break;case zr.invalid_enum_value:r=`Invalid enum value. Expected ${ra.joinValues(t.options)}, received '${t.received}'`;break;case zr.invalid_arguments:r="Invalid function arguments";break;case zr.invalid_return_type:r="Invalid function return type";break;case zr.invalid_date:r="Invalid date";break;case zr.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ra.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case zr.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case zr.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case zr.custom:r="Invalid input";break;case zr.invalid_intersection_types:r="Intersection results could not be merged";break;case zr.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case zr.not_finite:r="Number must be finite";break;default:r=e.defaultError,ra.assertNever(t)}return{message:r}},e7=tgo});function rgo(t){pFr=t}function lJ(){return pFr}var pFr,nke=te(()=>{v6t();pFr=e7});function En(t,e){let r=lJ(),n=_he({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===e7?void 0:e7].filter(o=>!!o)});t.common.issues.push(n)}var _he,ngo,l0,Xi,RU,OA,ike,oke,AO,uJ,b6t=te(()=>{nke();v6t();_he=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="",u=n.filter(d=>!!d).slice().reverse();for(let d of u)c=d(a,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},ngo=[];l0=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return Xi;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,a=await o.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return Xi;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},Xi=Object.freeze({status:"aborted"}),RU=t=>({status:"dirty",value:t}),OA=t=>({status:"valid",value:t}),ike=t=>t.status==="aborted",oke=t=>t.status==="dirty",AO=t=>t.status==="valid",uJ=t=>typeof Promise<"u"&&t instanceof Promise});var hFr=te(()=>{});var Ei,mFr=te(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Ei||(Ei={}))});function ds(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,c)=>{let{message:u}=t;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:u??n??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:u??r??c.defaultError}},description:o}}function _Fr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Ego(t){return new RegExp(`^${_Fr(t)}$`)}function EFr(t){let e=`${yFr}T${_Fr(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vgo(t,e){return!!((e==="v4"||!e)&&pgo.test(t)||(e==="v6"||!e)&&mgo.test(t))}function bgo(t,e){if(!lgo.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Cgo(t,e){return!!((e==="v4"||!e)&&hgo.test(t)||(e==="v6"||!e)&&ggo.test(t))}function Sgo(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}function dJ(t){if(t instanceof F3){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=vv.create(dJ(n))}return new F3({...t._def,shape:()=>e})}else return t instanceof n7?new n7({...t._def,type:dJ(t.element)}):t instanceof vv?vv.create(dJ(t.unwrap())):t instanceof Kx?Kx.create(dJ(t.unwrap())):t instanceof Yx?Yx.create(t.items.map(e=>dJ(e))):t}function S6t(t,e){let r=zx(t),n=zx(e);if(t===e)return{valid:!0,data:t};if(r===Un.object&&n===Un.object){let o=ra.objectKeys(e),s=ra.objectKeys(t).filter(c=>o.indexOf(c)!==-1),a={...t,...e};for(let c of s){let u=S6t(t[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(r===Un.array&&n===Un.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let a=t[s],c=e[s],u=S6t(a,c);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return r===Un.date&&n===Un.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function vFr(t,e){return new jU({values:t,typeName:oo.ZodEnum,...ds(e)})}function AFr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function bFr(t,e={},r){return t?_O.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let c=AFr(e,n),u=c.fatal??r??!0;o.addIssue({code:"custom",...c,fatal:u})}});if(!s){let a=AFr(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}}):_O.create()}var bv,gFr,Ts,igo,ogo,sgo,ago,cgo,lgo,ugo,dgo,fgo,C6t,pgo,hgo,mgo,ggo,Ago,ygo,yFr,_go,yO,NU,OU,kU,BU,fJ,PU,MU,_O,r7,IC,pJ,n7,F3,FU,t7,ske,LU,Yx,ake,hJ,mJ,cke,UU,QU,jU,GU,EO,Cv,vv,Kx,$U,qU,gJ,xgo,Ehe,vhe,HU,wgo,oo,Tgo,CFr,SFr,Igo,Dgo,xFr,Rgo,Ngo,Ogo,kgo,Bgo,Pgo,Mgo,Fgo,Lgo,Ugo,Qgo,jgo,Ggo,$go,qgo,Hgo,Vgo,Wgo,zgo,Ygo,Kgo,Xgo,Jgo,Zgo,e0o,t0o,r0o,n0o,i0o,o0o,s0o,a0o,c0o,l0o,wFr=te(()=>{rke();nke();mFr();b6t();yhe();bv=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},gFr=(t,e)=>{if(AO(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new M3(t.common.issues);return this._error=r,this._error}}};Ts=class{get description(){return this._def.description}_getType(e){return zx(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:zx(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new l0,ctx:{common:e.parent.common,data:e.data,parsedType:zx(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(uJ(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zx(e)},o=this._parseSync({data:e,path:n.path,parent:n});return gFr(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zx(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return AO(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>AO(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zx(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(uJ(o)?o:Promise.resolve(o));return gFr(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let a=e(o),c=()=>s.addIssue({code:zr.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Cv({schema:this,typeName:oo.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:r=>this["~validate"](r)}}optional(){return vv.create(this,this._def)}nullable(){return Kx.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return n7.create(this)}promise(){return EO.create(this,this._def)}or(e){return FU.create([this,e],this._def)}and(e){return LU.create(this,e,this._def)}transform(e){return new Cv({...ds(this._def),schema:this,typeName:oo.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new $U({...ds(this._def),innerType:this,defaultValue:r,typeName:oo.ZodDefault})}brand(){return new Ehe({typeName:oo.ZodBranded,type:this,...ds(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new qU({...ds(this._def),innerType:this,catchValue:r,typeName:oo.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vhe.create(this,e)}readonly(){return HU.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},igo=/^c[^\s-]{8,}$/i,ogo=/^[0-9a-z]+$/,sgo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ago=/^[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,cgo=/^[a-z0-9_-]{21}$/i,lgo=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ugo=/^[-+]?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)?)??$/,dgo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fgo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pgo=/^(?:(?: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])$/,hgo=/^(?:(?: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])$/,mgo=/^(([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]))$/,ggo=/^(([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])$/,Ago=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ygo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yFr="((\\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])))",_go=new RegExp(`^${yFr}$`);yO=class t extends Ts{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Un.string){let s=this._getOrReturnCtx(e);return En(s,{code:zr.invalid_type,expected:Un.string,received:s.parsedType}),Xi}let n=new l0,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),En(o,{code:zr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),En(o,{code:zr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,c=e.data.length<s.value;(a||c)&&(o=this._getOrReturnCtx(e,o),a?En(o,{code:zr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&En(o,{code:zr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")dgo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"email",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")C6t||(C6t=new RegExp(fgo,"u")),C6t.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"emoji",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")ago.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"uuid",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")cgo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"nanoid",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")igo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"cuid",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")ogo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"cuid2",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")sgo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"ulid",code:zr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),En(o,{validation:"url",code:zr.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"regex",code:zr.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?EFr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?_go.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Ego(s).test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{code:zr.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ugo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"duration",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?vgo(e.data,s.version)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"ip",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?bgo(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"jwt",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Cgo(e.data,s.version)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"cidr",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Ago.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"base64",code:zr.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ygo.test(e.data)||(o=this._getOrReturnCtx(e,o),En(o,{validation:"base64url",code:zr.invalid_string,message:s.message}),n.dirty()):ra.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:zr.invalid_string,...Ei.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Ei.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ei.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ei.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ei.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ei.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ei.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ei.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ei.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ei.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ei.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ei.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ei.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ei.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Ei.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Ei.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Ei.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Ei.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...Ei.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Ei.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Ei.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Ei.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Ei.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Ei.errToObj(r)})}nonempty(e){return this.min(1,Ei.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};yO.create=t=>new yO({checks:[],typeName:oo.ZodString,coerce:t?.coerce??!1,...ds(t)});NU=class t extends Ts{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)),this._getType(e)!==Un.number){let s=this._getOrReturnCtx(e);return En(s,{code:zr.invalid_type,expected:Un.number,received:s.parsedType}),Xi}let n,o=new l0;for(let s of this._def.checks)s.kind==="int"?ra.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),En(n,{code:zr.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Sgo(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),En(n,{code:zr.not_finite,message:s.message}),o.dirty()):ra.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Ei.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Ei.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Ei.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Ei.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Ei.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Ei.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ei.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ei.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ei.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ei.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Ei.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Ei.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ei.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ei.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ra.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};NU.create=t=>new NU({checks:[],typeName:oo.ZodNumber,coerce:t?.coerce||!1,...ds(t)});OU=class t extends Ts{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)!==Un.bigint)return this._getInvalidInput(e);let n,o=new l0;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),En(n,{code:zr.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ra.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return En(r,{code:zr.invalid_type,expected:Un.bigint,received:r.parsedType}),Xi}gte(e,r){return this.setLimit("min",e,!0,Ei.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Ei.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Ei.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Ei.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Ei.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ei.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ei.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ei.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ei.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Ei.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};OU.create=t=>new OU({checks:[],typeName:oo.ZodBigInt,coerce:t?.coerce??!1,...ds(t)});kU=class extends Ts{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Un.boolean){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.boolean,received:n.parsedType}),Xi}return OA(e.data)}};kU.create=t=>new kU({typeName:oo.ZodBoolean,coerce:t?.coerce||!1,...ds(t)});BU=class t extends Ts{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Un.date){let s=this._getOrReturnCtx(e);return En(s,{code:zr.invalid_type,expected:Un.date,received:s.parsedType}),Xi}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return En(s,{code:zr.invalid_date}),Xi}let n=new l0,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),En(o,{code:zr.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),En(o,{code:zr.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ra.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Ei.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Ei.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};BU.create=t=>new BU({checks:[],coerce:t?.coerce||!1,typeName:oo.ZodDate,...ds(t)});fJ=class extends Ts{_parse(e){if(this._getType(e)!==Un.symbol){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.symbol,received:n.parsedType}),Xi}return OA(e.data)}};fJ.create=t=>new fJ({typeName:oo.ZodSymbol,...ds(t)});PU=class extends Ts{_parse(e){if(this._getType(e)!==Un.undefined){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.undefined,received:n.parsedType}),Xi}return OA(e.data)}};PU.create=t=>new PU({typeName:oo.ZodUndefined,...ds(t)});MU=class extends Ts{_parse(e){if(this._getType(e)!==Un.null){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.null,received:n.parsedType}),Xi}return OA(e.data)}};MU.create=t=>new MU({typeName:oo.ZodNull,...ds(t)});_O=class extends Ts{constructor(){super(...arguments),this._any=!0}_parse(e){return OA(e.data)}};_O.create=t=>new _O({typeName:oo.ZodAny,...ds(t)});r7=class extends Ts{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OA(e.data)}};r7.create=t=>new r7({typeName:oo.ZodUnknown,...ds(t)});IC=class extends Ts{_parse(e){let r=this._getOrReturnCtx(e);return En(r,{code:zr.invalid_type,expected:Un.never,received:r.parsedType}),Xi}};IC.create=t=>new IC({typeName:oo.ZodNever,...ds(t)});pJ=class extends Ts{_parse(e){if(this._getType(e)!==Un.undefined){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.void,received:n.parsedType}),Xi}return OA(e.data)}};pJ.create=t=>new pJ({typeName:oo.ZodVoid,...ds(t)});n7=class t extends Ts{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==Un.array)return En(r,{code:zr.invalid_type,expected:Un.array,received:r.parsedType}),Xi;if(o.exactLength!==null){let a=r.data.length>o.exactLength.value,c=r.data.length<o.exactLength.value;(a||c)&&(En(r,{code:a?zr.too_big:zr.too_small,minimum:c?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&&r.data.length<o.minLength.value&&(En(r,{code:zr.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(En(r,{code:zr.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,c)=>o.type._parseAsync(new bv(r,a,r.path,c)))).then(a=>l0.mergeArray(n,a));let s=[...r.data].map((a,c)=>o.type._parseSync(new bv(r,a,r.path,c)));return l0.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:Ei.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:Ei.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:Ei.toString(r)}})}nonempty(e){return this.min(1,e)}};n7.create=(t,e)=>new n7({type:t,minLength:null,maxLength:null,exactLength:null,typeName:oo.ZodArray,...ds(e)});F3=class t extends Ts{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(),r=ra.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==Un.object){let d=this._getOrReturnCtx(e);return En(d,{code:zr.invalid_type,expected:Un.object,received:d.parsedType}),Xi}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof IC&&this._def.unknownKeys==="strip"))for(let d in o.data)a.includes(d)||c.push(d);let u=[];for(let d of a){let f=s[d],p=o.data[d];u.push({key:{status:"valid",value:d},value:f._parse(new bv(o,p,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof IC){let d=this._def.unknownKeys;if(d==="passthrough")for(let f of c)u.push({key:{status:"valid",value:f},value:{status:"valid",value:o.data[f]}});else if(d==="strict")c.length>0&&(En(o,{code:zr.unrecognized_keys,keys:c}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let f of c){let p=o.data[f];u.push({key:{status:"valid",value:f},value:d._parse(new bv(o,p,o.path,f)),alwaysSet:f in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let d=[];for(let f of u){let p=await f.key,h=await f.value;d.push({key:p,value:h,alwaysSet:f.alwaysSet})}return d}).then(d=>l0.mergeObjectSync(n,d)):l0.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return Ei.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Ei.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:oo.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ra.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ra.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return dJ(this)}partial(e){let r={};for(let n of ra.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ra.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof vv;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return vFr(ra.objectKeys(this.shape))}};F3.create=(t,e)=>new F3({shape:()=>t,unknownKeys:"strip",catchall:IC.create(),typeName:oo.ZodObject,...ds(e)});F3.strictCreate=(t,e)=>new F3({shape:()=>t,unknownKeys:"strict",catchall:IC.create(),typeName:oo.ZodObject,...ds(e)});F3.lazycreate=(t,e)=>new F3({shape:t,unknownKeys:"strip",catchall:IC.create(),typeName:oo.ZodObject,...ds(e)});FU=class extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;let a=s.map(c=>new M3(c.ctx.common.issues));return En(r,{code:zr.invalid_union,unionErrors:a}),Xi}if(r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s,a=[];for(let u of n){let d={...r,common:{...r.common,issues:[]},parent:null},f=u._parseSync({data:r.data,path:r.path,parent:d});if(f.status==="valid")return f;f.status==="dirty"&&!s&&(s={result:f,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let c=a.map(u=>new M3(u));return En(r,{code:zr.invalid_union,unionErrors:c}),Xi}}get options(){return this._def.options}};FU.create=(t,e)=>new FU({options:t,typeName:oo.ZodUnion,...ds(e)});t7=t=>t instanceof UU?t7(t.schema):t instanceof Cv?t7(t.innerType()):t instanceof QU?[t.value]:t instanceof jU?t.options:t instanceof GU?ra.objectValues(t.enum):t instanceof $U?t7(t._def.innerType):t instanceof PU?[void 0]:t instanceof MU?[null]:t instanceof vv?[void 0,...t7(t.unwrap())]:t instanceof Kx?[null,...t7(t.unwrap())]:t instanceof Ehe||t instanceof HU?t7(t.unwrap()):t instanceof qU?t7(t._def.innerType):[],ske=class t extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Un.object)return En(r,{code:zr.invalid_type,expected:Un.object,received:r.parsedType}),Xi;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(En(r,{code:zr.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Xi)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let a=t7(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,s)}}return new t({typeName:oo.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ds(n)})}};LU=class extends Ts{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,a)=>{if(ike(s)||ike(a))return Xi;let c=S6t(s.value,a.value);return c.valid?((oke(s)||oke(a))&&r.dirty(),{status:r.value,value:c.data}):(En(n,{code:zr.invalid_intersection_types}),Xi)};return n.common.async?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(([s,a])=>o(s,a)):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}))}};LU.create=(t,e,r)=>new LU({left:t,right:e,typeName:oo.ZodIntersection,...ds(r)});Yx=class t extends Ts{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Un.array)return En(n,{code:zr.invalid_type,expected:Un.array,received:n.parsedType}),Xi;if(n.data.length<this._def.items.length)return En(n,{code:zr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Xi;!this._def.rest&&n.data.length>this._def.items.length&&(En(n,{code:zr.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,c)=>{let u=this._def.items[c]||this._def.rest;return u?u._parse(new bv(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>l0.mergeArray(r,a)):l0.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Yx.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Yx({items:t,typeName:oo.ZodTuple,rest:null,...ds(e)})};ake=class t extends Ts{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Un.object)return En(n,{code:zr.invalid_type,expected:Un.object,received:n.parsedType}),Xi;let o=[],s=this._def.keyType,a=this._def.valueType;for(let c in n.data)o.push({key:s._parse(new bv(n,c,n.path,c)),value:a._parse(new bv(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?l0.mergeObjectAsync(r,o):l0.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ts?new t({keyType:e,valueType:r,typeName:oo.ZodRecord,...ds(n)}):new t({keyType:yO.create(),valueType:e,typeName:oo.ZodRecord,...ds(r)})}},hJ=class extends Ts{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Un.map)return En(n,{code:zr.invalid_type,expected:Un.map,received:n.parsedType}),Xi;let o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([c,u],d)=>({key:o._parse(new bv(n,c,n.path,[d,"key"])),value:s._parse(new bv(n,u,n.path,[d,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let u of a){let d=await u.key,f=await u.value;if(d.status==="aborted"||f.status==="aborted")return Xi;(d.status==="dirty"||f.status==="dirty")&&r.dirty(),c.set(d.value,f.value)}return{status:r.value,value:c}})}else{let c=new Map;for(let u of a){let d=u.key,f=u.value;if(d.status==="aborted"||f.status==="aborted")return Xi;(d.status==="dirty"||f.status==="dirty")&&r.dirty(),c.set(d.value,f.value)}return{status:r.value,value:c}}}};hJ.create=(t,e,r)=>new hJ({valueType:e,keyType:t,typeName:oo.ZodMap,...ds(r)});mJ=class t extends Ts{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Un.set)return En(n,{code:zr.invalid_type,expected:Un.set,received:n.parsedType}),Xi;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(En(n,{code:zr.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(En(n,{code:zr.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function a(u){let d=new Set;for(let f of u){if(f.status==="aborted")return Xi;f.status==="dirty"&&r.dirty(),d.add(f.value)}return{status:r.value,value:d}}let c=[...n.data.values()].map((u,d)=>s._parse(new bv(n,u,n.path,d)));return n.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,r){return new t({...this._def,minSize:{value:e,message:Ei.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:Ei.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};mJ.create=(t,e)=>new mJ({valueType:t,minSize:null,maxSize:null,typeName:oo.ZodSet,...ds(e)});cke=class t extends Ts{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Un.function)return En(r,{code:zr.invalid_type,expected:Un.function,received:r.parsedType}),Xi;function n(c,u){return _he({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lJ(),e7].filter(d=>!!d),issueData:{code:zr.invalid_arguments,argumentsError:u}})}function o(c,u){return _he({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lJ(),e7].filter(d=>!!d),issueData:{code:zr.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof EO){let c=this;return OA(async function(...u){let d=new M3([]),f=await c._def.args.parseAsync(u,s).catch(m=>{throw d.addIssue(n(u,m)),d}),p=await Reflect.apply(a,this,f);return await c._def.returns._def.type.parseAsync(p,s).catch(m=>{throw d.addIssue(o(p,m)),d})})}else{let c=this;return OA(function(...u){let d=c._def.args.safeParse(u,s);if(!d.success)throw new M3([n(u,d.error)]);let f=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(f,s);if(!p.success)throw new M3([o(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Yx.create(e).rest(r7.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Yx.create([]).rest(r7.create()),returns:r||r7.create(),typeName:oo.ZodFunction,...ds(n)})}},UU=class extends Ts{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};UU.create=(t,e)=>new UU({getter:t,typeName:oo.ZodLazy,...ds(e)});QU=class extends Ts{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return En(r,{received:r.data,code:zr.invalid_literal,expected:this._def.value}),Xi}return{status:"valid",value:e.data}}get value(){return this._def.value}};QU.create=(t,e)=>new QU({value:t,typeName:oo.ZodLiteral,...ds(e)});jU=class t extends Ts{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return En(r,{expected:ra.joinValues(n),received:r.parsedType,code:zr.invalid_type}),Xi}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return En(r,{received:r.data,code:zr.invalid_enum_value,options:n}),Xi}return OA(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};jU.create=vFr;GU=class extends Ts{_parse(e){let r=ra.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Un.string&&n.parsedType!==Un.number){let o=ra.objectValues(r);return En(n,{expected:ra.joinValues(o),received:n.parsedType,code:zr.invalid_type}),Xi}if(this._cache||(this._cache=new Set(ra.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ra.objectValues(r);return En(n,{received:n.data,code:zr.invalid_enum_value,options:o}),Xi}return OA(e.data)}get enum(){return this._def.values}};GU.create=(t,e)=>new GU({values:t,typeName:oo.ZodNativeEnum,...ds(e)});EO=class extends Ts{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Un.promise&&r.common.async===!1)return En(r,{code:zr.invalid_type,expected:Un.promise,received:r.parsedType}),Xi;let n=r.parsedType===Un.promise?r.data:Promise.resolve(r.data);return OA(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};EO.create=(t,e)=>new EO({type:t,typeName:oo.ZodPromise,...ds(e)});Cv=class extends Ts{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oo.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:a=>{En(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async c=>{if(r.value==="aborted")return Xi;let u=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return u.status==="aborted"?Xi:u.status==="dirty"?RU(u.value):r.value==="dirty"?RU(u.value):u});{if(r.value==="aborted")return Xi;let c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?Xi:c.status==="dirty"?RU(c.value):r.value==="dirty"?RU(c.value):c}}if(o.type==="refinement"){let a=c=>{let u=o.refinement(c,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?Xi:(c.status==="dirty"&&r.dirty(),a(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?Xi:(c.status==="dirty"&&r.dirty(),a(c.value).then(()=>({status:r.value,value:c.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(!AO(a))return Xi;let c=o.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>AO(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:r.value,value:c})):Xi);ra.assertNever(o)}};Cv.create=(t,e,r)=>new Cv({schema:t,typeName:oo.ZodEffects,effect:e,...ds(r)});Cv.createWithPreprocess=(t,e,r)=>new Cv({schema:e,effect:{type:"preprocess",transform:t},typeName:oo.ZodEffects,...ds(r)});vv=class extends Ts{_parse(e){return this._getType(e)===Un.undefined?OA(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vv.create=(t,e)=>new vv({innerType:t,typeName:oo.ZodOptional,...ds(e)});Kx=class extends Ts{_parse(e){return this._getType(e)===Un.null?OA(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Kx.create=(t,e)=>new Kx({innerType:t,typeName:oo.ZodNullable,...ds(e)});$U=class extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===Un.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};$U.create=(t,e)=>new $U({innerType:t,typeName:oo.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ds(e)});qU=class extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return uJ(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new M3(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new M3(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};qU.create=(t,e)=>new qU({innerType:t,typeName:oo.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ds(e)});gJ=class extends Ts{_parse(e){if(this._getType(e)!==Un.nan){let n=this._getOrReturnCtx(e);return En(n,{code:zr.invalid_type,expected:Un.nan,received:n.parsedType}),Xi}return{status:"valid",value:e.data}}};gJ.create=t=>new gJ({typeName:oo.ZodNaN,...ds(t)});xgo=Symbol("zod_brand"),Ehe=class extends Ts{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vhe=class t extends Ts{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Xi:s.status==="dirty"?(r.dirty(),RU(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Xi:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:oo.ZodPipeline})}},HU=class extends Ts{_parse(e){let r=this._def.innerType._parse(e),n=o=>(AO(o)&&(o.value=Object.freeze(o.value)),o);return uJ(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};HU.create=(t,e)=>new HU({innerType:t,typeName:oo.ZodReadonly,...ds(e)});wgo={object:F3.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(oo||(oo={}));Tgo=(t,e={message:`Input not instance of ${t.name}`})=>bFr(r=>r instanceof t,e),CFr=yO.create,SFr=NU.create,Igo=gJ.create,Dgo=OU.create,xFr=kU.create,Rgo=BU.create,Ngo=fJ.create,Ogo=PU.create,kgo=MU.create,Bgo=_O.create,Pgo=r7.create,Mgo=IC.create,Fgo=pJ.create,Lgo=n7.create,Ugo=F3.create,Qgo=F3.strictCreate,jgo=FU.create,Ggo=ske.create,$go=LU.create,qgo=Yx.create,Hgo=ake.create,Vgo=hJ.create,Wgo=mJ.create,zgo=cke.create,Ygo=UU.create,Kgo=QU.create,Xgo=jU.create,Jgo=GU.create,Zgo=EO.create,e0o=Cv.create,t0o=vv.create,r0o=Kx.create,n0o=Cv.createWithPreprocess,i0o=vhe.create,o0o=()=>CFr().optional(),s0o=()=>SFr().optional(),a0o=()=>xFr().optional(),c0o={string:(t=>yO.create({...t,coerce:!0})),number:(t=>NU.create({...t,coerce:!0})),boolean:(t=>kU.create({...t,coerce:!0})),bigint:(t=>OU.create({...t,coerce:!0})),date:(t=>BU.create({...t,coerce:!0}))},l0o=Xi});var se={};Ws(se,{BRAND:()=>xgo,DIRTY:()=>RU,EMPTY_PATH:()=>ngo,INVALID:()=>Xi,NEVER:()=>l0o,OK:()=>OA,ParseStatus:()=>l0,Schema:()=>Ts,ZodAny:()=>_O,ZodArray:()=>n7,ZodBigInt:()=>OU,ZodBoolean:()=>kU,ZodBranded:()=>Ehe,ZodCatch:()=>qU,ZodDate:()=>BU,ZodDefault:()=>$U,ZodDiscriminatedUnion:()=>ske,ZodEffects:()=>Cv,ZodEnum:()=>jU,ZodError:()=>M3,ZodFirstPartyTypeKind:()=>oo,ZodFunction:()=>cke,ZodIntersection:()=>LU,ZodIssueCode:()=>zr,ZodLazy:()=>UU,ZodLiteral:()=>QU,ZodMap:()=>hJ,ZodNaN:()=>gJ,ZodNativeEnum:()=>GU,ZodNever:()=>IC,ZodNull:()=>MU,ZodNullable:()=>Kx,ZodNumber:()=>NU,ZodObject:()=>F3,ZodOptional:()=>vv,ZodParsedType:()=>Un,ZodPipeline:()=>vhe,ZodPromise:()=>EO,ZodReadonly:()=>HU,ZodRecord:()=>ake,ZodSchema:()=>Ts,ZodSet:()=>mJ,ZodString:()=>yO,ZodSymbol:()=>fJ,ZodTransformer:()=>Cv,ZodTuple:()=>Yx,ZodType:()=>Ts,ZodUndefined:()=>PU,ZodUnion:()=>FU,ZodUnknown:()=>r7,ZodVoid:()=>pJ,addIssueToContext:()=>En,any:()=>Bgo,array:()=>Lgo,bigint:()=>Dgo,boolean:()=>xFr,coerce:()=>c0o,custom:()=>bFr,date:()=>Rgo,datetimeRegex:()=>EFr,defaultErrorMap:()=>e7,discriminatedUnion:()=>Ggo,effect:()=>e0o,enum:()=>Xgo,function:()=>zgo,getErrorMap:()=>lJ,getParsedType:()=>zx,instanceof:()=>Tgo,intersection:()=>$go,isAborted:()=>ike,isAsync:()=>uJ,isDirty:()=>oke,isValid:()=>AO,late:()=>wgo,lazy:()=>Ygo,literal:()=>Kgo,makeIssue:()=>_he,map:()=>Vgo,nan:()=>Igo,nativeEnum:()=>Jgo,never:()=>Mgo,null:()=>kgo,nullable:()=>r0o,number:()=>SFr,object:()=>Ugo,objectUtil:()=>E6t,oboolean:()=>a0o,onumber:()=>s0o,optional:()=>t0o,ostring:()=>o0o,pipeline:()=>i0o,preprocess:()=>n0o,promise:()=>Zgo,quotelessJson:()=>ego,record:()=>Hgo,set:()=>Wgo,setErrorMap:()=>rgo,strictObject:()=>Qgo,string:()=>CFr,symbol:()=>Ngo,transformer:()=>e0o,tuple:()=>qgo,undefined:()=>Ogo,union:()=>jgo,unknown:()=>Pgo,util:()=>ra,void:()=>Fgo});var x6t=te(()=>{nke();b6t();hFr();yhe();wFr();rke()});var vO=te(()=>{x6t();x6t()});var AJ,TFr,lke,IFr,DFr,u0o,wv,L3,bhe,Xx,Tv,uke,RFr,dke,NFr,OFr,kFr,Che,Sv,BFr,PFr,bO,VU,fke,d0o,She,xhe,MFr,f0o,p0o,h0o,w6t,FFr,LFr,pke,m0o,hke,mke,gke,UFr,QFr,T6t,jFr,GFr,g0o,A0o,I6t,y0o,D6t,_0o,R6t,E0o,v0o,b0o,C0o,S0o,x0o,w0o,whe,T0o,N6t,O6t,k6t,I0o,D0o,$Fr,R0o,The,N0o,O0o,k0o,B0o,B6t,Ake,FGa,P0o,M0o,qFr,F0o,L0o,U0o,Q0o,j0o,G0o,$0o,q0o,H0o,V0o,W0o,z0o,Y0o,K0o,X0o,J0o,Z0o,P6t,eAo,yke,tAo,rAo,LGa,UGa,QGa,jGa,GGa,$Ga,xv,CO=te(()=>{vO();AJ="2025-06-18",TFr=[AJ,"2025-03-26","2024-11-05","2024-10-07"],lke="2.0",IFr=se.union([se.string(),se.number().int()]),DFr=se.string(),u0o=se.object({progressToken:se.optional(IFr)}).passthrough(),wv=se.object({_meta:se.optional(u0o)}).passthrough(),L3=se.object({method:se.string(),params:se.optional(wv)}),bhe=se.object({_meta:se.optional(se.object({}).passthrough())}).passthrough(),Xx=se.object({method:se.string(),params:se.optional(bhe)}),Tv=se.object({_meta:se.optional(se.object({}).passthrough())}).passthrough(),uke=se.union([se.string(),se.number().int()]),RFr=se.object({jsonrpc:se.literal(lke),id:uke}).merge(L3).strict(),dke=t=>RFr.safeParse(t).success,NFr=se.object({jsonrpc:se.literal(lke)}).merge(Xx).strict(),OFr=t=>NFr.safeParse(t).success,kFr=se.object({jsonrpc:se.literal(lke),id:uke,result:Tv}).strict(),Che=t=>kFr.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(Sv||(Sv={}));BFr=se.object({jsonrpc:se.literal(lke),id:uke,error:se.object({code:se.number().int(),message:se.string(),data:se.optional(se.unknown())})}).strict(),PFr=t=>BFr.safeParse(t).success,bO=se.union([RFr,NFr,kFr,BFr]),VU=Tv.strict(),fke=Xx.extend({method:se.literal("notifications/cancelled"),params:bhe.extend({requestId:uke,reason:se.string().optional()})}),d0o=se.object({src:se.string(),mimeType:se.optional(se.string()),sizes:se.optional(se.array(se.string()))}).passthrough(),She=se.object({icons:se.array(d0o).optional()}).passthrough(),xhe=se.object({name:se.string(),title:se.optional(se.string())}).passthrough(),MFr=xhe.extend({version:se.string(),websiteUrl:se.optional(se.string())}).merge(She),f0o=se.object({experimental:se.optional(se.object({}).passthrough()),sampling:se.optional(se.object({}).passthrough()),elicitation:se.optional(se.object({}).passthrough()),roots:se.optional(se.object({listChanged:se.optional(se.boolean())}).passthrough())}).passthrough(),p0o=L3.extend({method:se.literal("initialize"),params:wv.extend({protocolVersion:se.string(),capabilities:f0o,clientInfo:MFr})}),h0o=se.object({experimental:se.optional(se.object({}).passthrough()),logging:se.optional(se.object({}).passthrough()),completions:se.optional(se.object({}).passthrough()),prompts:se.optional(se.object({listChanged:se.optional(se.boolean())}).passthrough()),resources:se.optional(se.object({subscribe:se.optional(se.boolean()),listChanged:se.optional(se.boolean())}).passthrough()),tools:se.optional(se.object({listChanged:se.optional(se.boolean())}).passthrough())}).passthrough(),w6t=Tv.extend({protocolVersion:se.string(),capabilities:h0o,serverInfo:MFr,instructions:se.optional(se.string())}),FFr=Xx.extend({method:se.literal("notifications/initialized")}),LFr=t=>FFr.safeParse(t).success,pke=L3.extend({method:se.literal("ping")}),m0o=se.object({progress:se.number(),total:se.optional(se.number()),message:se.optional(se.string())}).passthrough(),hke=Xx.extend({method:se.literal("notifications/progress"),params:bhe.merge(m0o).extend({progressToken:IFr})}),mke=L3.extend({params:wv.extend({cursor:se.optional(DFr)}).optional()}),gke=Tv.extend({nextCursor:se.optional(DFr)}),UFr=se.object({uri:se.string(),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).passthrough(),QFr=UFr.extend({text:se.string()}),T6t=se.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),jFr=UFr.extend({blob:T6t}),GFr=xhe.extend({uri:se.string(),description:se.optional(se.string()),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).merge(She),g0o=xhe.extend({uriTemplate:se.string(),description:se.optional(se.string()),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).merge(She),A0o=mke.extend({method:se.literal("resources/list")}),I6t=gke.extend({resources:se.array(GFr)}),y0o=mke.extend({method:se.literal("resources/templates/list")}),D6t=gke.extend({resourceTemplates:se.array(g0o)}),_0o=L3.extend({method:se.literal("resources/read"),params:wv.extend({uri:se.string()})}),R6t=Tv.extend({contents:se.array(se.union([QFr,jFr]))}),E0o=Xx.extend({method:se.literal("notifications/resources/list_changed")}),v0o=L3.extend({method:se.literal("resources/subscribe"),params:wv.extend({uri:se.string()})}),b0o=L3.extend({method:se.literal("resources/unsubscribe"),params:wv.extend({uri:se.string()})}),C0o=Xx.extend({method:se.literal("notifications/resources/updated"),params:bhe.extend({uri:se.string()})}),S0o=se.object({name:se.string(),description:se.optional(se.string()),required:se.optional(se.boolean())}).passthrough(),x0o=xhe.extend({description:se.optional(se.string()),arguments:se.optional(se.array(S0o)),_meta:se.optional(se.object({}).passthrough())}).merge(She),w0o=mke.extend({method:se.literal("prompts/list")}),whe=gke.extend({prompts:se.array(x0o)}),T0o=L3.extend({method:se.literal("prompts/get"),params:wv.extend({name:se.string(),arguments:se.optional(se.record(se.string()))})}),N6t=se.object({type:se.literal("text"),text:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),O6t=se.object({type:se.literal("image"),data:T6t,mimeType:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),k6t=se.object({type:se.literal("audio"),data:T6t,mimeType:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),I0o=se.object({type:se.literal("resource"),resource:se.union([QFr,jFr]),_meta:se.optional(se.object({}).passthrough())}).passthrough(),D0o=GFr.extend({type:se.literal("resource_link")}),$Fr=se.union([N6t,O6t,k6t,D0o,I0o]),R0o=se.object({role:se.enum(["user","assistant"]),content:$Fr}).passthrough(),The=Tv.extend({description:se.optional(se.string()),messages:se.array(R0o)}),N0o=Xx.extend({method:se.literal("notifications/prompts/list_changed")}),O0o=se.object({title:se.optional(se.string()),readOnlyHint:se.optional(se.boolean()),destructiveHint:se.optional(se.boolean()),idempotentHint:se.optional(se.boolean()),openWorldHint:se.optional(se.boolean())}).passthrough(),k0o=xhe.extend({description:se.optional(se.string()),inputSchema:se.object({type:se.literal("object"),properties:se.optional(se.object({}).passthrough()),required:se.optional(se.array(se.string()))}).passthrough(),outputSchema:se.optional(se.object({type:se.literal("object"),properties:se.optional(se.object({}).passthrough()),required:se.optional(se.array(se.string()))}).passthrough()),annotations:se.optional(O0o),_meta:se.optional(se.object({}).passthrough())}).merge(She),B0o=mke.extend({method:se.literal("tools/list")}),B6t=gke.extend({tools:se.array(k0o)}),Ake=Tv.extend({content:se.array($Fr).default([]),structuredContent:se.object({}).passthrough().optional(),isError:se.optional(se.boolean())}),FGa=Ake.or(Tv.extend({toolResult:se.unknown()})),P0o=L3.extend({method:se.literal("tools/call"),params:wv.extend({name:se.string(),arguments:se.optional(se.record(se.unknown()))})}),M0o=Xx.extend({method:se.literal("notifications/tools/list_changed")}),qFr=se.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),F0o=L3.extend({method:se.literal("logging/setLevel"),params:wv.extend({level:qFr})}),L0o=Xx.extend({method:se.literal("notifications/message"),params:bhe.extend({level:qFr,logger:se.optional(se.string()),data:se.unknown()})}),U0o=se.object({name:se.string().optional()}).passthrough(),Q0o=se.object({hints:se.optional(se.array(U0o)),costPriority:se.optional(se.number().min(0).max(1)),speedPriority:se.optional(se.number().min(0).max(1)),intelligencePriority:se.optional(se.number().min(0).max(1))}).passthrough(),j0o=se.object({role:se.enum(["user","assistant"]),content:se.union([N6t,O6t,k6t])}).passthrough(),G0o=L3.extend({method:se.literal("sampling/createMessage"),params:wv.extend({messages:se.array(j0o),systemPrompt:se.optional(se.string()),includeContext:se.optional(se.enum(["none","thisServer","allServers"])),temperature:se.optional(se.number()),maxTokens:se.number().int(),stopSequences:se.optional(se.array(se.string())),metadata:se.optional(se.object({}).passthrough()),modelPreferences:se.optional(Q0o)})}),$0o=Tv.extend({model:se.string(),stopReason:se.optional(se.enum(["endTurn","stopSequence","maxTokens"]).or(se.string())),role:se.enum(["user","assistant"]),content:se.discriminatedUnion("type",[N6t,O6t,k6t])}),q0o=se.object({type:se.literal("boolean"),title:se.optional(se.string()),description:se.optional(se.string()),default:se.optional(se.boolean())}).passthrough(),H0o=se.object({type:se.literal("string"),title:se.optional(se.string()),description:se.optional(se.string()),minLength:se.optional(se.number()),maxLength:se.optional(se.number()),format:se.optional(se.enum(["email","uri","date","date-time"]))}).passthrough(),V0o=se.object({type:se.enum(["number","integer"]),title:se.optional(se.string()),description:se.optional(se.string()),minimum:se.optional(se.number()),maximum:se.optional(se.number())}).passthrough(),W0o=se.object({type:se.literal("string"),title:se.optional(se.string()),description:se.optional(se.string()),enum:se.array(se.string()),enumNames:se.optional(se.array(se.string()))}).passthrough(),z0o=se.union([q0o,H0o,V0o,W0o]),Y0o=L3.extend({method:se.literal("elicitation/create"),params:wv.extend({message:se.string(),requestedSchema:se.object({type:se.literal("object"),properties:se.record(se.string(),z0o),required:se.optional(se.array(se.string()))}).passthrough()})}),K0o=Tv.extend({action:se.enum(["accept","decline","cancel"]),content:se.optional(se.record(se.string(),se.unknown()))}),X0o=se.object({type:se.literal("ref/resource"),uri:se.string()}).passthrough(),J0o=se.object({type:se.literal("ref/prompt"),name:se.string()}).passthrough(),Z0o=L3.extend({method:se.literal("completion/complete"),params:wv.extend({ref:se.union([J0o,X0o]),argument:se.object({name:se.string(),value:se.string()}).passthrough(),context:se.optional(se.object({arguments:se.optional(se.record(se.string(),se.string()))}))})}),P6t=Tv.extend({completion:se.object({values:se.array(se.string()).max(100),total:se.optional(se.number().int()),hasMore:se.optional(se.boolean())}).passthrough()}),eAo=se.object({uri:se.string().startsWith("file://"),name:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).passthrough(),yke=L3.extend({method:se.literal("roots/list")}),tAo=Tv.extend({roots:se.array(eAo)}),rAo=Xx.extend({method:se.literal("notifications/roots/list_changed")}),LGa=se.union([pke,p0o,Z0o,F0o,T0o,w0o,A0o,y0o,_0o,v0o,b0o,P0o,B0o]),UGa=se.union([fke,hke,FFr,rAo]),QGa=se.union([VU,$0o,K0o,tAo]),jGa=se.union([pke,G0o,Y0o,yke]),GGa=se.union([fke,hke,L0o,C0o,E0o,M0o,N0o]),$Ga=se.union([VU,w6t,P6t,The,whe,I6t,D6t,R6t,Ake,B6t]),xv=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}}});function HFr(t,e){return Object.entries(e).reduce((r,[n,o])=>(o&&typeof o=="object"?r[n]=r[n]?{...r[n],...o}:o:r[n]=o,r),{...t})}var nAo,_ke,VFr=te(()=>{CO();nAo=6e4,_ke=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(fke,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(hke,r=>{this._onprogress(r)}),this.setRequestHandler(pke,r=>({}))}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new xv(Sv.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,o;this._transport=e;let s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};let a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=u=>{a?.(u),this._onerror(u)};let c=(o=this._transport)===null||o===void 0?void 0:o.onmessage;this._transport.onmessage=(u,d)=>{c?.(u,d),Che(u)||PFr(u)?this._onresponse(u):dke(u)?this._onrequest(u,d):OFr(u)?this._onnotification(u):this._onerror(new Error(`Unknown message type: ${JSON.stringify(u)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new xv(Sv.ConnectionClosed,"Connection closed");for(let o of r.values())o(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){var n,o;let s=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,a=this._transport;if(s===void 0){a?.send({jsonrpc:"2.0",id:e.id,error:{code:Sv.MethodNotFound,message:"Method not found"}}).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let c=new AbortController;this._requestHandlerAbortControllers.set(e.id,c);let u={signal:c.signal,sessionId:a?.sessionId,_meta:(o=e.params)===null||o===void 0?void 0:o._meta,sendNotification:d=>this.notification(d,{relatedRequestId:e.id}),sendRequest:(d,f,p)=>this.request(d,f,{...p,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>s(e,u)).then(d=>{if(!c.signal.aborted)return a?.send({result:d,jsonrpc:"2.0",id:e.id})},d=>{var f;if(!c.signal.aborted)return a?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:Sv.InternalError,message:(f=d.message)!==null&&f!==void 0?f:"Internal error"}})}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),c=this._timeoutInfo.get(o);if(c&&a&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(u){a(u);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Che(e))n(e);else{let o=new xv(e.error.code,e.error.message,e.error.data);n(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}=n??{};return new Promise((c,u)=>{var d,f,p,h,m,g;if(!this._transport){u(new Error("Not connected"));return}((d=this._options)===null||d===void 0?void 0:d.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=n?.signal)===null||f===void 0||f.throwIfAborted();let A=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:A};n?.onprogress&&(this._progressHandlers.set(A,n.onprogress),y.params={...e.params,_meta:{...((p=e.params)===null||p===void 0?void 0:p._meta)||{},progressToken:A}});let E=S=>{var w;this._responseHandlers.delete(A),this._progressHandlers.delete(A),this._cleanupTimeout(A),(w=this._transport)===null||w===void 0||w.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:A,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`))),u(S)};this._responseHandlers.set(A,S=>{var w;if(!(!((w=n?.signal)===null||w===void 0)&&w.aborted)){if(S instanceof Error)return u(S);try{let R=r.parse(S.result);c(R)}catch(R){u(R)}}}),(h=n?.signal)===null||h===void 0||h.addEventListener("abort",()=>{var S;E((S=n?.signal)===null||S===void 0?void 0:S.reason)});let v=(m=n?.timeout)!==null&&m!==void 0?m:nAo,b=()=>E(new xv(Sv.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(A,v,n?.maxTotalTimeout,b,(g=n?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(S=>{this._cleanupTimeout(A),u(S)})})}async notification(e,r){var n,o;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((o=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&o!==void 0?o:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var u;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let d={...e,jsonrpc:"2.0"};(u=this._transport)===null||u===void 0||u.send(d,r).catch(f=>this._onerror(f))});return}let c={...e,jsonrpc:"2.0"};await this._transport.send(c,r)}setRequestHandler(e,r){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>Promise.resolve(r(e.parse(o),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(r(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}});var Rhe=T(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.regexpCode=Va.getEsmExportName=Va.getProperty=Va.safeStringify=Va.stringify=Va.strConcat=Va.addCodeArg=Va.str=Va._=Va.nil=Va._Code=Va.Name=Va.IDENTIFIER=Va._CodeOrName=void 0;var Ihe=class{};Va._CodeOrName=Ihe;Va.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var WU=class extends Ihe{constructor(e){if(super(),!Va.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Va.Name=WU;var Iv=class extends Ihe{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof WU&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Va._Code=Iv;Va.nil=new Iv("");function WFr(t,...e){let r=[t[0]],n=0;for(;n<e.length;)F6t(r,e[n]),r.push(t[++n]);return new Iv(r)}Va._=WFr;var M6t=new Iv("+");function zFr(t,...e){let r=[Dhe(t[0])],n=0;for(;n<e.length;)r.push(M6t),F6t(r,e[n]),r.push(M6t,Dhe(t[++n]));return iAo(r),new Iv(r)}Va.str=zFr;function F6t(t,e){e instanceof Iv?t.push(...e._items):e instanceof WU?t.push(e):t.push(aAo(e))}Va.addCodeArg=F6t;function iAo(t){let e=1;for(;e<t.length-1;){if(t[e]===M6t){let r=oAo(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function oAo(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof WU||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof WU))return`"${t}${e.slice(1)}`}function sAo(t,e){return e.emptyStr()?t:t.emptyStr()?e:zFr`${t}${e}`}Va.strConcat=sAo;function aAo(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Dhe(Array.isArray(t)?t.join(","):t)}function cAo(t){return new Iv(Dhe(t))}Va.stringify=cAo;function Dhe(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Va.safeStringify=Dhe;function lAo(t){return typeof t=="string"&&Va.IDENTIFIER.test(t)?new Iv(`.${t}`):WFr`[${t}]`}Va.getProperty=lAo;function uAo(t){if(typeof t=="string"&&Va.IDENTIFIER.test(t))return new Iv(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Va.getEsmExportName=uAo;function dAo(t){return new Iv(t.toString())}Va.regexpCode=dAo});var Q6t=T(Q3=>{"use strict";Object.defineProperty(Q3,"__esModule",{value:!0});Q3.ValueScope=Q3.ValueScopeName=Q3.Scope=Q3.varKinds=Q3.UsedValueState=void 0;var U3=Rhe(),L6t=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Eke;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Eke||(Q3.UsedValueState=Eke={}));Q3.varKinds={const:new U3.Name("const"),let:new U3.Name("let"),var:new U3.Name("var")};var vke=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof U3.Name?e:this.name(e)}name(e){return new U3.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Q3.Scope=vke;var bke=class extends U3.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,U3._)`.${new U3.Name(r)}[${n}]`}};Q3.ValueScopeName=bke;var fAo=(0,U3._)`\n`,U6t=class extends vke{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fAo:U3.nil}}get(){return this._scope}name(e){return new bke(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,a=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[s];if(c){let f=c.get(a);if(f)return f}else c=this._values[s]=new Map;c.set(a,o);let u=this._scope[s]||(this._scope[s]=[]),d=u.length;return u[d]=r.ref,o.setValue(r,{property:s,itemIndex:d}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,U3._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=U3.nil;for(let a in e){let c=e[a];if(!c)continue;let u=n[a]=n[a]||new Map;c.forEach(d=>{if(u.has(d))return;u.set(d,Eke.Started);let f=r(d);if(f){let p=this.opts.es5?Q3.varKinds.var:Q3.varKinds.const;s=(0,U3._)`${s}${p} ${d} = ${f};${this.opts._n}`}else if(f=o?.(d))s=(0,U3._)`${s}${f}${this.opts._n}`;else throw new L6t(d);u.set(d,Eke.Completed)})}return s}};Q3.ValueScope=U6t});var Is=T(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.or=Gs.and=Gs.not=Gs.CodeGen=Gs.operators=Gs.varKinds=Gs.ValueScopeName=Gs.ValueScope=Gs.Scope=Gs.Name=Gs.regexpCode=Gs.stringify=Gs.getProperty=Gs.nil=Gs.strConcat=Gs.str=Gs._=void 0;var ba=Rhe(),DC=Q6t(),SO=Rhe();Object.defineProperty(Gs,"_",{enumerable:!0,get:function(){return SO._}});Object.defineProperty(Gs,"str",{enumerable:!0,get:function(){return SO.str}});Object.defineProperty(Gs,"strConcat",{enumerable:!0,get:function(){return SO.strConcat}});Object.defineProperty(Gs,"nil",{enumerable:!0,get:function(){return SO.nil}});Object.defineProperty(Gs,"getProperty",{enumerable:!0,get:function(){return SO.getProperty}});Object.defineProperty(Gs,"stringify",{enumerable:!0,get:function(){return SO.stringify}});Object.defineProperty(Gs,"regexpCode",{enumerable:!0,get:function(){return SO.regexpCode}});Object.defineProperty(Gs,"Name",{enumerable:!0,get:function(){return SO.Name}});var wke=Q6t();Object.defineProperty(Gs,"Scope",{enumerable:!0,get:function(){return wke.Scope}});Object.defineProperty(Gs,"ValueScope",{enumerable:!0,get:function(){return wke.ValueScope}});Object.defineProperty(Gs,"ValueScopeName",{enumerable:!0,get:function(){return wke.ValueScopeName}});Object.defineProperty(Gs,"varKinds",{enumerable:!0,get:function(){return wke.varKinds}});Gs.operators={GT:new ba._Code(">"),GTE:new ba._Code(">="),LT:new ba._Code("<"),LTE:new ba._Code("<="),EQ:new ba._Code("==="),NEQ:new ba._Code("!=="),NOT:new ba._Code("!"),OR:new ba._Code("||"),AND:new ba._Code("&&"),ADD:new ba._Code("+")};var i7=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},j6t=class extends i7{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?DC.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=_J(this.rhs,e,r)),this}get names(){return this.rhs instanceof ba._CodeOrName?this.rhs.names:{}}},Cke=class extends i7{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ba.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=_J(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ba.Name?{}:{...this.lhs.names};return xke(e,this.rhs)}},G6t=class extends Cke{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},$6t=class extends i7{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},q6t=class extends i7{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},H6t=class extends i7{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},V6t=class extends i7{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=_J(this.code,e,r),this}get names(){return this.code instanceof ba._CodeOrName?this.code.names:{}}},Nhe=class extends i7{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(pAo(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>KU(e,r.names),{})}},o7=class extends Nhe{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},W6t=class extends Nhe{},yJ=class extends o7{};yJ.kind="else";var zU=class t extends o7{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new yJ(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(YFr(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=_J(this.condition,e,r),this}get names(){let e=super.names;return xke(e,this.condition),this.else&&KU(e,this.else.names),e}};zU.kind="if";var YU=class extends o7{};YU.kind="for";var z6t=class extends YU{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=_J(this.iteration,e,r),this}get names(){return KU(super.names,this.iteration.names)}},Y6t=class extends YU{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?DC.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=xke(super.names,this.from);return xke(e,this.to)}},Ske=class extends YU{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=_J(this.iterable,e,r),this}get names(){return KU(super.names,this.iterable.names)}},Ohe=class extends o7{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ohe.kind="func";var khe=class extends Nhe{render(e){return"return "+super.render(e)}};khe.kind="return";var K6t=class extends o7{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&KU(e,this.catch.names),this.finally&&KU(e,this.finally.names),e}},Bhe=class extends o7{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Bhe.kind="catch";var Phe=class extends o7{render(e){return"finally"+super.render(e)}};Phe.kind="finally";var X6t=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
950
950
|
`:""},this._extScope=e,this._scope=new DC.Scope({parent:e}),this._nodes=[new W6t]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new j6t(e,s,n)),s}const(e,r,n){return this._def(DC.varKinds.const,e,r,n)}let(e,r,n){return this._def(DC.varKinds.let,e,r,n)}var(e,r,n){return this._def(DC.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Cke(e,r,n))}add(e,r){return this._leafNode(new G6t(e,Gs.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ba.nil&&this._leafNode(new V6t(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ba.addCodeArg)(r,o));return r.push("}"),new ba._Code(r)}if(e,r,n){if(this._blockNode(new zU(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new zU(e))}else(){return this._elseNode(new yJ)}endIf(){return this._endBlockNode(zU,yJ)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new z6t(e),r)}forRange(e,r,n,o,s=this.opts.es5?DC.varKinds.var:DC.varKinds.let){let a=this._scope.toName(e);return this._for(new Y6t(s,a,r,n),()=>o(a))}forOf(e,r,n,o=DC.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let a=r instanceof ba.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ba._)`${a}.length`,c=>{this.var(s,(0,ba._)`${a}[${c}]`),n(s)})}return this._for(new Ske("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?DC.varKinds.var:DC.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ba._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ske("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(YU)}label(e){return this._leafNode(new $6t(e))}break(e){return this._leafNode(new q6t(e))}return(e){let r=new khe;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(khe)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new K6t;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Bhe(s),r(s)}return n&&(this._currNode=o.finally=new Phe,this.code(n)),this._endBlockNode(Bhe,Phe)}throw(e){return this._leafNode(new H6t(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ba.nil,n,o){return this._blockNode(new Ohe(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ohe)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof zU))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};Gs.CodeGen=X6t;function KU(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function xke(t,e){return e instanceof ba._CodeOrName?KU(t,e.names):t}function _J(t,e,r){if(t instanceof ba.Name)return n(t);if(!o(t))return t;return new ba._Code(t._items.reduce((s,a)=>(a instanceof ba.Name&&(a=n(a)),a instanceof ba._Code?s.push(...a._items):s.push(a),s),[]));function n(s){let a=r[s.str];return a===void 0||e[s.str]!==1?s:(delete e[s.str],a)}function o(s){return s instanceof ba._Code&&s._items.some(a=>a instanceof ba.Name&&e[a.str]===1&&r[a.str]!==void 0)}}function pAo(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function YFr(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ba._)`!${J6t(t)}`}Gs.not=YFr;var hAo=KFr(Gs.operators.AND);function mAo(...t){return t.reduce(hAo)}Gs.and=mAo;var gAo=KFr(Gs.operators.OR);function AAo(...t){return t.reduce(gAo)}Gs.or=AAo;function KFr(t){return(e,r)=>e===ba.nil?r:r===ba.nil?e:(0,ba._)`${J6t(e)} ${t} ${J6t(r)}`}function J6t(t){return t instanceof ba.Name?t:(0,ba._)`(${t})`}});var Wa=T(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.checkStrictMode=zs.getErrorPath=zs.Type=zs.useFunc=zs.setEvaluated=zs.evaluatedPropsToName=zs.mergeEvaluated=zs.eachItem=zs.unescapeJsonPointer=zs.escapeJsonPointer=zs.escapeFragment=zs.unescapeFragment=zs.schemaRefOrVal=zs.schemaHasRulesButRef=zs.schemaHasRules=zs.checkUnknownRules=zs.alwaysValidSchema=zs.toHash=void 0;var zl=Is(),yAo=Rhe();function _Ao(t){let e={};for(let r of t)e[r]=!0;return e}zs.toHash=_Ao;function EAo(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ZFr(t,e),!eLr(e,t.self.RULES.all))}zs.alwaysValidSchema=EAo;function ZFr(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||nLr(t,`unknown keyword: "${s}"`)}zs.checkUnknownRules=ZFr;function eLr(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}zs.schemaHasRules=eLr;function vAo(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}zs.schemaHasRulesButRef=vAo;function bAo({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,zl._)`${r}`}return(0,zl._)`${t}${e}${(0,zl.getProperty)(n)}`}zs.schemaRefOrVal=bAo;function CAo(t){return tLr(decodeURIComponent(t))}zs.unescapeFragment=CAo;function SAo(t){return encodeURIComponent(evt(t))}zs.escapeFragment=SAo;function evt(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}zs.escapeJsonPointer=evt;function tLr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}zs.unescapeJsonPointer=tLr;function xAo(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}zs.eachItem=xAo;function XFr({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,a,c)=>{let u=a===void 0?s:a instanceof zl.Name?(s instanceof zl.Name?t(o,s,a):e(o,s,a),a):s instanceof zl.Name?(e(o,a,s),s):r(s,a);return c===zl.Name&&!(u instanceof zl.Name)?n(o,u):u}}zs.mergeEvaluated={props:XFr({mergeNames:(t,e,r)=>t.if((0,zl._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,zl._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,zl._)`${r} || {}`).code((0,zl._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,zl._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,zl._)`${r} || {}`),tvt(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:rLr}),items:XFr({mergeNames:(t,e,r)=>t.if((0,zl._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,zl._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,zl._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,zl._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function rLr(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,zl._)`{}`);return e!==void 0&&tvt(t,r,e),r}zs.evaluatedPropsToName=rLr;function tvt(t,e,r){Object.keys(r).forEach(n=>t.assign((0,zl._)`${e}${(0,zl.getProperty)(n)}`,!0))}zs.setEvaluated=tvt;var JFr={};function wAo(t,e){return t.scopeValue("func",{ref:e,code:JFr[e.code]||(JFr[e.code]=new yAo._Code(e.code))})}zs.useFunc=wAo;var Z6t;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Z6t||(zs.Type=Z6t={}));function TAo(t,e,r){if(t instanceof zl.Name){let n=e===Z6t.Num;return r?n?(0,zl._)`"[" + ${t} + "]"`:(0,zl._)`"['" + ${t} + "']"`:n?(0,zl._)`"/" + ${t}`:(0,zl._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,zl.getProperty)(t).toString():"/"+evt(t)}zs.getErrorPath=TAo;function nLr(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}zs.checkStrictMode=nLr});var s7=T(rvt=>{"use strict";Object.defineProperty(rvt,"__esModule",{value:!0});var kA=Is(),IAo={data:new kA.Name("data"),valCxt:new kA.Name("valCxt"),instancePath:new kA.Name("instancePath"),parentData:new kA.Name("parentData"),parentDataProperty:new kA.Name("parentDataProperty"),rootData:new kA.Name("rootData"),dynamicAnchors:new kA.Name("dynamicAnchors"),vErrors:new kA.Name("vErrors"),errors:new kA.Name("errors"),this:new kA.Name("this"),self:new kA.Name("self"),scope:new kA.Name("scope"),json:new kA.Name("json"),jsonPos:new kA.Name("jsonPos"),jsonLen:new kA.Name("jsonLen"),jsonPart:new kA.Name("jsonPart")};rvt.default=IAo});var Mhe=T(BA=>{"use strict";Object.defineProperty(BA,"__esModule",{value:!0});BA.extendErrors=BA.resetErrorsCount=BA.reportExtraError=BA.reportError=BA.keyword$DataError=BA.keywordError=void 0;var Ma=Is(),Tke=Wa(),s1=s7();BA.keywordError={message:({keyword:t})=>(0,Ma.str)`must pass "${t}" keyword validation`};BA.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Ma.str)`"${t}" keyword must be ${e} ($data)`:(0,Ma.str)`"${t}" keyword is invalid ($data)`};function DAo(t,e=BA.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:a,allErrors:c}=o,u=sLr(t,e,r);n??(a||c)?iLr(s,u):oLr(o,(0,Ma._)`[${u}]`)}BA.reportError=DAo;function RAo(t,e=BA.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:a}=n,c=sLr(t,e,r);iLr(o,c),s||a||oLr(n,s1.default.vErrors)}BA.reportExtraError=RAo;function NAo(t,e){t.assign(s1.default.errors,e),t.if((0,Ma._)`${s1.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Ma._)`${s1.default.vErrors}.length`,e),()=>t.assign(s1.default.vErrors,null)))}BA.resetErrorsCount=NAo;function OAo({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let a=t.name("err");t.forRange("i",o,s1.default.errors,c=>{t.const(a,(0,Ma._)`${s1.default.vErrors}[${c}]`),t.if((0,Ma._)`${a}.instancePath === undefined`,()=>t.assign((0,Ma._)`${a}.instancePath`,(0,Ma.strConcat)(s1.default.instancePath,s.errorPath))),t.assign((0,Ma._)`${a}.schemaPath`,(0,Ma.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Ma._)`${a}.schema`,r),t.assign((0,Ma._)`${a}.data`,n))})}BA.extendErrors=OAo;function iLr(t,e){let r=t.const("err",e);t.if((0,Ma._)`${s1.default.vErrors} === null`,()=>t.assign(s1.default.vErrors,(0,Ma._)`[${r}]`),(0,Ma._)`${s1.default.vErrors}.push(${r})`),t.code((0,Ma._)`${s1.default.errors}++`)}function oLr(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Ma._)`new ${t.ValidationError}(${e})`):(r.assign((0,Ma._)`${n}.errors`,e),r.return(!1))}var XU={keyword:new Ma.Name("keyword"),schemaPath:new Ma.Name("schemaPath"),params:new Ma.Name("params"),propertyName:new Ma.Name("propertyName"),message:new Ma.Name("message"),schema:new Ma.Name("schema"),parentSchema:new Ma.Name("parentSchema")};function sLr(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Ma._)`{}`:kAo(t,e,r)}function kAo(t,e,r={}){let{gen:n,it:o}=t,s=[BAo(o,r),PAo(t,r)];return MAo(t,e,s),n.object(...s)}function BAo({errorPath:t},{instancePath:e}){let r=e?(0,Ma.str)`${t}${(0,Tke.getErrorPath)(e,Tke.Type.Str)}`:t;return[s1.default.instancePath,(0,Ma.strConcat)(s1.default.instancePath,r)]}function PAo({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Ma.str)`${e}/${t}`;return r&&(o=(0,Ma.str)`${o}${(0,Tke.getErrorPath)(r,Tke.Type.Str)}`),[XU.schemaPath,o]}function MAo(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:a,it:c}=t,{opts:u,propertyName:d,topSchemaRef:f,schemaPath:p}=c;n.push([XU.keyword,o],[XU.params,typeof e=="function"?e(t):e||(0,Ma._)`{}`]),u.messages&&n.push([XU.message,typeof r=="function"?r(t):r]),u.verbose&&n.push([XU.schema,a],[XU.parentSchema,(0,Ma._)`${f}${p}`],[s1.default.data,s]),d&&n.push([XU.propertyName,d])}});var cLr=T(EJ=>{"use strict";Object.defineProperty(EJ,"__esModule",{value:!0});EJ.boolOrEmptySchema=EJ.topBoolOrEmptySchema=void 0;var FAo=Mhe(),LAo=Is(),UAo=s7(),QAo={message:"boolean schema is false"};function jAo(t){let{gen:e,schema:r,validateName:n}=t;r===!1?aLr(t,!1):typeof r=="object"&&r.$async===!0?e.return(UAo.default.data):(e.assign((0,LAo._)`${n}.errors`,null),e.return(!0))}EJ.topBoolOrEmptySchema=jAo;function GAo(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),aLr(t)):r.var(e,!0)}EJ.boolOrEmptySchema=GAo;function aLr(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,FAo.reportError)(o,QAo,void 0,e)}});var nvt=T(vJ=>{"use strict";Object.defineProperty(vJ,"__esModule",{value:!0});vJ.getRules=vJ.isJSONType=void 0;var $Ao=["string","number","integer","boolean","null","object","array"],qAo=new Set($Ao);function HAo(t){return typeof t=="string"&&qAo.has(t)}vJ.isJSONType=HAo;function VAo(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}vJ.getRules=VAo});var ivt=T(xO=>{"use strict";Object.defineProperty(xO,"__esModule",{value:!0});xO.shouldUseRule=xO.shouldUseGroup=xO.schemaHasRulesForType=void 0;function WAo({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&lLr(t,n)}xO.schemaHasRulesForType=WAo;function lLr(t,e){return e.rules.some(r=>uLr(t,r))}xO.shouldUseGroup=lLr;function uLr(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}xO.shouldUseRule=uLr});var Fhe=T(PA=>{"use strict";Object.defineProperty(PA,"__esModule",{value:!0});PA.reportTypeError=PA.checkDataTypes=PA.checkDataType=PA.coerceAndCheckDataType=PA.getJSONTypes=PA.getSchemaTypes=PA.DataType=void 0;var zAo=nvt(),YAo=ivt(),KAo=Mhe(),Es=Is(),dLr=Wa(),bJ;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(bJ||(PA.DataType=bJ={}));function XAo(t){let e=fLr(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}PA.getSchemaTypes=XAo;function fLr(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(zAo.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}PA.getJSONTypes=fLr;function JAo(t,e){let{gen:r,data:n,opts:o}=t,s=ZAo(e,o.coerceTypes),a=e.length>0&&!(s.length===0&&e.length===1&&(0,YAo.schemaHasRulesForType)(t,e[0]));if(a){let c=svt(e,n,o.strictNumbers,bJ.Wrong);r.if(c,()=>{s.length?e2o(t,e,s):avt(t)})}return a}PA.coerceAndCheckDataType=JAo;var pLr=new Set(["string","number","integer","boolean","null"]);function ZAo(t,e){return e?t.filter(r=>pLr.has(r)||e==="array"&&r==="array"):[]}function e2o(t,e,r){let{gen:n,data:o,opts:s}=t,a=n.let("dataType",(0,Es._)`typeof ${o}`),c=n.let("coerced",(0,Es._)`undefined`);s.coerceTypes==="array"&&n.if((0,Es._)`${a} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,Es._)`${o}[0]`).assign(a,(0,Es._)`typeof ${o}`).if(svt(e,o,s.strictNumbers),()=>n.assign(c,o))),n.if((0,Es._)`${c} !== undefined`);for(let d of r)(pLr.has(d)||d==="array"&&s.coerceTypes==="array")&&u(d);n.else(),avt(t),n.endIf(),n.if((0,Es._)`${c} !== undefined`,()=>{n.assign(o,c),t2o(t,c)});function u(d){switch(d){case"string":n.elseIf((0,Es._)`${a} == "number" || ${a} == "boolean"`).assign(c,(0,Es._)`"" + ${o}`).elseIf((0,Es._)`${o} === null`).assign(c,(0,Es._)`""`);return;case"number":n.elseIf((0,Es._)`${a} == "boolean" || ${o} === null
|
|
951
951
|
|| (${a} == "string" && ${o} && ${o} == +${o})`).assign(c,(0,Es._)`+${o}`);return;case"integer":n.elseIf((0,Es._)`${a} === "boolean" || ${o} === null
|
|
952
952
|
|| (${a} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(c,(0,Es._)`+${o}`);return;case"boolean":n.elseIf((0,Es._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(c,!1).elseIf((0,Es._)`${o} === "true" || ${o} === 1`).assign(c,!0);return;case"null":n.elseIf((0,Es._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(c,null);return;case"array":n.elseIf((0,Es._)`${a} === "string" || ${a} === "number"
|
|
@@ -959,7 +959,7 @@ ${e}
|
|
|
959
959
|
`;break;case"id":c=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new aBe(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:E}));break;default:r(new aBe(`Unknown field "${A.length>20?`${A.slice(0,20)}\u2026`:A}"`,{type:"unknown-field",field:A,value:y,line:E}));break}}function m(){u.length>0&&e({id:c,event:d||void 0,data:u.endsWith(`
|
|
960
960
|
`)?u.slice(0,-1):u}),c=void 0,u="",d=""}function g(A={}){s&&A.consume&&p(s),a=!0,c=void 0,u="",d="",s=""}return{feed:f,reset:g}}function xEo(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),s=t.indexOf(`
|
|
961
961
|
`,n),a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===t.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){r=t.slice(n);break}else{let c=t.slice(n,a);e.push(c),n=a+1,t[n-1]==="\r"&&t[n]===`
|
|
962
|
-
`&&n++}}return[e,r]}var aBe,Lbt=te(()=>{aBe=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function wEo(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Ubt(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Ubt).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Ubt(t.cause)}`:t.message:`${t}`}function wjr(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function TEo(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var uBe,Ijr,Wbt,na,Wh,Md,l7,$3,nQ,LJ,lBe,dBe,ome,jJ,sme,OO,UJ,GJ,QJ,nme,BC,Qbt,jbt,Gbt,Tjr,$bt,qbt,ime,Hbt,Vbt,iQ,Djr=te(()=>{Lbt();uBe=class extends Event{constructor(e,r){var n,o;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(wjr(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(wjr(this),r)}};Ijr=t=>{throw TypeError(t)},Wbt=(t,e,r)=>e.has(t)||Ijr("Cannot "+r),na=(t,e,r)=>(Wbt(t,e,"read from private field"),r?r.call(t):e.get(t)),Wh=(t,e,r)=>e.has(t)?Ijr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Md=(t,e,r,n)=>(Wbt(t,e,"write to private field"),e.set(t,r),r),l7=(t,e,r)=>(Wbt(t,e,"access private method"),r),iQ=class extends EventTarget{constructor(e,r){var n,o;super(),Wh(this,BC),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Wh(this,$3),Wh(this,nQ),Wh(this,LJ),Wh(this,lBe),Wh(this,dBe),Wh(this,ome),Wh(this,jJ),Wh(this,sme,null),Wh(this,OO),Wh(this,UJ),Wh(this,GJ,null),Wh(this,QJ,null),Wh(this,nme,null),Wh(this,jbt,async s=>{var a;na(this,UJ).reset();let{body:c,redirected:u,status:d,headers:f}=s;if(d===204){l7(this,BC,ime).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Md(this,LJ,new URL(s.url)):Md(this,LJ,void 0),d!==200){l7(this,BC,ime).call(this,`Non-200 status code (${d})`,d);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){l7(this,BC,ime).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(na(this,$3)===this.CLOSED)return;Md(this,$3,this.OPEN);let p=new Event("open");if((a=na(this,nme))==null||a.call(this,p),this.dispatchEvent(p),typeof c!="object"||!c||!("getReader"in c)){l7(this,BC,ime).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}let h=new TextDecoder,m=c.getReader(),g=!0;do{let{done:A,value:y}=await m.read();y&&na(this,UJ).feed(h.decode(y,{stream:!A})),A&&(g=!1,na(this,UJ).reset(),l7(this,BC,Hbt).call(this))}while(g)}),Wh(this,Gbt,s=>{Md(this,OO,void 0),!(s.name==="AbortError"||s.type==="aborted")&&l7(this,BC,Hbt).call(this,Ubt(s))}),Wh(this,$bt,s=>{typeof s.id=="string"&&Md(this,sme,s.id);let a=new MessageEvent(s.event||"message",{data:s.data,origin:na(this,LJ)?na(this,LJ).origin:na(this,nQ).origin,lastEventId:s.id||""});na(this,QJ)&&(!s.event||s.event==="message")&&na(this,QJ).call(this,a),this.dispatchEvent(a)}),Wh(this,qbt,s=>{Md(this,ome,s)}),Wh(this,Vbt,()=>{Md(this,jJ,void 0),na(this,$3)===this.CONNECTING&&l7(this,BC,Qbt).call(this)});try{if(e instanceof URL)Md(this,nQ,e);else if(typeof e=="string")Md(this,nQ,new URL(e,TEo()));else throw new Error("Invalid URL")}catch{throw wEo("An invalid or illegal string was specified")}Md(this,UJ,cBe({onEvent:na(this,$bt),onRetry:na(this,qbt)})),Md(this,$3,this.CONNECTING),Md(this,ome,3e3),Md(this,dBe,(n=r?.fetch)!=null?n:globalThis.fetch),Md(this,lBe,(o=r?.withCredentials)!=null?o:!1),l7(this,BC,Qbt).call(this)}get readyState(){return na(this,$3)}get url(){return na(this,nQ).href}get withCredentials(){return na(this,lBe)}get onerror(){return na(this,GJ)}set onerror(e){Md(this,GJ,e)}get onmessage(){return na(this,QJ)}set onmessage(e){Md(this,QJ,e)}get onopen(){return na(this,nme)}set onopen(e){Md(this,nme,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){na(this,jJ)&&clearTimeout(na(this,jJ)),na(this,$3)!==this.CLOSED&&(na(this,OO)&&na(this,OO).abort(),Md(this,$3,this.CLOSED),Md(this,OO,void 0))}};$3=new WeakMap,nQ=new WeakMap,LJ=new WeakMap,lBe=new WeakMap,dBe=new WeakMap,ome=new WeakMap,jJ=new WeakMap,sme=new WeakMap,OO=new WeakMap,UJ=new WeakMap,GJ=new WeakMap,QJ=new WeakMap,nme=new WeakMap,BC=new WeakSet,Qbt=function(){Md(this,$3,this.CONNECTING),Md(this,OO,new AbortController),na(this,dBe)(na(this,nQ),l7(this,BC,Tjr).call(this)).then(na(this,jbt)).catch(na(this,Gbt))},jbt=new WeakMap,Gbt=new WeakMap,Tjr=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...na(this,sme)?{"Last-Event-ID":na(this,sme)}:void 0},cache:"no-store",signal:(t=na(this,OO))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},$bt=new WeakMap,qbt=new WeakMap,ime=function(t,e){var r;na(this,$3)!==this.CLOSED&&Md(this,$3,this.CLOSED);let n=new uBe("error",{code:e,message:t});(r=na(this,GJ))==null||r.call(this,n),this.dispatchEvent(n)},Hbt=function(t,e){var r;if(na(this,$3)===this.CLOSED)return;Md(this,$3,this.CONNECTING);let n=new uBe("error",{code:e,message:t});(r=na(this,GJ))==null||r.call(this,n),this.dispatchEvent(n),Md(this,jJ,setTimeout(na(this,Vbt),na(this,ome)))},Vbt=new WeakMap,iQ.CONNECTING=0,iQ.OPEN=1,iQ.CLOSED=2});async function IEo(t){return(await zbt).getRandomValues(new Uint8Array(t))}async function DEo(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await IEo(t);for(let o=0;o<t;o++){let s=n[o]%e.length;r+=e[s]}return r}async function REo(t){return await DEo(t)}async function NEo(t){let e=await(await zbt).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Ybt(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await REo(t),r=await NEo(e);return{code_verifier:e,code_challenge:r}}var zbt,Rjr=te(()=>{zbt=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var f0,Ojr,Kbt,OEo,kjr,Xbt,Bjr,Njr,kEo,BEo,Pjr,Lqa,Uqa,Jbt=te(()=>{vO();f0=se.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:se.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),se.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ojr=se.object({resource:se.string().url(),authorization_servers:se.array(f0).optional(),jwks_uri:se.string().url().optional(),scopes_supported:se.array(se.string()).optional(),bearer_methods_supported:se.array(se.string()).optional(),resource_signing_alg_values_supported:se.array(se.string()).optional(),resource_name:se.string().optional(),resource_documentation:se.string().optional(),resource_policy_uri:se.string().url().optional(),resource_tos_uri:se.string().url().optional(),tls_client_certificate_bound_access_tokens:se.boolean().optional(),authorization_details_types_supported:se.array(se.string()).optional(),dpop_signing_alg_values_supported:se.array(se.string()).optional(),dpop_bound_access_tokens_required:se.boolean().optional()}).passthrough(),Kbt=se.object({issuer:se.string(),authorization_endpoint:f0,token_endpoint:f0,registration_endpoint:f0.optional(),scopes_supported:se.array(se.string()).optional(),response_types_supported:se.array(se.string()),response_modes_supported:se.array(se.string()).optional(),grant_types_supported:se.array(se.string()).optional(),token_endpoint_auth_methods_supported:se.array(se.string()).optional(),token_endpoint_auth_signing_alg_values_supported:se.array(se.string()).optional(),service_documentation:f0.optional(),revocation_endpoint:f0.optional(),revocation_endpoint_auth_methods_supported:se.array(se.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:se.array(se.string()).optional(),introspection_endpoint:se.string().optional(),introspection_endpoint_auth_methods_supported:se.array(se.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:se.array(se.string()).optional(),code_challenge_methods_supported:se.array(se.string()).optional()}).passthrough(),OEo=se.object({issuer:se.string(),authorization_endpoint:f0,token_endpoint:f0,userinfo_endpoint:f0.optional(),jwks_uri:f0,registration_endpoint:f0.optional(),scopes_supported:se.array(se.string()).optional(),response_types_supported:se.array(se.string()),response_modes_supported:se.array(se.string()).optional(),grant_types_supported:se.array(se.string()).optional(),acr_values_supported:se.array(se.string()).optional(),subject_types_supported:se.array(se.string()),id_token_signing_alg_values_supported:se.array(se.string()),id_token_encryption_alg_values_supported:se.array(se.string()).optional(),id_token_encryption_enc_values_supported:se.array(se.string()).optional(),userinfo_signing_alg_values_supported:se.array(se.string()).optional(),userinfo_encryption_alg_values_supported:se.array(se.string()).optional(),userinfo_encryption_enc_values_supported:se.array(se.string()).optional(),request_object_signing_alg_values_supported:se.array(se.string()).optional(),request_object_encryption_alg_values_supported:se.array(se.string()).optional(),request_object_encryption_enc_values_supported:se.array(se.string()).optional(),token_endpoint_auth_methods_supported:se.array(se.string()).optional(),token_endpoint_auth_signing_alg_values_supported:se.array(se.string()).optional(),display_values_supported:se.array(se.string()).optional(),claim_types_supported:se.array(se.string()).optional(),claims_supported:se.array(se.string()).optional(),service_documentation:se.string().optional(),claims_locales_supported:se.array(se.string()).optional(),ui_locales_supported:se.array(se.string()).optional(),claims_parameter_supported:se.boolean().optional(),request_parameter_supported:se.boolean().optional(),request_uri_parameter_supported:se.boolean().optional(),require_request_uri_registration:se.boolean().optional(),op_policy_uri:f0.optional(),op_tos_uri:f0.optional()}).passthrough(),kjr=OEo.merge(Kbt.pick({code_challenge_methods_supported:!0})),Xbt=se.object({access_token:se.string(),id_token:se.string().optional(),token_type:se.string(),expires_in:se.number().optional(),scope:se.string().optional(),refresh_token:se.string().optional()}).strip(),Bjr=se.object({error:se.string(),error_description:se.string().optional(),error_uri:se.string().optional()}),Njr=f0.optional().or(se.literal("").transform(()=>{})),kEo=se.object({redirect_uris:se.array(f0),token_endpoint_auth_method:se.string().optional(),grant_types:se.array(se.string()).optional(),response_types:se.array(se.string()).optional(),client_name:se.string().optional(),client_uri:f0.optional(),logo_uri:Njr,scope:se.string().optional(),contacts:se.array(se.string()).optional(),tos_uri:Njr,policy_uri:se.string().optional(),jwks_uri:f0.optional(),jwks:se.any().optional(),software_id:se.string().optional(),software_version:se.string().optional(),software_statement:se.string().optional()}).strip(),BEo=se.object({client_id:se.string(),client_secret:se.string().optional(),client_id_issued_at:se.number().optional(),client_secret_expires_at:se.number().optional()}).strip(),Pjr=kEo.merge(BEo),Lqa=se.object({error:se.string(),error_description:se.string().optional()}).strip(),Uqa=se.object({token:se.string(),token_type_hint:se.string().optional()}).strip()});function Mjr(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Fjr({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var Ljr=te(()=>{});var dh,ame,oQ,sQ,aQ,cme,lme,ume,u7,dme,fme,pme,hme,mme,gme,Ame,yme,Ujr,Qjr=te(()=>{dh=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},ame=class extends dh{};ame.errorCode="invalid_request";oQ=class extends dh{};oQ.errorCode="invalid_client";sQ=class extends dh{};sQ.errorCode="invalid_grant";aQ=class extends dh{};aQ.errorCode="unauthorized_client";cme=class extends dh{};cme.errorCode="unsupported_grant_type";lme=class extends dh{};lme.errorCode="invalid_scope";ume=class extends dh{};ume.errorCode="access_denied";u7=class extends dh{};u7.errorCode="server_error";dme=class extends dh{};dme.errorCode="temporarily_unavailable";fme=class extends dh{};fme.errorCode="unsupported_response_type";pme=class extends dh{};pme.errorCode="unsupported_token_type";hme=class extends dh{};hme.errorCode="invalid_token";mme=class extends dh{};mme.errorCode="method_not_allowed";gme=class extends dh{};gme.errorCode="too_many_requests";Ame=class extends dh{};Ame.errorCode="invalid_client_metadata";yme=class extends dh{};yme.errorCode="insufficient_scope";Ujr={[ame.errorCode]:ame,[oQ.errorCode]:oQ,[sQ.errorCode]:sQ,[aQ.errorCode]:aQ,[cme.errorCode]:cme,[lme.errorCode]:lme,[ume.errorCode]:ume,[u7.errorCode]:u7,[dme.errorCode]:dme,[fme.errorCode]:fme,[pme.errorCode]:pme,[hme.errorCode]:hme,[mme.errorCode]:mme,[gme.errorCode]:gme,[Ame.errorCode]:Ame,[yme.errorCode]:yme}});function PEo(t){return["client_secret_basic","client_secret_post","none"].includes(t)}function Gjr(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&PEo(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function $jr(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":MEo(o,s,r);return;case"client_secret_post":FEo(o,s,n);return;case"none":LEo(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function MEo(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function FEo(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function LEo(t,e){e.set("client_id",t)}async function r4t(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=Bjr.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,c=Ujr[o]||u7;return new c(s||"",a)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new u7(o)}}async function kO(t,e){var r,n;try{return await t4t(t,e)}catch(o){if(o instanceof oQ||o instanceof aQ)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await t4t(t,e);if(o instanceof sQ)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await t4t(t,e);throw o}}async function t4t(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,c;try{a=await QEo(e,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(c=a.authorization_servers[0])}catch{}c||(c=e);let u=await UEo(e,t,a),d=await HEo(c,{fetchFn:s}),f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let A=await WEo(c,{metadata:d,clientMetadata:t.clientMetadata,fetchFn:s});await t.saveClientInformation(A),f=A}if(r!==void 0){let A=await t.codeVerifier(),y=await i4t(c,{metadata:d,clientInformation:f,authorizationCode:r,codeVerifier:A,redirectUri:t.redirectUrl,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(y),"AUTHORIZED"}let p=await t.tokens();if(p?.refresh_token)try{let A=await o4t(c,{metadata:d,clientInformation:f,refreshToken:p.refresh_token,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(A),"AUTHORIZED"}catch(A){if(!(!(A instanceof dh)||A instanceof u7))throw A}let h=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:g}=await VEo(c,{metadata:d,clientInformation:f,state:h,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:u});return await t.saveCodeVerifier(g),await t.redirectToAuthorization(m),"REDIRECT"}async function UEo(t,e,r){let n=Mjr(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Fjr({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function _me(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let s=/resource_metadata="([^"]*)"/.exec(e),c=/scope="([^"]*)"/.exec(e),u;if(s)try{u=new URL(s[1])}catch{}let d=c?.[1]||void 0;return{resourceMetadataUrl:u,scope:d}}async function QEo(t,e,r=fetch){let n=await $Eo(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Ojr.parse(await n.json())}async function n4t(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?n4t(t,void 0,r):void 0;throw n}}function jEo(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function jjr(t,e,r=fetch){return await n4t(t,{"MCP-Protocol-Version":e},r)}function GEo(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function $Eo(t,e,r,n){var o,s;let a=new URL(t),c=(o=n?.protocolVersion)!==null&&o!==void 0?o:AJ,u;if(n?.metadataUrl)u=new URL(n.metadataUrl);else{let f=jEo(e,a.pathname);u=new URL(f,(s=n?.metadataServerUrl)!==null&&s!==void 0?s:a),u.search=a.search}let d=await jjr(u,c,r);if(!n?.metadataUrl&&GEo(d,a.pathname)){let f=new URL(`/.well-known/${e}`,a);d=await jjr(f,c,r)}return d}function qEo(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function HEo(t,{fetchFn:e=fetch,protocolVersion:r=AJ}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=qEo(t);for(let{url:s,type:a}of o){let c=await n4t(s,n,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?Kbt.parse(await c.json()):kjr.parse(await c.json())}}}async function VEo(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let c;if(e){if(c=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Zbt))throw new Error(`Incompatible auth server: does not support response type ${Zbt}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(e4t))throw new Error(`Incompatible auth server: does not support code challenge method ${e4t}`)}else c=new URL("/authorize",t);let u=await Ybt(),d=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",Zbt),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",e4t),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:d}}async function i4t(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:c,fetchFn:u}){var d;let f="authorization_code",p=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(f))throw new Error(`Incompatible auth server: does not support grant type ${f}`);let h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),m=new URLSearchParams({grant_type:f,code:n,code_verifier:o,redirect_uri:String(s)});if(c)c(h,m,t,e);else{let A=(d=e?.token_endpoint_auth_methods_supported)!==null&&d!==void 0?d:[],y=Gjr(r,A);$jr(y,r,h,m)}a&&m.set("resource",a.href);let g=await(u??fetch)(p,{method:"POST",headers:h,body:m});if(!g.ok)throw await r4t(g);return Xbt.parse(await g.json())}async function o4t(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var c;let u="refresh_token",d;if(e){if(d=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`)}else d=new URL("/token",t);let f=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),p=new URLSearchParams({grant_type:u,refresh_token:n});if(s)s(f,p,t,e);else{let m=(c=e?.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],g=Gjr(r,m);$jr(g,r,f,p)}o&&p.set("resource",o.href);let h=await(a??fetch)(d,{method:"POST",headers:f,body:p});if(!h.ok)throw await r4t(h);return Xbt.parse({refresh_token:n,...await h.json()})}async function WEo(t,{metadata:e,clientMetadata:r,fetchFn:n}){let o;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(e.registration_endpoint)}else o=new URL("/register",t);let s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await r4t(s);return Pjr.parse(await s.json())}var q3,Zbt,e4t,fBe=te(()=>{Rjr();CO();Jbt();Jbt();Ljr();Qjr();q3=class extends Error{constructor(e){super(e??"Unauthorized")}};Zbt="code",e4t="S256"});var s4t,$J,qjr=te(()=>{Djr();CO();fBe();s4t=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},$J=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new q3("No auth provider");let r;try{r=await kO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new q3;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let o=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((s,a)=>{this._eventSource=new iQ(this._url.href,{...this._eventSourceInit,fetch:async(c,u)=>{let d=await this._commonHeaders();d.set("Accept","text/event-stream");let f=await o(c,{...u,headers:d});if(f.status===401&&f.headers.has("www-authenticate")){let{resourceMetadataUrl:p,scope:h}=_me(f);this._resourceMetadataUrl=p,this._scope=h}return f}}),this._abortController=new AbortController,this._eventSource.onerror=c=>{var u;if(c.code===401&&this._authProvider){this._authThenStart().then(s,a);return}let d=new s4t(c.code,c.message,c);a(d),(u=this.onerror)===null||u===void 0||u.call(this,d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",c=>{var u;let d=c;try{if(this._endpoint=new URL(d.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(f){a(f),(u=this.onerror)===null||u===void 0||u.call(this,f),this.close();return}s()}),this._eventSource.onmessage=c=>{var u,d;let f=c,p;try{p=bO.parse(JSON.parse(f.data))}catch(h){(u=this.onerror)===null||u===void 0||u.call(this,h);return}(d=this.onmessage)===null||d===void 0||d.call(this,p)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new q3("No auth provider");if(await kO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new q3("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},c=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!c.ok){if(c.status===401&&this._authProvider){let{resourceMetadataUrl:d,scope:f}=_me(c);if(this._resourceMetadataUrl=d,this._scope=f,await kO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new q3;return this.send(e)}let u=await c.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${c.status}): ${u}`)}}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}}});var pBe,Hjr=te(()=>{Lbt();pBe=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(s){o=cBe({onEvent:a=>{s.enqueue(a)},onError(a){e==="terminate"?s.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}});var zEo,qJ,BO,a4t=te(()=>{CO();fBe();Hjr();zEo={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},qJ=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},BO=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:zEo}async _authThenStart(){var e;if(!this._authProvider)throw new q3("No auth provider");let r;try{r=await kO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new q3;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(r.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let c=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!c.ok){if(c.status===401&&this._authProvider)return await this._authThenStart();if(c.status===405)return;throw new qJ(c.status,`Failed to open SSE stream: ${c.statusText}`)}this._handleSseStream(c.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var n;let o=this._reconnectionOptions.maxRetries;if(o>0&&r>=o){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r,a;(async()=>{var u,d,f,p;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new pBe).getReader();for(;;){let{value:m,done:g}=await h.read();if(g)break;if(m.id&&(a=m.id,o?.(m.id)),!m.event||m.event==="message")try{let A=bO.parse(JSON.parse(m.data));s!==void 0&&Che(A)&&(A.id=s),(u=this.onmessage)===null||u===void 0||u.call(this,A)}catch(A){(d=this.onerror)===null||d===void 0||d.call(this,A)}}}catch(h){if((f=this.onerror)===null||f===void 0||f.call(this,new Error(`SSE stream disconnected: ${h}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(m){(p=this.onerror)===null||p===void 0||p.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new q3("No auth provider");if(await kO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new q3("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,o,s,a;try{let{resumptionToken:c,onresumptiontoken:u}=r||{};if(c){this._startOrAuthSse({resumptionToken:c,replayMessageId:dke(e)?e.id:void 0}).catch(y=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,y)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},p=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,f),h=p.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!p.ok){if(p.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new qJ(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:v}=_me(p);if(this._resourceMetadataUrl=E,this._scope=v,await kO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new q3;return this._hasCompletedAuthFlow=!0,this.send(e)}let y=await p.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${p.status}): ${y}`)}if(this._hasCompletedAuthFlow=!1,p.status===202){LFr(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,y)});return}let g=(Array.isArray(e)?e:[e]).filter(y=>"method"in y&&"id"in y&&y.id!==void 0).length>0,A=p.headers.get("content-type");if(g)if(A?.includes("text/event-stream"))this._handleSseStream(p.body,{onresumptiontoken:u},!1);else if(A?.includes("application/json")){let y=await p.json(),E=Array.isArray(y)?y.map(v=>bO.parse(v)):[bO.parse(y)];for(let v of E)(s=this.onmessage)===null||s===void 0||s.call(this,v)}else throw new qJ(-1,`Unexpected content type: ${A}`)}catch(c){throw(a=this.onerror)===null||a===void 0||a.call(this,c),c}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!a.ok&&a.status!==405)throw new qJ(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}});import{readFile as YEo}from"node:fs/promises";var Eme,vme,cQ,c4t=te(()=>{"use strict";sue();fBe();_i();(function(t){t.CLI_CONNECT="cli_connect",t.PING="ping",t.GET_ACTIVE_FILE="get_active_file",t.GET_FILE_CONTENT="get_file_content",t.GET_SELECTED_TEXT="get_selected_text",t.SHOW_DIFF="show_diff"})(Eme||(Eme={}));vme=class extends Error{code;constructor(e,r){super(r),this.code=e}},cQ=class{_websocket;_url;_authProvider;_websocketOptions;_WebSocket;_protocolVersion;_isClosed=!1;_specialIds=new Set;onclose;onerror;onmessage;sessionId;constructor(e,r){this._url=e,this._authProvider=r?.authProvider,this._websocketOptions=r?.websocketOptions,this._WebSocket=r?.WebSocket||wF.default}async start(){if(this._isClosed)throw new Error(O.t("websocketClient.errors.transportClosed"));let e=null;if(this._authProvider)try{let o=await this._authProvider.tokens();o?.access_token&&(e=o.access_token)}catch(o){try{let s=await this._authProvider.clientInformation();if(s){let a=await this._authProvider.tokens();if(a?.refresh_token){let c=await o4t(this._url,{clientInformation:s,refreshToken:a.refresh_token,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(c),c?.access_token&&(e=c.access_token)}}}catch{if(this._authProvider.redirectToAuthorization){let s=this._authProvider.redirectUrl;throw await this._authProvider.redirectToAuthorization(typeof s=="string"?new URL(s):s),new Error(O.t("websocketClient.errors.unauthorizedOAuth"))}throw o}}let r={...this._websocketOptions?.headers};e&&(r.Authorization=`Bearer ${e}`),this._protocolVersion&&(r["MCP-Protocol-Version"]=this._protocolVersion);let n=new URL(this._url.toString());return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),new Promise((o,s)=>{try{let a={headers:r};this._websocket=new this._WebSocket(n.toString(),a),this._websocket.on("open",()=>{o()}),this._websocket.on("error",c=>{let u=c.code!==void 0?c.code:void 0;s(new vme(u,`WebSocket error: ${c.message}`))}),this._websocket.on("message",async c=>{try{let u=c.toString(),d=JSON.parse(u);if(this._specialIds.has(Number(d.id))||d.type==="welcome")return;this.onmessage?.(await this._transformResponse(d))}catch(u){this.onerror?.(new Error(`Failed to parse WebSocket message: ${u instanceof Error?u.message:String(u)}`))}}),this._websocket.on("close",()=>{this._isClosed||(this._isClosed=!0,this.onclose?.())})}catch(a){s(new vme(void 0,`Failed to create WebSocket: ${a}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error(O.t("websocketClient.errors.noAuthProvider"));try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),o=await i4t(this._url,{clientInformation:r,authorizationCode:e,codeVerifier:await this._authProvider.codeVerifier(),redirectUri:n,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(o)}else throw new Error(O.t("websocketClient.errors.clientInfoNotAvailable"))}catch(r){throw new Error(`Failed to exchange authorization code for access token: ${r}`)}}async close(){this._isClosed=!0,this._websocket&&this._websocket.readyState===wF.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error(O.t("websocketClient.errors.transportClosed"));if(!this._websocket)throw new Error(O.t("websocketClient.errors.transportNotStarted"));if(this._websocket.readyState!==wF.default.OPEN)throw new Error(O.t("websocketClient.errors.websocketNotOpen"));try{if(e.method==="notifications/initialized")return;let r=await this._transformRequest(e),n=JSON.stringify(r);this._websocket.send(n)}catch(r){throw new vme(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:Eme.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.4.2",platform:process.platform,workingDirectory:process.cwd()}}};if(e.method==="tools/call"&&e.params?.name==="openDiff"){let{arguments:r}=e.params||{},{filePath:n,newContent:o}=r||{};return{type:Eme.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{filePath:n,originalText:await YEo(n,"utf8"),modifiedText:o}}}return e}async _transformResponse(e){if(e.type==="connection_ack")return{jsonrpc:"2.0",id:e.id,result:{protocolVersion:"2024-11-05",capabilities:{logging:{},prompts:{},resources:{},tools:{}},serverInfo:{name:"JetBrains Plugin Server",title:"JetBrains Plugin Server",version:"1.0.0"}}};if(e.type==="selection_changed"){let r=await this._getSelectedText();return{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0,selectedText:r}]}}}}return e.type==="active_file_changed"?{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0}]}}}:e}async _getSelectedText(){if(!this._websocket)return"";let e=performance.now();return this._specialIds.add(e),this._websocket.send(JSON.stringify({type:Eme.GET_SELECTED_TEXT,id:e,timestamp:Date.now()})),new Promise((r,n)=>{this._websocket.once("message",o=>{try{let s=JSON.parse(o.toString());Number(s.id)===e&&(this._specialIds.delete(e),s.payload.success?r(s.payload.data.text):n(s.payload.error))}catch{r("")}})})}setProtocolVersion(e){this._protocolVersion=e}}});var Wjr=T((dHa,Vjr)=>{"use strict";Vjr.exports=function(e){return e.map(function(r){return r===""?"''":r&&typeof r=="object"?r.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(r)&&!/'/.test(r)?"'"+r.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(r)?'"'+r.replace(/(["\\$`!])/g,"\\$1")+'"':String(r).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var eGr=T((fHa,Zjr)=>{"use strict";var Jjr="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",zjr=new RegExp("^"+Jjr+"$"),Yjr="|&;()<> \\t",KEo='"((\\\\"|[^"])*?)"',XEo="'((\\\\'|[^'])*?)'",JEo=/^#$/,Kjr="'",Xjr='"',l4t="$",lQ="",ZEo=4294967296;for(u4t=0;u4t<4;u4t++)lQ+=(ZEo*Math.random()).toString(16);var u4t,e6o=new RegExp("^"+lQ);function t6o(t,e){for(var r=e.lastIndex,n=[],o;o=e.exec(t);)n.push(o),e.lastIndex===o.index&&(e.lastIndex+=1);return e.lastIndex=r,n}function r6o(t,e,r){var n=typeof t=="function"?t(r):t[r];return typeof n>"u"&&r!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?e+lQ+JSON.stringify(n)+lQ:e+n}function n6o(t,e,r){r||(r={});var n=r.escape||"\\",o="(\\"+n+`['"`+Yjr+`]|[^\\s'"`+Yjr+"])+",s=new RegExp(["("+Jjr+")","("+o+"|"+KEo+"|"+XEo+")+"].join("|"),"g"),a=t6o(t,s);if(a.length===0)return[];e||(e={});var c=!1;return a.map(function(u){var d=u[0];if(!d||c)return;if(zjr.test(d))return{op:d};var f=!1,p=!1,h="",m=!1,g;function A(){g+=1;var v,b,S=d.charAt(g);if(S==="{"){if(g+=1,d.charAt(g)==="}")throw new Error("Bad substitution: "+d.slice(g-2,g+1));if(v=d.indexOf("}",g),v<0)throw new Error("Bad substitution: "+d.slice(g));b=d.slice(g,v),g=v}else if(/[*@#?$!_-]/.test(S))b=S,g+=1;else{var w=d.slice(g);v=w.match(/[^\w\d_]/),v?(b=w.slice(0,v.index),g+=v.index-1):(b=w,g=d.length)}return r6o(e,"",b)}for(g=0;g<d.length;g++){var y=d.charAt(g);if(m=m||!f&&(y==="*"||y==="?"),p)h+=y,p=!1;else if(f)y===f?f=!1:f==Kjr?h+=y:y===n?(g+=1,y=d.charAt(g),y===Xjr||y===n||y===l4t?h+=y:h+=n+y):y===l4t?h+=A():h+=y;else if(y===Xjr||y===Kjr)f=y;else{if(zjr.test(y))return{op:d};if(JEo.test(y)){c=!0;var E={comment:t.slice(u.index+g+1)};return h.length?[h,E]:[E]}else y===n?p=!0:y===l4t?h+=A():h+=y}}return m?{op:"glob",pattern:h}:h}).reduce(function(u,d){return typeof d>"u"?u:u.concat(d)},[])}Zjr.exports=function(e,r,n){var o=n6o(e,r,n);return typeof r!="function"?o:o.reduce(function(s,a){if(typeof a=="object")return s.concat(a);var c=a.split(RegExp("("+lQ+".*?"+lQ+")","g"));return c.length===1?s.concat(c[0]):s.concat(c.filter(Boolean).map(function(u){return e6o.test(u)?JSON.parse(u.split(lQ)[1]):u}))},[])}});var bme=T(d4t=>{"use strict";d4t.quote=Wjr();d4t.parse=eGr()});var tGr,hBe,rGr=te(()=>{"use strict";tGr=Ie(V5e(),1);_i();hBe=class{config;auth;redirectUrl="";clientMetadata={client_name:"iFlow CLI (Google ADC)",redirect_uris:[],grant_types:[],response_types:[],token_endpoint_auth_method:"none"};_clientInformation;constructor(e){this.config=e;let r=this.config?.oauth?.scopes;if(!r||r.length===0)throw new Error(O.t("mcp.auth.scopesRequired"));this.auth=new tGr.GoogleAuth({scopes:r})}clientInformation(){return this._clientInformation}saveClientInformation(e){this._clientInformation=e}async tokens(){let r=await(await this.auth.getClient()).getAccessToken();if(!r.token){console.error(O.t("mcp.auth.failedToGetAccessToken"));return}return{access_token:r.token,token_type:"Bearer"}}saveTokens(e){}redirectToAuthorization(e){}saveCodeVerifier(e){}codeVerifier(){return""}}});import{execFile as i6o}from"node:child_process";import{promisify as o6o}from"node:util";import{platform as s6o}from"node:os";import{URL as a6o}from"node:url";function c6o(t){let e;try{e=new a6o(t)}catch{throw new Error(`Invalid URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsafe protocol: ${e.protocol}. Only HTTP and HTTPS are allowed.`);if(/[\r\n\x00-\x1f]/.test(t))throw new Error("URL contains invalid characters")}async function iGr(t){c6o(t);let e=s6o(),r,n;switch(e){case"darwin":r="open",n=[t];break;case"win32":r="powershell.exe",n=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":r="xdg-open",n=[t];break;default:throw new Error(`Unsupported platform: ${e}`)}let o={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await nGr(r,n,o)}catch(s){if((e==="linux"||e==="freebsd"||e==="openbsd")&&r==="xdg-open"){let a=["gnome-open","kde-open","firefox","chromium","google-chrome"];for(let c of a)try{await nGr(c,[t],o);return}catch{continue}}throw new Error(`Failed to open browser: ${s instanceof Error?s.message:"Unknown error"}`)}}var nGr,oGr=te(()=>{"use strict";nGr=o6o(i6o)});function ps(t){return t instanceof Error&&"code"in t}function _r(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"Failed to get error details"}}function f4t(t){if(t&&typeof t=="object"&&"response"in t){let r=l6o(t);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new gBe(r.error.message);case 401:return new PO(r.error.message);case 403:return new mBe(r.error.message);default:}}return t}function l6o(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var mBe,PO,gBe,Fd=te(()=>{"use strict";mBe=class extends Error{},PO=class extends Error{},gBe=class extends Error{}});import{promises as HJ}from"node:fs";import*as ABe from"node:path";import*as sGr from"node:os";var Xm,yBe=te(()=>{"use strict";Fd();_i();Xm=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=sGr.homedir();return ABe.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=ABe.dirname(this.getTokenFilePath());await HJ.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await HJ.readFile(r,"utf-8"),o=JSON.parse(n);for(let s of o)e.set(s.serverName,s)}catch(r){r.code!=="ENOENT"&&console.error(O.t("mcp.tokenStorage.errors.failedToLoadTokens",{error:_r(r)}))}return e}static async saveToken(e,r,n,o,s){await this.ensureConfigDir();let a=await this.loadTokens(),c={serverName:e,token:r,clientId:n,tokenUrl:o,mcpServerUrl:s,updatedAt:Date.now()};a.set(e,c);let u=Array.from(a.values()),d=this.getTokenFilePath();try{await HJ.writeFile(d,JSON.stringify(u,null,2),{mode:384})}catch(f){throw console.error(O.t("mcp.tokenStorage.errors.failedToSaveToken",{error:_r(f)})),f}}static async getToken(e){return(await this.loadTokens()).get(e)||null}static async removeToken(e){let r=await this.loadTokens();if(r.delete(e)){let n=Array.from(r.values()),o=this.getTokenFilePath();try{n.length===0?await HJ.unlink(o):await HJ.writeFile(o,JSON.stringify(n,null,2),{mode:384})}catch(s){console.error(O.t("mcp.tokenStorage.errors.failedToRemoveToken",{error:_r(s)}))}}}static isTokenExpired(e){if(!e.expiresAt)return!1;let r=300*1e3;return Date.now()+r>=e.expiresAt}static async clearAllTokens(){try{let e=this.getTokenFilePath();await HJ.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(O.t("mcp.tokenStorage.errors.failedToClearTokens",{error:_r(e)}))}}}});var Jm,_Be=te(()=>{"use strict";Fd();_i();Jm=class{static buildWellKnownUrls(e){let r=new URL(e),n=`${r.protocol}//${r.host}`;return{protectedResource:new URL("/.well-known/oauth-protected-resource",n).toString(),authorizationServer:new URL("/.well-known/oauth-authorization-server",n).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch protected resource metadata from ${e}: ${_r(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch authorization server metadata from ${e}: ${_r(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[]}}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(n?.authorization_servers?.length){let s=n.authorization_servers[0],a=new URL("/.well-known/oauth-authorization-server",s).toString(),c=await this.fetchAuthorizationServerMetadata(a);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&console.log(O.t("mcp.oauth.discovery.dynamicRegistrationSupported"),c.registration_endpoint),u}}console.debug(`Trying OAuth discovery fallback at ${r.authorizationServer}`);let o=await this.fetchAuthorizationServerMetadata(r.authorizationServer);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&console.log(O.t("mcp.oauth.discovery.dynamicRegistrationSupported"),o.registration_endpoint),s}return null}catch(r){return console.debug(`Failed to discover OAuth configuration: ${_r(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e){let r=this.parseWWWAuthenticateHeader(e);if(!r)return null;console.log(O.t("mcp.oauth.discovery.foundResourceMetadataUri",{uri:r}));let n=await this.fetchProtectedResourceMetadata(r);if(!n?.authorization_servers?.length)return null;let o=n.authorization_servers[0],s=new URL("/.well-known/oauth-authorization-server",o).toString(),a=await this.fetchAuthorizationServerMetadata(s);return a?(console.log(O.t("mcp.oauth.discovery.configDiscoveredFromWwwAuth")),this.metadataToOAuthConfig(a)):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}`}}});import*as aGr from"node:http";import*as Cme from"node:crypto";import{URL as p4t}from"node:url";var B_,h4t=te(()=>{"use strict";oGr();yBe();Fd();_Be();_i();B_=class{static REDIRECT_PORT=7777;static REDIRECT_PATH="/oauth/callback";static HTTP_OK=200;static HTTP_REDIRECT=302;static async registerClient(e,r){let o={client_name:"iFlow CLI MCP Client",redirect_uris:[r.redirectUri||`http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",code_challenge_method:["S256"],scope:r.scopes?.join(" ")||""},s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let a=await s.text();throw new Error(O.t("mcp.auth.clientRegistrationFailed",{status:s.status,statusText:s.statusText,error:a}))}return await s.json()}static async discoverOAuthFromMCPServer(e){let r=Jm.extractBaseUrl(e);return Jm.discoverOAuthConfig(r)}static generatePKCEParams(){let e=Cme.randomBytes(32).toString("base64url"),r=Cme.createHash("sha256").update(e).digest("base64url"),n=Cme.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let o=aGr.createServer(async(s,a)=>{try{let c=new p4t(s.url,`http://localhost:${this.REDIRECT_PORT}`);if(c.pathname!==this.REDIRECT_PATH){a.writeHead(404),a.end(O.t("mcp.ui.notFound"));return}let u=c.searchParams.get("code"),d=c.searchParams.get("state"),f=c.searchParams.get("error");if(f){a.writeHead(this.HTTP_OK,{"Content-Type":"text/html"}),a.end(`
|
|
962
|
+
`&&n++}}return[e,r]}var aBe,Lbt=te(()=>{aBe=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function wEo(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Ubt(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Ubt).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Ubt(t.cause)}`:t.message:`${t}`}function wjr(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function TEo(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var uBe,Ijr,Wbt,na,Wh,Md,l7,$3,nQ,LJ,lBe,dBe,ome,jJ,sme,OO,UJ,GJ,QJ,nme,BC,Qbt,jbt,Gbt,Tjr,$bt,qbt,ime,Hbt,Vbt,iQ,Djr=te(()=>{Lbt();uBe=class extends Event{constructor(e,r){var n,o;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(wjr(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(wjr(this),r)}};Ijr=t=>{throw TypeError(t)},Wbt=(t,e,r)=>e.has(t)||Ijr("Cannot "+r),na=(t,e,r)=>(Wbt(t,e,"read from private field"),r?r.call(t):e.get(t)),Wh=(t,e,r)=>e.has(t)?Ijr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Md=(t,e,r,n)=>(Wbt(t,e,"write to private field"),e.set(t,r),r),l7=(t,e,r)=>(Wbt(t,e,"access private method"),r),iQ=class extends EventTarget{constructor(e,r){var n,o;super(),Wh(this,BC),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Wh(this,$3),Wh(this,nQ),Wh(this,LJ),Wh(this,lBe),Wh(this,dBe),Wh(this,ome),Wh(this,jJ),Wh(this,sme,null),Wh(this,OO),Wh(this,UJ),Wh(this,GJ,null),Wh(this,QJ,null),Wh(this,nme,null),Wh(this,jbt,async s=>{var a;na(this,UJ).reset();let{body:c,redirected:u,status:d,headers:f}=s;if(d===204){l7(this,BC,ime).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Md(this,LJ,new URL(s.url)):Md(this,LJ,void 0),d!==200){l7(this,BC,ime).call(this,`Non-200 status code (${d})`,d);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){l7(this,BC,ime).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(na(this,$3)===this.CLOSED)return;Md(this,$3,this.OPEN);let p=new Event("open");if((a=na(this,nme))==null||a.call(this,p),this.dispatchEvent(p),typeof c!="object"||!c||!("getReader"in c)){l7(this,BC,ime).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}let h=new TextDecoder,m=c.getReader(),g=!0;do{let{done:A,value:y}=await m.read();y&&na(this,UJ).feed(h.decode(y,{stream:!A})),A&&(g=!1,na(this,UJ).reset(),l7(this,BC,Hbt).call(this))}while(g)}),Wh(this,Gbt,s=>{Md(this,OO,void 0),!(s.name==="AbortError"||s.type==="aborted")&&l7(this,BC,Hbt).call(this,Ubt(s))}),Wh(this,$bt,s=>{typeof s.id=="string"&&Md(this,sme,s.id);let a=new MessageEvent(s.event||"message",{data:s.data,origin:na(this,LJ)?na(this,LJ).origin:na(this,nQ).origin,lastEventId:s.id||""});na(this,QJ)&&(!s.event||s.event==="message")&&na(this,QJ).call(this,a),this.dispatchEvent(a)}),Wh(this,qbt,s=>{Md(this,ome,s)}),Wh(this,Vbt,()=>{Md(this,jJ,void 0),na(this,$3)===this.CONNECTING&&l7(this,BC,Qbt).call(this)});try{if(e instanceof URL)Md(this,nQ,e);else if(typeof e=="string")Md(this,nQ,new URL(e,TEo()));else throw new Error("Invalid URL")}catch{throw wEo("An invalid or illegal string was specified")}Md(this,UJ,cBe({onEvent:na(this,$bt),onRetry:na(this,qbt)})),Md(this,$3,this.CONNECTING),Md(this,ome,3e3),Md(this,dBe,(n=r?.fetch)!=null?n:globalThis.fetch),Md(this,lBe,(o=r?.withCredentials)!=null?o:!1),l7(this,BC,Qbt).call(this)}get readyState(){return na(this,$3)}get url(){return na(this,nQ).href}get withCredentials(){return na(this,lBe)}get onerror(){return na(this,GJ)}set onerror(e){Md(this,GJ,e)}get onmessage(){return na(this,QJ)}set onmessage(e){Md(this,QJ,e)}get onopen(){return na(this,nme)}set onopen(e){Md(this,nme,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){na(this,jJ)&&clearTimeout(na(this,jJ)),na(this,$3)!==this.CLOSED&&(na(this,OO)&&na(this,OO).abort(),Md(this,$3,this.CLOSED),Md(this,OO,void 0))}};$3=new WeakMap,nQ=new WeakMap,LJ=new WeakMap,lBe=new WeakMap,dBe=new WeakMap,ome=new WeakMap,jJ=new WeakMap,sme=new WeakMap,OO=new WeakMap,UJ=new WeakMap,GJ=new WeakMap,QJ=new WeakMap,nme=new WeakMap,BC=new WeakSet,Qbt=function(){Md(this,$3,this.CONNECTING),Md(this,OO,new AbortController),na(this,dBe)(na(this,nQ),l7(this,BC,Tjr).call(this)).then(na(this,jbt)).catch(na(this,Gbt))},jbt=new WeakMap,Gbt=new WeakMap,Tjr=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...na(this,sme)?{"Last-Event-ID":na(this,sme)}:void 0},cache:"no-store",signal:(t=na(this,OO))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},$bt=new WeakMap,qbt=new WeakMap,ime=function(t,e){var r;na(this,$3)!==this.CLOSED&&Md(this,$3,this.CLOSED);let n=new uBe("error",{code:e,message:t});(r=na(this,GJ))==null||r.call(this,n),this.dispatchEvent(n)},Hbt=function(t,e){var r;if(na(this,$3)===this.CLOSED)return;Md(this,$3,this.CONNECTING);let n=new uBe("error",{code:e,message:t});(r=na(this,GJ))==null||r.call(this,n),this.dispatchEvent(n),Md(this,jJ,setTimeout(na(this,Vbt),na(this,ome)))},Vbt=new WeakMap,iQ.CONNECTING=0,iQ.OPEN=1,iQ.CLOSED=2});async function IEo(t){return(await zbt).getRandomValues(new Uint8Array(t))}async function DEo(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await IEo(t);for(let o=0;o<t;o++){let s=n[o]%e.length;r+=e[s]}return r}async function REo(t){return await DEo(t)}async function NEo(t){let e=await(await zbt).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Ybt(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await REo(t),r=await NEo(e);return{code_verifier:e,code_challenge:r}}var zbt,Rjr=te(()=>{zbt=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var f0,Ojr,Kbt,OEo,kjr,Xbt,Bjr,Njr,kEo,BEo,Pjr,Lqa,Uqa,Jbt=te(()=>{vO();f0=se.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:se.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),se.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ojr=se.object({resource:se.string().url(),authorization_servers:se.array(f0).optional(),jwks_uri:se.string().url().optional(),scopes_supported:se.array(se.string()).optional(),bearer_methods_supported:se.array(se.string()).optional(),resource_signing_alg_values_supported:se.array(se.string()).optional(),resource_name:se.string().optional(),resource_documentation:se.string().optional(),resource_policy_uri:se.string().url().optional(),resource_tos_uri:se.string().url().optional(),tls_client_certificate_bound_access_tokens:se.boolean().optional(),authorization_details_types_supported:se.array(se.string()).optional(),dpop_signing_alg_values_supported:se.array(se.string()).optional(),dpop_bound_access_tokens_required:se.boolean().optional()}).passthrough(),Kbt=se.object({issuer:se.string(),authorization_endpoint:f0,token_endpoint:f0,registration_endpoint:f0.optional(),scopes_supported:se.array(se.string()).optional(),response_types_supported:se.array(se.string()),response_modes_supported:se.array(se.string()).optional(),grant_types_supported:se.array(se.string()).optional(),token_endpoint_auth_methods_supported:se.array(se.string()).optional(),token_endpoint_auth_signing_alg_values_supported:se.array(se.string()).optional(),service_documentation:f0.optional(),revocation_endpoint:f0.optional(),revocation_endpoint_auth_methods_supported:se.array(se.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:se.array(se.string()).optional(),introspection_endpoint:se.string().optional(),introspection_endpoint_auth_methods_supported:se.array(se.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:se.array(se.string()).optional(),code_challenge_methods_supported:se.array(se.string()).optional()}).passthrough(),OEo=se.object({issuer:se.string(),authorization_endpoint:f0,token_endpoint:f0,userinfo_endpoint:f0.optional(),jwks_uri:f0,registration_endpoint:f0.optional(),scopes_supported:se.array(se.string()).optional(),response_types_supported:se.array(se.string()),response_modes_supported:se.array(se.string()).optional(),grant_types_supported:se.array(se.string()).optional(),acr_values_supported:se.array(se.string()).optional(),subject_types_supported:se.array(se.string()),id_token_signing_alg_values_supported:se.array(se.string()),id_token_encryption_alg_values_supported:se.array(se.string()).optional(),id_token_encryption_enc_values_supported:se.array(se.string()).optional(),userinfo_signing_alg_values_supported:se.array(se.string()).optional(),userinfo_encryption_alg_values_supported:se.array(se.string()).optional(),userinfo_encryption_enc_values_supported:se.array(se.string()).optional(),request_object_signing_alg_values_supported:se.array(se.string()).optional(),request_object_encryption_alg_values_supported:se.array(se.string()).optional(),request_object_encryption_enc_values_supported:se.array(se.string()).optional(),token_endpoint_auth_methods_supported:se.array(se.string()).optional(),token_endpoint_auth_signing_alg_values_supported:se.array(se.string()).optional(),display_values_supported:se.array(se.string()).optional(),claim_types_supported:se.array(se.string()).optional(),claims_supported:se.array(se.string()).optional(),service_documentation:se.string().optional(),claims_locales_supported:se.array(se.string()).optional(),ui_locales_supported:se.array(se.string()).optional(),claims_parameter_supported:se.boolean().optional(),request_parameter_supported:se.boolean().optional(),request_uri_parameter_supported:se.boolean().optional(),require_request_uri_registration:se.boolean().optional(),op_policy_uri:f0.optional(),op_tos_uri:f0.optional()}).passthrough(),kjr=OEo.merge(Kbt.pick({code_challenge_methods_supported:!0})),Xbt=se.object({access_token:se.string(),id_token:se.string().optional(),token_type:se.string(),expires_in:se.number().optional(),scope:se.string().optional(),refresh_token:se.string().optional()}).strip(),Bjr=se.object({error:se.string(),error_description:se.string().optional(),error_uri:se.string().optional()}),Njr=f0.optional().or(se.literal("").transform(()=>{})),kEo=se.object({redirect_uris:se.array(f0),token_endpoint_auth_method:se.string().optional(),grant_types:se.array(se.string()).optional(),response_types:se.array(se.string()).optional(),client_name:se.string().optional(),client_uri:f0.optional(),logo_uri:Njr,scope:se.string().optional(),contacts:se.array(se.string()).optional(),tos_uri:Njr,policy_uri:se.string().optional(),jwks_uri:f0.optional(),jwks:se.any().optional(),software_id:se.string().optional(),software_version:se.string().optional(),software_statement:se.string().optional()}).strip(),BEo=se.object({client_id:se.string(),client_secret:se.string().optional(),client_id_issued_at:se.number().optional(),client_secret_expires_at:se.number().optional()}).strip(),Pjr=kEo.merge(BEo),Lqa=se.object({error:se.string(),error_description:se.string().optional()}).strip(),Uqa=se.object({token:se.string(),token_type_hint:se.string().optional()}).strip()});function Mjr(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Fjr({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var Ljr=te(()=>{});var dh,ame,oQ,sQ,aQ,cme,lme,ume,u7,dme,fme,pme,hme,mme,gme,Ame,yme,Ujr,Qjr=te(()=>{dh=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},ame=class extends dh{};ame.errorCode="invalid_request";oQ=class extends dh{};oQ.errorCode="invalid_client";sQ=class extends dh{};sQ.errorCode="invalid_grant";aQ=class extends dh{};aQ.errorCode="unauthorized_client";cme=class extends dh{};cme.errorCode="unsupported_grant_type";lme=class extends dh{};lme.errorCode="invalid_scope";ume=class extends dh{};ume.errorCode="access_denied";u7=class extends dh{};u7.errorCode="server_error";dme=class extends dh{};dme.errorCode="temporarily_unavailable";fme=class extends dh{};fme.errorCode="unsupported_response_type";pme=class extends dh{};pme.errorCode="unsupported_token_type";hme=class extends dh{};hme.errorCode="invalid_token";mme=class extends dh{};mme.errorCode="method_not_allowed";gme=class extends dh{};gme.errorCode="too_many_requests";Ame=class extends dh{};Ame.errorCode="invalid_client_metadata";yme=class extends dh{};yme.errorCode="insufficient_scope";Ujr={[ame.errorCode]:ame,[oQ.errorCode]:oQ,[sQ.errorCode]:sQ,[aQ.errorCode]:aQ,[cme.errorCode]:cme,[lme.errorCode]:lme,[ume.errorCode]:ume,[u7.errorCode]:u7,[dme.errorCode]:dme,[fme.errorCode]:fme,[pme.errorCode]:pme,[hme.errorCode]:hme,[mme.errorCode]:mme,[gme.errorCode]:gme,[Ame.errorCode]:Ame,[yme.errorCode]:yme}});function PEo(t){return["client_secret_basic","client_secret_post","none"].includes(t)}function Gjr(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&PEo(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function $jr(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":MEo(o,s,r);return;case"client_secret_post":FEo(o,s,n);return;case"none":LEo(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function MEo(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function FEo(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function LEo(t,e){e.set("client_id",t)}async function r4t(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=Bjr.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,c=Ujr[o]||u7;return new c(s||"",a)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new u7(o)}}async function kO(t,e){var r,n;try{return await t4t(t,e)}catch(o){if(o instanceof oQ||o instanceof aQ)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await t4t(t,e);if(o instanceof sQ)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await t4t(t,e);throw o}}async function t4t(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,c;try{a=await QEo(e,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(c=a.authorization_servers[0])}catch{}c||(c=e);let u=await UEo(e,t,a),d=await HEo(c,{fetchFn:s}),f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let A=await WEo(c,{metadata:d,clientMetadata:t.clientMetadata,fetchFn:s});await t.saveClientInformation(A),f=A}if(r!==void 0){let A=await t.codeVerifier(),y=await i4t(c,{metadata:d,clientInformation:f,authorizationCode:r,codeVerifier:A,redirectUri:t.redirectUrl,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(y),"AUTHORIZED"}let p=await t.tokens();if(p?.refresh_token)try{let A=await o4t(c,{metadata:d,clientInformation:f,refreshToken:p.refresh_token,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(A),"AUTHORIZED"}catch(A){if(!(!(A instanceof dh)||A instanceof u7))throw A}let h=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:g}=await VEo(c,{metadata:d,clientInformation:f,state:h,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:u});return await t.saveCodeVerifier(g),await t.redirectToAuthorization(m),"REDIRECT"}async function UEo(t,e,r){let n=Mjr(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Fjr({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function _me(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let s=/resource_metadata="([^"]*)"/.exec(e),c=/scope="([^"]*)"/.exec(e),u;if(s)try{u=new URL(s[1])}catch{}let d=c?.[1]||void 0;return{resourceMetadataUrl:u,scope:d}}async function QEo(t,e,r=fetch){let n=await $Eo(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Ojr.parse(await n.json())}async function n4t(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?n4t(t,void 0,r):void 0;throw n}}function jEo(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function jjr(t,e,r=fetch){return await n4t(t,{"MCP-Protocol-Version":e},r)}function GEo(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function $Eo(t,e,r,n){var o,s;let a=new URL(t),c=(o=n?.protocolVersion)!==null&&o!==void 0?o:AJ,u;if(n?.metadataUrl)u=new URL(n.metadataUrl);else{let f=jEo(e,a.pathname);u=new URL(f,(s=n?.metadataServerUrl)!==null&&s!==void 0?s:a),u.search=a.search}let d=await jjr(u,c,r);if(!n?.metadataUrl&&GEo(d,a.pathname)){let f=new URL(`/.well-known/${e}`,a);d=await jjr(f,c,r)}return d}function qEo(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function HEo(t,{fetchFn:e=fetch,protocolVersion:r=AJ}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=qEo(t);for(let{url:s,type:a}of o){let c=await n4t(s,n,e);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?Kbt.parse(await c.json()):kjr.parse(await c.json())}}}async function VEo(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let c;if(e){if(c=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Zbt))throw new Error(`Incompatible auth server: does not support response type ${Zbt}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(e4t))throw new Error(`Incompatible auth server: does not support code challenge method ${e4t}`)}else c=new URL("/authorize",t);let u=await Ybt(),d=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",Zbt),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",e4t),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:d}}async function i4t(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:c,fetchFn:u}){var d;let f="authorization_code",p=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(f))throw new Error(`Incompatible auth server: does not support grant type ${f}`);let h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),m=new URLSearchParams({grant_type:f,code:n,code_verifier:o,redirect_uri:String(s)});if(c)c(h,m,t,e);else{let A=(d=e?.token_endpoint_auth_methods_supported)!==null&&d!==void 0?d:[],y=Gjr(r,A);$jr(y,r,h,m)}a&&m.set("resource",a.href);let g=await(u??fetch)(p,{method:"POST",headers:h,body:m});if(!g.ok)throw await r4t(g);return Xbt.parse(await g.json())}async function o4t(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var c;let u="refresh_token",d;if(e){if(d=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`)}else d=new URL("/token",t);let f=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),p=new URLSearchParams({grant_type:u,refresh_token:n});if(s)s(f,p,t,e);else{let m=(c=e?.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],g=Gjr(r,m);$jr(g,r,f,p)}o&&p.set("resource",o.href);let h=await(a??fetch)(d,{method:"POST",headers:f,body:p});if(!h.ok)throw await r4t(h);return Xbt.parse({refresh_token:n,...await h.json()})}async function WEo(t,{metadata:e,clientMetadata:r,fetchFn:n}){let o;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(e.registration_endpoint)}else o=new URL("/register",t);let s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await r4t(s);return Pjr.parse(await s.json())}var q3,Zbt,e4t,fBe=te(()=>{Rjr();CO();Jbt();Jbt();Ljr();Qjr();q3=class extends Error{constructor(e){super(e??"Unauthorized")}};Zbt="code",e4t="S256"});var s4t,$J,qjr=te(()=>{Djr();CO();fBe();s4t=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},$J=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new q3("No auth provider");let r;try{r=await kO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new q3;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,n;let o=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((s,a)=>{this._eventSource=new iQ(this._url.href,{...this._eventSourceInit,fetch:async(c,u)=>{let d=await this._commonHeaders();d.set("Accept","text/event-stream");let f=await o(c,{...u,headers:d});if(f.status===401&&f.headers.has("www-authenticate")){let{resourceMetadataUrl:p,scope:h}=_me(f);this._resourceMetadataUrl=p,this._scope=h}return f}}),this._abortController=new AbortController,this._eventSource.onerror=c=>{var u;if(c.code===401&&this._authProvider){this._authThenStart().then(s,a);return}let d=new s4t(c.code,c.message,c);a(d),(u=this.onerror)===null||u===void 0||u.call(this,d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",c=>{var u;let d=c;try{if(this._endpoint=new URL(d.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(f){a(f),(u=this.onerror)===null||u===void 0||u.call(this,f),this.close();return}s()}),this._eventSource.onmessage=c=>{var u,d;let f=c,p;try{p=bO.parse(JSON.parse(f.data))}catch(h){(u=this.onerror)===null||u===void 0||u.call(this,h);return}(d=this.onmessage)===null||d===void 0||d.call(this,p)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new q3("No auth provider");if(await kO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new q3("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},c=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!c.ok){if(c.status===401&&this._authProvider){let{resourceMetadataUrl:d,scope:f}=_me(c);if(this._resourceMetadataUrl=d,this._scope=f,await kO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new q3;return this.send(e)}let u=await c.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${c.status}): ${u}`)}}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}}});var pBe,Hjr=te(()=>{Lbt();pBe=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(s){o=cBe({onEvent:a=>{s.enqueue(a)},onError(a){e==="terminate"?s.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}});var zEo,qJ,BO,a4t=te(()=>{CO();fBe();Hjr();zEo={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},qJ=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},BO=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:zEo}async _authThenStart(){var e;if(!this._authProvider)throw new q3("No auth provider");let r;try{r=await kO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new q3;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(r.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let c=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!c.ok){if(c.status===401&&this._authProvider)return await this._authThenStart();if(c.status===405)return;throw new qJ(c.status,`Failed to open SSE stream: ${c.statusText}`)}this._handleSseStream(c.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(e){let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var n;let o=this._reconnectionOptions.maxRetries;if(o>0&&r>=o){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r,a;(async()=>{var u,d,f,p;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new pBe).getReader();for(;;){let{value:m,done:g}=await h.read();if(g)break;if(m.id&&(a=m.id,o?.(m.id)),!m.event||m.event==="message")try{let A=bO.parse(JSON.parse(m.data));s!==void 0&&Che(A)&&(A.id=s),(u=this.onmessage)===null||u===void 0||u.call(this,A)}catch(A){(d=this.onerror)===null||d===void 0||d.call(this,A)}}}catch(h){if((f=this.onerror)===null||f===void 0||f.call(this,new Error(`SSE stream disconnected: ${h}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(m){(p=this.onerror)===null||p===void 0||p.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new q3("No auth provider");if(await kO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new q3("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,o,s,a;try{let{resumptionToken:c,onresumptiontoken:u}=r||{};if(c){this._startOrAuthSse({resumptionToken:c,replayMessageId:dke(e)?e.id:void 0}).catch(y=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,y)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},p=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,f),h=p.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!p.ok){if(p.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new qJ(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:v}=_me(p);if(this._resourceMetadataUrl=E,this._scope=v,await kO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new q3;return this._hasCompletedAuthFlow=!0,this.send(e)}let y=await p.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${p.status}): ${y}`)}if(this._hasCompletedAuthFlow=!1,p.status===202){LFr(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,y)});return}let g=(Array.isArray(e)?e:[e]).filter(y=>"method"in y&&"id"in y&&y.id!==void 0).length>0,A=p.headers.get("content-type");if(g)if(A?.includes("text/event-stream"))this._handleSseStream(p.body,{onresumptiontoken:u},!1);else if(A?.includes("application/json")){let y=await p.json(),E=Array.isArray(y)?y.map(v=>bO.parse(v)):[bO.parse(y)];for(let v of E)(s=this.onmessage)===null||s===void 0||s.call(this,v)}else throw new qJ(-1,`Unexpected content type: ${A}`)}catch(c){throw(a=this.onerror)===null||a===void 0||a.call(this,c),c}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!a.ok&&a.status!==405)throw new qJ(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}});import{readFile as YEo}from"node:fs/promises";var Eme,vme,cQ,c4t=te(()=>{"use strict";sue();fBe();_i();(function(t){t.CLI_CONNECT="cli_connect",t.PING="ping",t.GET_ACTIVE_FILE="get_active_file",t.GET_FILE_CONTENT="get_file_content",t.GET_SELECTED_TEXT="get_selected_text",t.SHOW_DIFF="show_diff"})(Eme||(Eme={}));vme=class extends Error{code;constructor(e,r){super(r),this.code=e}},cQ=class{_websocket;_url;_authProvider;_websocketOptions;_WebSocket;_protocolVersion;_isClosed=!1;_specialIds=new Set;onclose;onerror;onmessage;sessionId;constructor(e,r){this._url=e,this._authProvider=r?.authProvider,this._websocketOptions=r?.websocketOptions,this._WebSocket=r?.WebSocket||wF.default}async start(){if(this._isClosed)throw new Error(O.t("websocketClient.errors.transportClosed"));let e=null;if(this._authProvider)try{let o=await this._authProvider.tokens();o?.access_token&&(e=o.access_token)}catch(o){try{let s=await this._authProvider.clientInformation();if(s){let a=await this._authProvider.tokens();if(a?.refresh_token){let c=await o4t(this._url,{clientInformation:s,refreshToken:a.refresh_token,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(c),c?.access_token&&(e=c.access_token)}}}catch{if(this._authProvider.redirectToAuthorization){let s=this._authProvider.redirectUrl;throw await this._authProvider.redirectToAuthorization(typeof s=="string"?new URL(s):s),new Error(O.t("websocketClient.errors.unauthorizedOAuth"))}throw o}}let r={...this._websocketOptions?.headers};e&&(r.Authorization=`Bearer ${e}`),this._protocolVersion&&(r["MCP-Protocol-Version"]=this._protocolVersion);let n=new URL(this._url.toString());return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),new Promise((o,s)=>{try{let a={headers:r};this._websocket=new this._WebSocket(n.toString(),a),this._websocket.on("open",()=>{o()}),this._websocket.on("error",c=>{let u=c.code!==void 0?c.code:void 0;s(new vme(u,`WebSocket error: ${c.message}`))}),this._websocket.on("message",async c=>{try{let u=c.toString(),d=JSON.parse(u);if(this._specialIds.has(Number(d.id))||d.type==="welcome")return;this.onmessage?.(await this._transformResponse(d))}catch(u){this.onerror?.(new Error(`Failed to parse WebSocket message: ${u instanceof Error?u.message:String(u)}`))}}),this._websocket.on("close",()=>{this._isClosed||(this._isClosed=!0,this.onclose?.())})}catch(a){s(new vme(void 0,`Failed to create WebSocket: ${a}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error(O.t("websocketClient.errors.noAuthProvider"));try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),o=await i4t(this._url,{clientInformation:r,authorizationCode:e,codeVerifier:await this._authProvider.codeVerifier(),redirectUri:n,addClientAuthentication:this._authProvider.addClientAuthentication});await this._authProvider.saveTokens(o)}else throw new Error(O.t("websocketClient.errors.clientInfoNotAvailable"))}catch(r){throw new Error(`Failed to exchange authorization code for access token: ${r}`)}}async close(){this._isClosed=!0,this._websocket&&this._websocket.readyState===wF.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error(O.t("websocketClient.errors.transportClosed"));if(!this._websocket)throw new Error(O.t("websocketClient.errors.transportNotStarted"));if(this._websocket.readyState!==wF.default.OPEN)throw new Error(O.t("websocketClient.errors.websocketNotOpen"));try{if(e.method==="notifications/initialized")return;let r=await this._transformRequest(e),n=JSON.stringify(r);this._websocket.send(n)}catch(r){throw new vme(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:Eme.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.4.3",platform:process.platform,workingDirectory:process.cwd()}}};if(e.method==="tools/call"&&e.params?.name==="openDiff"){let{arguments:r}=e.params||{},{filePath:n,newContent:o}=r||{};return{type:Eme.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{filePath:n,originalText:await YEo(n,"utf8"),modifiedText:o}}}return e}async _transformResponse(e){if(e.type==="connection_ack")return{jsonrpc:"2.0",id:e.id,result:{protocolVersion:"2024-11-05",capabilities:{logging:{},prompts:{},resources:{},tools:{}},serverInfo:{name:"JetBrains Plugin Server",title:"JetBrains Plugin Server",version:"1.0.0"}}};if(e.type==="selection_changed"){let r=await this._getSelectedText();return{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0,selectedText:r}]}}}}return e.type==="active_file_changed"?{jsonrpc:"2.0",method:"ide/contextUpdate",params:{workspaceState:{openFiles:[{path:e.payload.fileName,timestamp:Date.now(),isActive:!0}]}}}:e}async _getSelectedText(){if(!this._websocket)return"";let e=performance.now();return this._specialIds.add(e),this._websocket.send(JSON.stringify({type:Eme.GET_SELECTED_TEXT,id:e,timestamp:Date.now()})),new Promise((r,n)=>{this._websocket.once("message",o=>{try{let s=JSON.parse(o.toString());Number(s.id)===e&&(this._specialIds.delete(e),s.payload.success?r(s.payload.data.text):n(s.payload.error))}catch{r("")}})})}setProtocolVersion(e){this._protocolVersion=e}}});var Wjr=T((dHa,Vjr)=>{"use strict";Vjr.exports=function(e){return e.map(function(r){return r===""?"''":r&&typeof r=="object"?r.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(r)&&!/'/.test(r)?"'"+r.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(r)?'"'+r.replace(/(["\\$`!])/g,"\\$1")+'"':String(r).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var eGr=T((fHa,Zjr)=>{"use strict";var Jjr="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",zjr=new RegExp("^"+Jjr+"$"),Yjr="|&;()<> \\t",KEo='"((\\\\"|[^"])*?)"',XEo="'((\\\\'|[^'])*?)'",JEo=/^#$/,Kjr="'",Xjr='"',l4t="$",lQ="",ZEo=4294967296;for(u4t=0;u4t<4;u4t++)lQ+=(ZEo*Math.random()).toString(16);var u4t,e6o=new RegExp("^"+lQ);function t6o(t,e){for(var r=e.lastIndex,n=[],o;o=e.exec(t);)n.push(o),e.lastIndex===o.index&&(e.lastIndex+=1);return e.lastIndex=r,n}function r6o(t,e,r){var n=typeof t=="function"?t(r):t[r];return typeof n>"u"&&r!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?e+lQ+JSON.stringify(n)+lQ:e+n}function n6o(t,e,r){r||(r={});var n=r.escape||"\\",o="(\\"+n+`['"`+Yjr+`]|[^\\s'"`+Yjr+"])+",s=new RegExp(["("+Jjr+")","("+o+"|"+KEo+"|"+XEo+")+"].join("|"),"g"),a=t6o(t,s);if(a.length===0)return[];e||(e={});var c=!1;return a.map(function(u){var d=u[0];if(!d||c)return;if(zjr.test(d))return{op:d};var f=!1,p=!1,h="",m=!1,g;function A(){g+=1;var v,b,S=d.charAt(g);if(S==="{"){if(g+=1,d.charAt(g)==="}")throw new Error("Bad substitution: "+d.slice(g-2,g+1));if(v=d.indexOf("}",g),v<0)throw new Error("Bad substitution: "+d.slice(g));b=d.slice(g,v),g=v}else if(/[*@#?$!_-]/.test(S))b=S,g+=1;else{var w=d.slice(g);v=w.match(/[^\w\d_]/),v?(b=w.slice(0,v.index),g+=v.index-1):(b=w,g=d.length)}return r6o(e,"",b)}for(g=0;g<d.length;g++){var y=d.charAt(g);if(m=m||!f&&(y==="*"||y==="?"),p)h+=y,p=!1;else if(f)y===f?f=!1:f==Kjr?h+=y:y===n?(g+=1,y=d.charAt(g),y===Xjr||y===n||y===l4t?h+=y:h+=n+y):y===l4t?h+=A():h+=y;else if(y===Xjr||y===Kjr)f=y;else{if(zjr.test(y))return{op:d};if(JEo.test(y)){c=!0;var E={comment:t.slice(u.index+g+1)};return h.length?[h,E]:[E]}else y===n?p=!0:y===l4t?h+=A():h+=y}}return m?{op:"glob",pattern:h}:h}).reduce(function(u,d){return typeof d>"u"?u:u.concat(d)},[])}Zjr.exports=function(e,r,n){var o=n6o(e,r,n);return typeof r!="function"?o:o.reduce(function(s,a){if(typeof a=="object")return s.concat(a);var c=a.split(RegExp("("+lQ+".*?"+lQ+")","g"));return c.length===1?s.concat(c[0]):s.concat(c.filter(Boolean).map(function(u){return e6o.test(u)?JSON.parse(u.split(lQ)[1]):u}))},[])}});var bme=T(d4t=>{"use strict";d4t.quote=Wjr();d4t.parse=eGr()});var tGr,hBe,rGr=te(()=>{"use strict";tGr=Ie(V5e(),1);_i();hBe=class{config;auth;redirectUrl="";clientMetadata={client_name:"iFlow CLI (Google ADC)",redirect_uris:[],grant_types:[],response_types:[],token_endpoint_auth_method:"none"};_clientInformation;constructor(e){this.config=e;let r=this.config?.oauth?.scopes;if(!r||r.length===0)throw new Error(O.t("mcp.auth.scopesRequired"));this.auth=new tGr.GoogleAuth({scopes:r})}clientInformation(){return this._clientInformation}saveClientInformation(e){this._clientInformation=e}async tokens(){let r=await(await this.auth.getClient()).getAccessToken();if(!r.token){console.error(O.t("mcp.auth.failedToGetAccessToken"));return}return{access_token:r.token,token_type:"Bearer"}}saveTokens(e){}redirectToAuthorization(e){}saveCodeVerifier(e){}codeVerifier(){return""}}});import{execFile as i6o}from"node:child_process";import{promisify as o6o}from"node:util";import{platform as s6o}from"node:os";import{URL as a6o}from"node:url";function c6o(t){let e;try{e=new a6o(t)}catch{throw new Error(`Invalid URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsafe protocol: ${e.protocol}. Only HTTP and HTTPS are allowed.`);if(/[\r\n\x00-\x1f]/.test(t))throw new Error("URL contains invalid characters")}async function iGr(t){c6o(t);let e=s6o(),r,n;switch(e){case"darwin":r="open",n=[t];break;case"win32":r="powershell.exe",n=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":r="xdg-open",n=[t];break;default:throw new Error(`Unsupported platform: ${e}`)}let o={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await nGr(r,n,o)}catch(s){if((e==="linux"||e==="freebsd"||e==="openbsd")&&r==="xdg-open"){let a=["gnome-open","kde-open","firefox","chromium","google-chrome"];for(let c of a)try{await nGr(c,[t],o);return}catch{continue}}throw new Error(`Failed to open browser: ${s instanceof Error?s.message:"Unknown error"}`)}}var nGr,oGr=te(()=>{"use strict";nGr=o6o(i6o)});function ps(t){return t instanceof Error&&"code"in t}function _r(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"Failed to get error details"}}function f4t(t){if(t&&typeof t=="object"&&"response"in t){let r=l6o(t);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new gBe(r.error.message);case 401:return new PO(r.error.message);case 403:return new mBe(r.error.message);default:}}return t}function l6o(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var mBe,PO,gBe,Fd=te(()=>{"use strict";mBe=class extends Error{},PO=class extends Error{},gBe=class extends Error{}});import{promises as HJ}from"node:fs";import*as ABe from"node:path";import*as sGr from"node:os";var Xm,yBe=te(()=>{"use strict";Fd();_i();Xm=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=sGr.homedir();return ABe.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=ABe.dirname(this.getTokenFilePath());await HJ.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await HJ.readFile(r,"utf-8"),o=JSON.parse(n);for(let s of o)e.set(s.serverName,s)}catch(r){r.code!=="ENOENT"&&console.error(O.t("mcp.tokenStorage.errors.failedToLoadTokens",{error:_r(r)}))}return e}static async saveToken(e,r,n,o,s){await this.ensureConfigDir();let a=await this.loadTokens(),c={serverName:e,token:r,clientId:n,tokenUrl:o,mcpServerUrl:s,updatedAt:Date.now()};a.set(e,c);let u=Array.from(a.values()),d=this.getTokenFilePath();try{await HJ.writeFile(d,JSON.stringify(u,null,2),{mode:384})}catch(f){throw console.error(O.t("mcp.tokenStorage.errors.failedToSaveToken",{error:_r(f)})),f}}static async getToken(e){return(await this.loadTokens()).get(e)||null}static async removeToken(e){let r=await this.loadTokens();if(r.delete(e)){let n=Array.from(r.values()),o=this.getTokenFilePath();try{n.length===0?await HJ.unlink(o):await HJ.writeFile(o,JSON.stringify(n,null,2),{mode:384})}catch(s){console.error(O.t("mcp.tokenStorage.errors.failedToRemoveToken",{error:_r(s)}))}}}static isTokenExpired(e){if(!e.expiresAt)return!1;let r=300*1e3;return Date.now()+r>=e.expiresAt}static async clearAllTokens(){try{let e=this.getTokenFilePath();await HJ.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(O.t("mcp.tokenStorage.errors.failedToClearTokens",{error:_r(e)}))}}}});var Jm,_Be=te(()=>{"use strict";Fd();_i();Jm=class{static buildWellKnownUrls(e){let r=new URL(e),n=`${r.protocol}//${r.host}`;return{protectedResource:new URL("/.well-known/oauth-protected-resource",n).toString(),authorizationServer:new URL("/.well-known/oauth-authorization-server",n).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch protected resource metadata from ${e}: ${_r(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return console.debug(`Failed to fetch authorization server metadata from ${e}: ${_r(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[]}}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(n?.authorization_servers?.length){let s=n.authorization_servers[0],a=new URL("/.well-known/oauth-authorization-server",s).toString(),c=await this.fetchAuthorizationServerMetadata(a);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&console.log(O.t("mcp.oauth.discovery.dynamicRegistrationSupported"),c.registration_endpoint),u}}console.debug(`Trying OAuth discovery fallback at ${r.authorizationServer}`);let o=await this.fetchAuthorizationServerMetadata(r.authorizationServer);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&console.log(O.t("mcp.oauth.discovery.dynamicRegistrationSupported"),o.registration_endpoint),s}return null}catch(r){return console.debug(`Failed to discover OAuth configuration: ${_r(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e){let r=this.parseWWWAuthenticateHeader(e);if(!r)return null;console.log(O.t("mcp.oauth.discovery.foundResourceMetadataUri",{uri:r}));let n=await this.fetchProtectedResourceMetadata(r);if(!n?.authorization_servers?.length)return null;let o=n.authorization_servers[0],s=new URL("/.well-known/oauth-authorization-server",o).toString(),a=await this.fetchAuthorizationServerMetadata(s);return a?(console.log(O.t("mcp.oauth.discovery.configDiscoveredFromWwwAuth")),this.metadataToOAuthConfig(a)):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}`}}});import*as aGr from"node:http";import*as Cme from"node:crypto";import{URL as p4t}from"node:url";var B_,h4t=te(()=>{"use strict";oGr();yBe();Fd();_Be();_i();B_=class{static REDIRECT_PORT=7777;static REDIRECT_PATH="/oauth/callback";static HTTP_OK=200;static HTTP_REDIRECT=302;static async registerClient(e,r){let o={client_name:"iFlow CLI MCP Client",redirect_uris:[r.redirectUri||`http://localhost:${this.REDIRECT_PORT}${this.REDIRECT_PATH}`],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",code_challenge_method:["S256"],scope:r.scopes?.join(" ")||""},s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let a=await s.text();throw new Error(O.t("mcp.auth.clientRegistrationFailed",{status:s.status,statusText:s.statusText,error:a}))}return await s.json()}static async discoverOAuthFromMCPServer(e){let r=Jm.extractBaseUrl(e);return Jm.discoverOAuthConfig(r)}static generatePKCEParams(){let e=Cme.randomBytes(32).toString("base64url"),r=Cme.createHash("sha256").update(e).digest("base64url"),n=Cme.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let o=aGr.createServer(async(s,a)=>{try{let c=new p4t(s.url,`http://localhost:${this.REDIRECT_PORT}`);if(c.pathname!==this.REDIRECT_PATH){a.writeHead(404),a.end(O.t("mcp.ui.notFound"));return}let u=c.searchParams.get("code"),d=c.searchParams.get("state"),f=c.searchParams.get("error");if(f){a.writeHead(this.HTTP_OK,{"Content-Type":"text/html"}),a.end(`
|
|
963
963
|
<html>
|
|
964
964
|
<body>
|
|
965
965
|
<h1>${O.t("mcp.ui.authenticationFailed")}</h1>
|
|
@@ -4497,7 +4497,7 @@ ${g.join(`
|
|
|
4497
4497
|
`,e-1),[o,s]=asa(r);return{line:n===-1?o:t.slice(0,n+1).match(/\n/g).length+o,column:e-n-1+s}}function aer(t,e,r){if(typeof t!="string")throw new TypeError("Text parameter should be a string");if(!Number.isInteger(e))throw new TypeError("Index parameter should be an integer");if(e<0||e>t.length)throw new RangeError("Index out of bounds");return csa(t,e,r)}var lsa=t=>`\\u{${t.codePointAt(0).toString(16)}}`,cer=class t extends Error{name="JSONError";fileName;#e;#t;#r;#n;#i;constructor(e){if(typeof e=="string")super(),this.#r=e;else{let{jsonParseError:r,fileName:n,input:o}=e;super(void 0,{cause:r}),this.#e=o,this.#t=r,this.fileName=n}Error.captureStackTrace?.(this,t)}get message(){this.#r??=`${dsa(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:e}=this;return`${this.#r}${this.fileName?` in ${this.fileName}`:""}${e?`
|
|
4498
4498
|
|
|
4499
4499
|
${e}
|
|
4500
|
-
`:""}`}set message(e){this.#r=e}#o(e){if(!this.#t)return;let r=this.#e,n=usa(r,this.#t.message);if(n)return(0,zri.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#o(!0),this.#n}get rawCodeFrame(){return this.#i??=this.#o(!1),this.#i}},usa=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:o,column:s}=r.groups;return o&&s?{line:Number(o),column:Number(s)}:aer(t,Number(n),{oneBased:!0})},dsa=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${lsa(n)})`);function ler(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new cer({jsonParseError:n,fileName:r,input:t})}}var iii=Ie(rii(),1);import{fileURLToPath as Baa}from"node:url";function nii(t){return t instanceof URL?Baa(t):t}var Faa=t=>Maa.resolve(nii(t)??".","package.json"),Laa=(t,e)=>{let r=typeof t=="string"?ler(t):t;return e&&(0,iii.default)(r),r};async function oii({cwd:t,normalize:e=!0}={}){let r=await Paa.readFile(Faa(t),"utf8");return Laa(r,e)}async function sii(t){let e=await Cri("package.json",t);if(e)return{packageJson:await oii({...t,cwd:Uaa.dirname(e)}),path:e}}import{fileURLToPath as Qaa}from"url";import jaa from"path";var Gaa=Qaa(import.meta.url),$aa=jaa.dirname(Gaa),ztt;async function sM(){if(ztt)return ztt;let t=await sii({cwd:$aa});if(t)return ztt=t.packageJson,ztt}async function aM(){let t=await sM();return"0.4.2"}var L6e=Ie(hii(),1);import*as mii from"node:os";var gii=["docker","podman","sandbox-exec"];function Jaa(t){return gii.includes(t)}function Zaa(t){if(process.env.SANDBOX)return"";let e=process.env.IFLOW_SANDBOX?.toLowerCase().trim()??"";if(t=e?.length>0?e:t,t==="1"||t==="true"?t=!0:(t==="0"||t==="false"||!t)&&(t=!1),t===!1)return"";if(typeof t=="string"&&t){if(Jaa(t)||(console.error(`ERROR: invalid sandbox command '${t}'. Must be one of ${gii.join(", ")}`),process.exit(1)),L6e.default.sync(t))return t;console.error(`ERROR: missing sandbox command '${t}' (from IFLOW_SANDBOX)`),process.exit(1)}return mii.platform()==="darwin"&&L6e.default.sync("sandbox-exec")?"sandbox-exec":L6e.default.sync("docker")&&t===!0?"docker":L6e.default.sync("podman")&&t===!0?"podman":(t===!0&&(console.error("ERROR: IFLOW_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in IFLOW_SANDBOX"),process.exit(1)),"")}async function Aii(t,e){let r=e.sandbox??t.sandbox,n=Zaa(r),o=await sM(),s=e.sandboxImage??process.env.IFLOW_SANDBOX_IMAGE??o?.config?.sandboxImageUri;return n==="sandbox-exec"?{command:n,image:s||"n/a"}:n&&s?{command:n,image:s}:void 0}_l();Gt();import*as Ber from"path";import{homedir as eca}from"os";import*as U6e from"fs";function tca(t){try{let e=Ber.resolve(t),r=Ber.resolve(eca()),n=U6e.existsSync(e)?U6e.realpathSync(e):e,o=U6e.realpathSync(r);return n===o}catch{return!1}}async function rca(t,e,r,n){let{scope:o,transport:s,env:a,header:c,timeout:u,trust:d,description:f,includeTools:p,excludeTools:h}=n,m=process.cwd();o==="project"&&tca(m)&&(console.log(O.t("mcpAdd.info.detectedHomeDirectory")),o="user");let g=o==="user"?"User":"Workspace",A=yl(process.cwd()),y={},E=c?.reduce((w,R)=>{let[D,...M]=R.split(":"),I=M.join(":").trim();return D.trim()&&I&&(w[D.trim()]=I),w},{});switch(s){case"sse":y={url:e,headers:E,timeout:u,trust:d,description:f,includeTools:p,excludeTools:h};break;case"http":y={httpUrl:e,headers:E,timeout:u,trust:d,description:f,includeTools:p,excludeTools:h};break;case"stdio":default:y={command:e,args:r?.map(String),env:a?.reduce((w,R)=>{let[D,M]=R.split("=");return D&&M&&(w[D]=M),w},{}),timeout:u,trust:d,description:f,includeTools:p,excludeTools:h};break}let b=A.forScope(g).settings.mcpServers||{},S=!!b[t];S&&console.log(O.t("mcpAdd.info.serverAlreadyConfigured",{name:t,scope:o})),b[t]=y,A.setValue(g,"mcpServers",b),console.log(S?O.t("mcpAdd.info.serverUpdated",{name:t,scope:o}):O.t("mcpAdd.info.serverAdded",{name:t,scope:o,transport:s}))}var yii={command:"add <name> <commandOrUrl> [args...]",describe:O.t("mcpAdd.description"),builder:t=>t.usage(O.t("mcpAdd.usage")).parserConfiguration({"unknown-options-as-args":!0,"populate--":!0}).positional("name",{describe:O.t("mcpAdd.options.name"),type:"string",demandOption:!0}).positional("commandOrUrl",{describe:O.t("mcpAdd.options.commandOrUrl"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:O.t("mcpAdd.options.scope"),type:"string",default:"project",choices:["user","project"]}).option("transport",{alias:"t",describe:O.t("mcpAdd.options.transport"),type:"string",default:"stdio",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:O.t("mcpAdd.options.env"),type:"array",string:!0}).option("header",{alias:"H",describe:O.t("mcpAdd.options.header"),type:"array",string:!0}).option("timeout",{describe:O.t("mcpAdd.options.timeout"),type:"number"}).option("trust",{describe:O.t("mcpAdd.options.trust"),type:"boolean"}).option("description",{describe:O.t("mcpAdd.options.description"),type:"string"}).option("include-tools",{describe:O.t("mcpAdd.options.includeTools"),type:"array",string:!0}).option("exclude-tools",{describe:O.t("mcpAdd.options.excludeTools"),type:"array",string:!0}).middleware(e=>{if(e["--"]){let r=e.args||[];e.args=[...r,...e["--"]]}}),handler:async t=>{await rca(t.name,t.commandOrUrl,t.args,{scope:t.scope,transport:t.transport,env:t.env,header:t.header,timeout:t.timeout,trust:t.trust,description:t.description,includeTools:t.includeTools,excludeTools:t.excludeTools})}};_l();Gt();async function nca(t,e){let{scope:r}=e,n=r==="user"?"User":"Workspace",o=yl(process.cwd()),a=o.forScope(n).settings.mcpServers||{};if(!a[t]){console.log(O.t("mcpRemove.errors.serverNotFound",{name:t,scope:r}));return}delete a[t],o.setValue(n,"mcpServers",a),console.log(O.t("mcpRemove.info.serverRemoved",{name:t,scope:r}))}var _ii={command:"remove <name>",describe:O.t("mcpRemove.description"),builder:t=>t.usage(O.t("mcpRemove.usage")).positional("name",{describe:O.t("mcpRemove.options.name"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:O.t("mcpRemove.options.scope"),type:"string",default:"project",choices:["user","project"]}),handler:async t=>{await nca(t.name,{scope:t.scope})}};_l();Gt();BJ();var ica="\x1B[32m",oca="\x1B[33m",sca="\x1B[31m",aca="\x1B[90m",Ktt="\x1B[0m";async function cca(){let t=yl(process.cwd()),e=rM(process.cwd()),r={...t.merged.mcpServers||{}};for(let n of e)Object.entries(n.config.mcpServers||{}).forEach(([o,s])=>{r[o]||(r[o]={...s,extensionName:n.config.name})});return r}async function lca(t,e){let r=new k_({name:"mcp-test-client",version:"0.0.1"}),n;try{n=await Dme(t,e,!1)}catch{return await r.close(),ko.DISCONNECTED}try{return await r.connect(n,{timeout:5e3}),await r.ping(),await r.close(),ko.CONNECTED}catch{return await n.close(),ko.DISCONNECTED}}async function uca(t,e){return await lca(t,e)}async function dca(){let t=await cca(),e=Object.keys(t);if(e.length===0){console.log(O.t("mcpList.info.noServersConfigured"));return}console.log(O.t("mcpList.info.configuredServers"));for(let r of e){let n=t[r],o=await uca(r,n),s="",a="";if(n?.disabled)s=aca+"\u26A0"+Ktt,a=O.t("mcpList.status.disabled");else switch(o){case ko.CONNECTED:s=ica+"\u2713"+Ktt,a=O.t("mcpList.status.connected");break;case ko.CONNECTING:s=oca+"\u2026"+Ktt,a=O.t("mcpList.status.connecting");break;case ko.DISCONNECTED:default:s=sca+"\u2717"+Ktt,a=O.t("mcpList.status.disconnected");break}let c=`${r}: `;if(n.httpUrl)c+=O.t("mcpList.info.serverInfoHttp",{url:n.httpUrl});else if(n.url)c+=O.t("mcpList.info.serverInfoSse",{url:n.url});else if(n.command){let u=n.args?.join(" ")||"";c+=O.t("mcpList.info.serverInfoStdio",{command:n.command,args:u})}console.log(O.t("mcpList.info.serverStatusLine",{statusIndicator:s,serverInfo:c,statusText:a}))}}var Eii={command:"list",describe:O.t("mcpList.description"),handler:async()=>{await dca()}};_l();Gt();import*as Per from"path";import{homedir as fca}from"os";import*as Q6e from"fs";import{execSync as pca}from"child_process";function hca(t){try{let e=Per.resolve(t),r=Per.resolve(fca()),n=Q6e.existsSync(e)?Q6e.realpathSync(e):e,o=Q6e.realpathSync(r);return n===o}catch{return!1}}function mca(){try{return pca("uv --version",{stdio:"pipe"}),!0}catch{return!1}}function gca(t){return t.search(/uvx/)!==-1}async function Aca(t,e,r){let{scope:n}=r,o=process.cwd();n==="project"&&hca(o)&&(console.log(O.t("mcpAdd.info.detectedHomeDirectory")),n="user");let s=n==="user"?"User":"Workspace",a=yl(process.cwd()),c;try{c=JSON.parse(e)}catch(m){console.error(O.t("mcpAddJson.errors.invalidJson")),console.error(m);return}if(typeof c!="object"||c===null||Array.isArray(c)){console.error(O.t("mcpAddJson.errors.mustBeObject"));return}let u=c,d=u;if(d.command&&gca(d.command)&&!mca()){console.error(O.t("mcpAddJson.errors.uvxRequiresUv")),console.error(O.t("mcpAddJson.errors.uvInstallationGuide")),console.error(""),console.error("Installation methods:"),console.error(" - macOS/Linux: curl -LsSf https://astral.sh/uv/install.sh | sh"),console.error(' - Windows: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"'),console.error(" - Via package managers:"),console.error(" * Homebrew (macOS): brew install uv"),console.error(" * Cargo (cross-platform): cargo install uv"),console.error("");return}if(u.type==="http"&&u.url&&!u.httpUrl&&(u.httpUrl=u.url,delete u.url),!u.command&&!u.url&&!u.httpUrl&&!u.tcp){console.error(O.t("mcpAddJson.errors.noTransport"));return}let p=a.forScope(s).settings.mcpServers||{},h=!!p[t];h&&console.log(O.t("mcpAdd.info.serverAlreadyConfigured",{name:t,scope:n})),p[t]=u,a.setValue(s,"mcpServers",p),console.log(h?O.t("mcpAdd.info.serverUpdated",{name:t,scope:n}):O.t("mcpAddJson.info.serverAdded",{name:t,scope:n})),d.command?(console.log(O.t("mcpAddJson.info.transportStdio")),console.log(O.t("mcpAddJson.info.command",{command:d.command})),d.args&&Array.isArray(d.args)&&d.args.length>0&&console.log(O.t("mcpAddJson.info.arguments",{args:d.args.join(" ")}))):d.url?(console.log(O.t("mcpAddJson.info.transportSse")),console.log(O.t("mcpAddJson.info.url",{url:d.url}))):d.httpUrl?(console.log(O.t("mcpAddJson.info.transportHttp")),console.log(O.t("mcpAddJson.info.url",{url:d.httpUrl}))):d.tcp&&(console.log(O.t("mcpAddJson.info.transportWebsocket")),console.log(O.t("mcpAddJson.info.tcp",{tcp:d.tcp}))),d.description&&console.log(O.t("mcpAddJson.info.description",{description:d.description})),d.env&&typeof d.env=="object"&&Object.keys(d.env).length>0&&console.log(O.t("mcpAddJson.info.envVars",{vars:Object.keys(d.env).join(", ")})),d.headers&&typeof d.headers=="object"&&Object.keys(d.headers).length>0&&console.log(O.t("mcpAddJson.info.headers",{headers:Object.keys(d.headers).join(", ")})),d.oauth?.enabled&&console.log(O.t("mcpAddJson.info.oauthEnabled"))}var vii={command:"add-json <name> <json>",describe:O.t("mcpAddJson.description"),builder:t=>t.usage(O.t("mcpAddJson.usage")).positional("name",{describe:O.t("mcpAdd.options.name"),type:"string",demandOption:!0}).positional("json",{describe:O.t("mcpAddJson.options.json"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:O.t("mcpAdd.options.scope"),type:"string",default:"project",choices:["user","project"]}),handler:async t=>{await Aca(t.name,t.json,{scope:t.scope})}};_l();Gt();async function yca(){let t=yl(process.cwd()),e=rM(process.cwd()),r={...t.merged.mcpServers||{}};for(let n of e)Object.entries(n.config.mcpServers||{}).forEach(([o,s])=>{r[o]||(r[o]={...s,extensionName:n.config.name})});return r}async function _ca(t){let e=await yca();if(!e[t]){console.log(O.t("mcpGet.errors.serverNotFound",{name:t}));return}let r=e[t];if(console.log(O.t("mcpGet.info.serverTitle",{name:t})),console.log(),console.log(O.t("mcpGet.info.configuration")),r.command?(console.log(O.t("mcpGet.info.transportStdio")),console.log(O.t("mcpGet.info.command",{command:r.command})),r.args&&r.args.length>0&&(console.log(O.t("mcpGet.info.arguments")),r.args.forEach((n,o)=>{console.log(O.t("mcpGet.info.argumentItem",{index:o,arg:n}))}))):r.url?(console.log(O.t("mcpGet.info.transportSse")),console.log(O.t("mcpGet.info.url",{url:r.url}))):r.httpUrl?(console.log(O.t("mcpGet.info.transportHttp")),console.log(O.t("mcpGet.info.url",{url:r.httpUrl}))):console.log(O.t("mcpGet.info.transportUnknown")),r.env&&Object.keys(r.env).length>0){console.log(O.t("mcpGet.info.environmentVariables"));for(let[n,o]of Object.entries(r.env))console.log(O.t("mcpGet.info.envVar",{key:n,value:o}))}if(r.headers&&Object.keys(r.headers).length>0){console.log(O.t("mcpGet.info.headers"));for(let[n,o]of Object.entries(r.headers))console.log(O.t("mcpGet.info.header",{key:n,value:o}))}r.description&&console.log(O.t("mcpGet.info.description",{description:r.description})),r.timeout!==void 0&&console.log(O.t("mcpGet.info.timeout",{timeout:r.timeout})),r.trust!==void 0&&console.log(O.t("mcpGet.info.trusted",{trusted:r.trust?O.t("mcpGet.common.yes"):O.t("mcpGet.common.no")})),r.includeTools&&r.includeTools.length>0&&(console.log(O.t("mcpGet.info.includeTools")),r.includeTools.forEach((n,o)=>{console.log(O.t("mcpGet.info.toolItem",{index:o,tool:n}))})),r.excludeTools&&r.excludeTools.length>0&&(console.log(O.t("mcpGet.info.excludeTools")),r.excludeTools.forEach((n,o)=>{console.log(O.t("mcpGet.info.toolItem",{index:o,tool:n}))})),r.extensionName&&console.log(O.t("mcpGet.info.extension",{extension:r.extensionName})),console.log(),console.log(O.t("mcpGet.info.rawJsonConfiguration")),console.log(JSON.stringify(r,null,2))}var bii={command:"get <name>",describe:O.t("mcpGet.description"),builder:t=>t.usage(O.t("mcpGet.usage")).positional("name",{describe:O.t("mcpGet.options.name"),type:"string",demandOption:!0}),handler:async t=>{await _ca(t.name)}};fG();Gt();import*as Xtt from"fs";import*as Cii from"path";async function Eca(){let t=process.cwd();try{let e=await Jv("**/.mcp.json",{cwd:t,absolute:!0,ignore:["**/node_modules/**","**/.*/**"]});if(e.length===0){console.log(O.t("mcpResetProjectChoices.info.noFilesFound"));return}console.log(O.t("mcpResetProjectChoices.info.foundFiles",{count:e.length}));let r=0,n=0;for(let o of e){let s=Cii.relative(t,o);try{let a=Xtt.readFileSync(o,"utf8"),c;try{c=JSON.parse(a)}catch{console.log(O.t("mcpResetProjectChoices.info.invalidJson",{path:s}));continue}c.approvedServers||c.rejectedServers||c.mcpServerChoices?(Xtt.unlinkSync(o),console.log(O.t("mcpResetProjectChoices.info.fileDeleted",{path:s})),r++):console.log(O.t("mcpResetProjectChoices.info.noChoicesSkipping",{path:s}))}catch(a){console.log(O.t("mcpResetProjectChoices.errors.fileError",{path:s,error:a})),n++}}console.log(),console.log(O.t("mcpResetProjectChoices.info.summary")),console.log(O.t("mcpResetProjectChoices.info.deletedFiles",{count:r})),n>0&&console.log(O.t("mcpResetProjectChoices.info.errorFiles",{count:n})),r>0&&(console.log(),console.log(O.t("mcpResetProjectChoices.info.resetComplete")),console.log(O.t("mcpResetProjectChoices.info.extensionPrompt")))}catch(e){console.error(O.t("mcpResetProjectChoices.errors.searchError"),e)}}var Sii={command:"reset-project-choices",describe:O.t("mcpResetProjectChoices.description"),builder:t=>t.usage(O.t("mcpResetProjectChoices.usage")),handler:async()=>{await Eca()}};Gt();var xii={command:"mcp",describe:O.t("mcpCommand.description"),builder:t=>t.command(yii).command(_ii).command(Eii).command(vii).command(bii).command(Sii).demandCommand(1,O.t("mcpCommand.demandCommand")).version(!1),handler:()=>{}};Qer();Ger();_l();Gt();import kg from"fs/promises";import z5 from"path";import ola from"os";var sla=async(t,e=1,r=20)=>{try{if(!t)return{success:!1,message:O.t("workflowAdd.pleaseAuthenticate")};let o=await fetch("https://apis.iflow.cn/v1/workflows/list",{method:"POST",headers:{"User-Agent":"iFlow-Cli","Content-Type":"application/json"},body:JSON.stringify({page:e,size:r,usePage:!0})});if(!o.ok){let c=O.t("workflowAdd.unableToLoadWorkflows");return o.status===401?c=O.t("workflowAdd.authenticationFailed"):o.status===403?c=O.t("workflowAdd.accessDenied"):o.status===404?c=O.t("workflowAdd.serviceNotFound"):o.status>=500&&(c=O.t("workflowAdd.serverError")),{success:!1,message:c}}let s=await o.json();return s.success?{success:!0,workflows:Array.isArray(s.data.data)?s.data.data:[],total:s.data.total||0}:{success:!1,message:s.message||O.t("workflowAdd.failedToLoadFromServer")}}catch(n){let o=O.t("workflowAdd.connectionError");return n instanceof Error&&n.message.includes("Failed to fetch")&&(o=O.t("workflowAdd.networkError")),{success:!1,message:o}}},ala=async(t,e)=>{try{let r=await fetch(`https://apis.iflow.cn/v1/workflows/get/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);let n=await r.json();if(!n.success)throw new Error(n.message||O.t("workflowAdd.failedToFetchDetails"));return n.data||null}catch(r){return console.error(O.t("workflowAdd.failedToFetchDetails"),r),null}},cla=async(t,e)=>{let r=await fetch(t);if(!r.ok)throw new Error(`Failed to download file: ${r.status} ${r.statusText}`);let n=await r.arrayBuffer();await kg.writeFile(e,Buffer.from(n))},lla=t=>{let e=new URL(t).pathname;return z5.extname(e).toLowerCase()},ula=async t=>{let{exec:e}=await import("child_process"),{promisify:r}=await import("util"),n=r(e);try{let o=process.platform==="win32"?`where ${t}`:`which ${t}`;return await n(o),!0}catch{return!1}},dla=async(t,e)=>{let{exec:r}=await import("child_process"),{promisify:n}=await import("util"),o=n(r),s=process.platform==="win32",a=[];s?a.push({name:"Windows tar",command:`tar -xf "${t}" -C "${e}"`,check:"tar"},{name:"PowerShell",command:`powershell -Command "Expand-Archive -Path '${t}' -DestinationPath '${e}' -Force"`,check:"powershell"},{name:"7-Zip",command:`7z x "${t}" -o"${e}" -y`,check:"7z"},{name:"WinRAR",command:`winrar x "${t}" "${e}\\"`,check:"winrar"}):a.push({name:"unzip",command:`unzip -q "${t}" -d "${e}"`,check:"unzip"},{name:"tar",command:`tar -xf "${t}" -C "${e}"`,check:"tar"});let c=null;for(let d of a)try{if(d.check&&!await ula(d.check)){console.log(`\u23ED\uFE0F Skipping ${d.name} (not available)`);continue}console.log(`\u{1F527} Trying to extract with ${d.name}...`),await o(d.command),console.log(`\u2714 Successfully extracted using ${d.name}`);return}catch(f){console.log(`\u274C ${d.name} failed: ${f instanceof Error?f.message:String(f)}`),c=f instanceof Error?f:new Error(String(f))}let u=a.map(d=>d.name).join(", ");throw new Error(`Failed to extract ZIP file. Tried all available methods: ${u}. Last error: ${c?.message||"Unknown error"}. Please install one of: ${s?"7-Zip, WinRAR, or ensure PowerShell is available":"unzip or tar"}`)},fla=async(t,e,r)=>{try{switch(r){case".zip":await dla(t,e);break;case".tgz":case".tar.gz":case".tar":case".tar.bz2":case".tbz2":case".tar.xz":case".txz":{let{exec:n}=await import("child_process"),{promisify:o}=await import("util"),s=o(n),a;switch(r){case".tgz":case".tar.gz":a=`tar -xzf "${t}" -C "${e}"`;break;case".tar":a=`tar -xf "${t}" -C "${e}"`;break;case".tar.bz2":case".tbz2":a=`tar -xjf "${t}" -C "${e}"`;break;case".tar.xz":case".txz":a=`tar -xJf "${t}" -C "${e}"`;break;default:throw new Error(`Unsupported tar format: ${r}`)}await s(a);break}default:throw new Error(`Unsupported archive format: ${r}`)}}catch(n){throw new Error(`Failed to extract ${r} file. Original error: ${n}`)}},pla=async t=>{try{let e=await kg.readFile(t,{flag:"r"});if(e.length>=4){let r=e.readUInt32BE(0);return r===333319||r===333312}return!1}catch{return!1}},toi=async t=>{try{let e=await kg.readdir(t,{withFileTypes:!0});for(let r of e){let n=z5.join(t,r.name);if(r.isDirectory())await toi(n),r.name==="__MACOSX"&&await kg.rm(n,{recursive:!0,force:!0});else{let o=!1;(r.name===".DS_Store"||r.name.startsWith("._")&&await pla(n))&&(o=!0),o&&await kg.rm(n,{force:!0})}}}catch(e){console.warn(`Warning: Failed to clean up macOS files in ${t}: ${e}`)}},hla=async(t,e,r)=>{try{let n;try{n=JSON.parse(t.extInfo)}catch(u){return{success:!1,message:O.t("workflowAdd.invalidExtInfo",{error:u instanceof Error?u.message:String(u)})}}if(!n.url)return{success:!1,message:O.t("workflowAdd.noDownloadUrl")};let o=lla(n.url),s=await kg.mkdtemp(z5.join(ola.tmpdir(),"iflow-workflow-")),a=z5.join(s,`workflow${o}`),c=z5.join(s,"extracted");try{console.log(O.t("workflowAdd.downloading",{url:n.url})),await cla(n.url,a),console.log(O.t("workflowAdd.extracting")),await kg.mkdir(c,{recursive:!0}),await fla(a,c,o),await toi(c);let u=await mla(c);console.log(O.t("workflowAdd.copyingFiles"));let d=e||process.cwd(),f=await kg.readdir(c);for(let p of f){let h=z5.join(c,p),m=z5.join(d,p);(await kg.stat(h)).isDirectory()?(console.log(`Copying directory: ${h} -> ${m}`),await roi(h,m)):(console.log(`\u{1F4C4} Copying file: ${h} -> ${m}`),await kg.copyFile(h,m))}return u&&await gla(d),await kg.rm(s,{recursive:!0,force:!0}),{success:!0,message:O.t("workflowAdd.installSuccess",{workflowName:r,targetDir:d})}}catch(u){try{await kg.rm(s,{recursive:!0,force:!0})}catch{}throw u}}catch(n){let o=n instanceof Error?n.message:String(n);return{success:!1,message:O.t("workflowAdd.installFailed",{workflowName:r,error:o})}}},roi=async(t,e)=>{await kg.mkdir(e,{recursive:!0});let r=await kg.readdir(t,{withFileTypes:!0});for(let n of r){let o=z5.join(t,n.name),s=z5.join(e,n.name);n.isDirectory()?await roi(o,s):await kg.copyFile(o,s)}},mla=async t=>{let e=z5.join(t,"command_setup.sh");try{return await kg.access(e,kg.constants.F_OK),console.log("\u{1F50D} Detected command_setup.sh in workflow"),!0}catch{return!1}},gla=async t=>{let e=z5.join(t,"command_setup.sh");try{console.log("\u{1F527} Executing command_setup.sh..."),await kg.chmod(e,493);let{exec:r}=await import("child_process"),{promisify:n}=await import("util"),o=n(r),{stdout:s,stderr:a}=await o("bash command_setup.sh",{cwd:t,timeout:3e5});s&&(console.log("\u{1F4CB} Setup script output:"),console.log(s)),a&&(console.warn("\u26A0\uFE0F Setup script warnings:"),console.warn(a)),console.log("\u2714 command_setup.sh executed successfully")}catch(r){console.error("\u274C Failed to execute command_setup.sh:"),console.error(r instanceof Error?r.message:String(r)),console.warn("\u26A0\uFE0F Workflow installation completed but setup script failed"),console.warn("\u{1F4A1} Please manually execute command_setup.sh if needed")}};async function Ala(t){let r=yl(process.cwd()).merged.apiKey;r||(console.error(O.t("workflowAdd.apiKeyNotFound")),console.error(O.t("workflowAdd.pleaseAuthenticate")),process.exit(1)),console.log(O.t("workflowAdd.searching",{nameOrId:t}));try{let n=null;if(/^\d+$/.test(t)){let u=parseInt(t,10);n=await ala(r,u)}if(!n){let u=await sla(r,1,500);u.success||(console.error(O.t("workflowAdd.error",{error:u.message})),process.exit(1)),n=u.workflows?.find(d=>d.workflowId?.toLowerCase()===t.toLowerCase())||u.workflows?.[0]||null}n||(console.error(O.t("workflowAdd.notFoundInRepo",{nameOrId:t})),process.exit(1));let o=n.name||"Unknown";try{if(n.name){let u=JSON.parse(n.name);u.en&&(o=u.en)}}catch{}console.log(O.t("workflowAdd.foundWorkflow",{name:o}));let s=n.description||"No description available";try{if(n.description){let u=JSON.parse(n.description);u.en&&(s=u.en)}}catch{}console.log(O.t("workflowAdd.workflowDescription",{description:s})),console.log(O.t("workflowAdd.installing"));let a=process.cwd(),c=await hla(n,a,o);c.success?console.log(c.message):(console.error(c.message),process.exit(1))}catch(n){console.error(O.t("workflowAdd.errorAdding",{error:n})),process.exit(1)}}var noi={command:"add <name-or-id>",describe:O.t("workflowAdd.description"),builder:t=>t.usage(O.t("workflowAdd.usage")).positional("name-or-id",{describe:O.t("workflowAdd.workflowIdOrNumericIdOption"),type:"string",demandOption:!0}),handler:async t=>{await Ala(t["name-or-id"])}};Gt();var ioi={command:"workflow",describe:O.t("workflowCommand.description"),builder:t=>t.command(noi).demandCommand(1,O.t("workflowCommand.demandCommand")).version(!1),handler:()=>{}};var Her={debug:(...t)=>console.debug("[DEBUG]",...t),warn:(...t)=>console.warn("[WARN]",...t),error:(...t)=>console.error("[ERROR]",...t)};function _la(t){let e=[],r=new Set(["-p","--prompt"]);for(let n=0;n<t.length;n++){let o=t[n];if(r.has(o)&&n+1<t.length){let s=t[n+1];if(s.startsWith("-")){e.push(`${o}=${s}`),n++;continue}}e.push(o)}return e}async function nrt(){let t=_la(fm.argv),e=jti(BZt(t)).locale("en").scriptName("iflow").usage(`Usage: iflow [options] [command]
|
|
4500
|
+
`:""}`}set message(e){this.#r=e}#o(e){if(!this.#t)return;let r=this.#e,n=usa(r,this.#t.message);if(n)return(0,zri.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#o(!0),this.#n}get rawCodeFrame(){return this.#i??=this.#o(!1),this.#i}},usa=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:o,column:s}=r.groups;return o&&s?{line:Number(o),column:Number(s)}:aer(t,Number(n),{oneBased:!0})},dsa=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${lsa(n)})`);function ler(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new cer({jsonParseError:n,fileName:r,input:t})}}var iii=Ie(rii(),1);import{fileURLToPath as Baa}from"node:url";function nii(t){return t instanceof URL?Baa(t):t}var Faa=t=>Maa.resolve(nii(t)??".","package.json"),Laa=(t,e)=>{let r=typeof t=="string"?ler(t):t;return e&&(0,iii.default)(r),r};async function oii({cwd:t,normalize:e=!0}={}){let r=await Paa.readFile(Faa(t),"utf8");return Laa(r,e)}async function sii(t){let e=await Cri("package.json",t);if(e)return{packageJson:await oii({...t,cwd:Uaa.dirname(e)}),path:e}}import{fileURLToPath as Qaa}from"url";import jaa from"path";var Gaa=Qaa(import.meta.url),$aa=jaa.dirname(Gaa),ztt;async function sM(){if(ztt)return ztt;let t=await sii({cwd:$aa});if(t)return ztt=t.packageJson,ztt}async function aM(){let t=await sM();return"0.4.3"}var L6e=Ie(hii(),1);import*as mii from"node:os";var gii=["docker","podman","sandbox-exec"];function Jaa(t){return gii.includes(t)}function Zaa(t){if(process.env.SANDBOX)return"";let e=process.env.IFLOW_SANDBOX?.toLowerCase().trim()??"";if(t=e?.length>0?e:t,t==="1"||t==="true"?t=!0:(t==="0"||t==="false"||!t)&&(t=!1),t===!1)return"";if(typeof t=="string"&&t){if(Jaa(t)||(console.error(`ERROR: invalid sandbox command '${t}'. Must be one of ${gii.join(", ")}`),process.exit(1)),L6e.default.sync(t))return t;console.error(`ERROR: missing sandbox command '${t}' (from IFLOW_SANDBOX)`),process.exit(1)}return mii.platform()==="darwin"&&L6e.default.sync("sandbox-exec")?"sandbox-exec":L6e.default.sync("docker")&&t===!0?"docker":L6e.default.sync("podman")&&t===!0?"podman":(t===!0&&(console.error("ERROR: IFLOW_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in IFLOW_SANDBOX"),process.exit(1)),"")}async function Aii(t,e){let r=e.sandbox??t.sandbox,n=Zaa(r),o=await sM(),s=e.sandboxImage??process.env.IFLOW_SANDBOX_IMAGE??o?.config?.sandboxImageUri;return n==="sandbox-exec"?{command:n,image:s||"n/a"}:n&&s?{command:n,image:s}:void 0}_l();Gt();import*as Ber from"path";import{homedir as eca}from"os";import*as U6e from"fs";function tca(t){try{let e=Ber.resolve(t),r=Ber.resolve(eca()),n=U6e.existsSync(e)?U6e.realpathSync(e):e,o=U6e.realpathSync(r);return n===o}catch{return!1}}async function rca(t,e,r,n){let{scope:o,transport:s,env:a,header:c,timeout:u,trust:d,description:f,includeTools:p,excludeTools:h}=n,m=process.cwd();o==="project"&&tca(m)&&(console.log(O.t("mcpAdd.info.detectedHomeDirectory")),o="user");let g=o==="user"?"User":"Workspace",A=yl(process.cwd()),y={},E=c?.reduce((w,R)=>{let[D,...M]=R.split(":"),I=M.join(":").trim();return D.trim()&&I&&(w[D.trim()]=I),w},{});switch(s){case"sse":y={url:e,headers:E,timeout:u,trust:d,description:f,includeTools:p,excludeTools:h};break;case"http":y={httpUrl:e,headers:E,timeout:u,trust:d,description:f,includeTools:p,excludeTools:h};break;case"stdio":default:y={command:e,args:r?.map(String),env:a?.reduce((w,R)=>{let[D,M]=R.split("=");return D&&M&&(w[D]=M),w},{}),timeout:u,trust:d,description:f,includeTools:p,excludeTools:h};break}let b=A.forScope(g).settings.mcpServers||{},S=!!b[t];S&&console.log(O.t("mcpAdd.info.serverAlreadyConfigured",{name:t,scope:o})),b[t]=y,A.setValue(g,"mcpServers",b),console.log(S?O.t("mcpAdd.info.serverUpdated",{name:t,scope:o}):O.t("mcpAdd.info.serverAdded",{name:t,scope:o,transport:s}))}var yii={command:"add <name> <commandOrUrl> [args...]",describe:O.t("mcpAdd.description"),builder:t=>t.usage(O.t("mcpAdd.usage")).parserConfiguration({"unknown-options-as-args":!0,"populate--":!0}).positional("name",{describe:O.t("mcpAdd.options.name"),type:"string",demandOption:!0}).positional("commandOrUrl",{describe:O.t("mcpAdd.options.commandOrUrl"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:O.t("mcpAdd.options.scope"),type:"string",default:"project",choices:["user","project"]}).option("transport",{alias:"t",describe:O.t("mcpAdd.options.transport"),type:"string",default:"stdio",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:O.t("mcpAdd.options.env"),type:"array",string:!0}).option("header",{alias:"H",describe:O.t("mcpAdd.options.header"),type:"array",string:!0}).option("timeout",{describe:O.t("mcpAdd.options.timeout"),type:"number"}).option("trust",{describe:O.t("mcpAdd.options.trust"),type:"boolean"}).option("description",{describe:O.t("mcpAdd.options.description"),type:"string"}).option("include-tools",{describe:O.t("mcpAdd.options.includeTools"),type:"array",string:!0}).option("exclude-tools",{describe:O.t("mcpAdd.options.excludeTools"),type:"array",string:!0}).middleware(e=>{if(e["--"]){let r=e.args||[];e.args=[...r,...e["--"]]}}),handler:async t=>{await rca(t.name,t.commandOrUrl,t.args,{scope:t.scope,transport:t.transport,env:t.env,header:t.header,timeout:t.timeout,trust:t.trust,description:t.description,includeTools:t.includeTools,excludeTools:t.excludeTools})}};_l();Gt();async function nca(t,e){let{scope:r}=e,n=r==="user"?"User":"Workspace",o=yl(process.cwd()),a=o.forScope(n).settings.mcpServers||{};if(!a[t]){console.log(O.t("mcpRemove.errors.serverNotFound",{name:t,scope:r}));return}delete a[t],o.setValue(n,"mcpServers",a),console.log(O.t("mcpRemove.info.serverRemoved",{name:t,scope:r}))}var _ii={command:"remove <name>",describe:O.t("mcpRemove.description"),builder:t=>t.usage(O.t("mcpRemove.usage")).positional("name",{describe:O.t("mcpRemove.options.name"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:O.t("mcpRemove.options.scope"),type:"string",default:"project",choices:["user","project"]}),handler:async t=>{await nca(t.name,{scope:t.scope})}};_l();Gt();BJ();var ica="\x1B[32m",oca="\x1B[33m",sca="\x1B[31m",aca="\x1B[90m",Ktt="\x1B[0m";async function cca(){let t=yl(process.cwd()),e=rM(process.cwd()),r={...t.merged.mcpServers||{}};for(let n of e)Object.entries(n.config.mcpServers||{}).forEach(([o,s])=>{r[o]||(r[o]={...s,extensionName:n.config.name})});return r}async function lca(t,e){let r=new k_({name:"mcp-test-client",version:"0.0.1"}),n;try{n=await Dme(t,e,!1)}catch{return await r.close(),ko.DISCONNECTED}try{return await r.connect(n,{timeout:5e3}),await r.ping(),await r.close(),ko.CONNECTED}catch{return await n.close(),ko.DISCONNECTED}}async function uca(t,e){return await lca(t,e)}async function dca(){let t=await cca(),e=Object.keys(t);if(e.length===0){console.log(O.t("mcpList.info.noServersConfigured"));return}console.log(O.t("mcpList.info.configuredServers"));for(let r of e){let n=t[r],o=await uca(r,n),s="",a="";if(n?.disabled)s=aca+"\u26A0"+Ktt,a=O.t("mcpList.status.disabled");else switch(o){case ko.CONNECTED:s=ica+"\u2713"+Ktt,a=O.t("mcpList.status.connected");break;case ko.CONNECTING:s=oca+"\u2026"+Ktt,a=O.t("mcpList.status.connecting");break;case ko.DISCONNECTED:default:s=sca+"\u2717"+Ktt,a=O.t("mcpList.status.disconnected");break}let c=`${r}: `;if(n.httpUrl)c+=O.t("mcpList.info.serverInfoHttp",{url:n.httpUrl});else if(n.url)c+=O.t("mcpList.info.serverInfoSse",{url:n.url});else if(n.command){let u=n.args?.join(" ")||"";c+=O.t("mcpList.info.serverInfoStdio",{command:n.command,args:u})}console.log(O.t("mcpList.info.serverStatusLine",{statusIndicator:s,serverInfo:c,statusText:a}))}}var Eii={command:"list",describe:O.t("mcpList.description"),handler:async()=>{await dca()}};_l();Gt();import*as Per from"path";import{homedir as fca}from"os";import*as Q6e from"fs";import{execSync as pca}from"child_process";function hca(t){try{let e=Per.resolve(t),r=Per.resolve(fca()),n=Q6e.existsSync(e)?Q6e.realpathSync(e):e,o=Q6e.realpathSync(r);return n===o}catch{return!1}}function mca(){try{return pca("uv --version",{stdio:"pipe"}),!0}catch{return!1}}function gca(t){return t.search(/uvx/)!==-1}async function Aca(t,e,r){let{scope:n}=r,o=process.cwd();n==="project"&&hca(o)&&(console.log(O.t("mcpAdd.info.detectedHomeDirectory")),n="user");let s=n==="user"?"User":"Workspace",a=yl(process.cwd()),c;try{c=JSON.parse(e)}catch(m){console.error(O.t("mcpAddJson.errors.invalidJson")),console.error(m);return}if(typeof c!="object"||c===null||Array.isArray(c)){console.error(O.t("mcpAddJson.errors.mustBeObject"));return}let u=c,d=u;if(d.command&&gca(d.command)&&!mca()){console.error(O.t("mcpAddJson.errors.uvxRequiresUv")),console.error(O.t("mcpAddJson.errors.uvInstallationGuide")),console.error(""),console.error("Installation methods:"),console.error(" - macOS/Linux: curl -LsSf https://astral.sh/uv/install.sh | sh"),console.error(' - Windows: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"'),console.error(" - Via package managers:"),console.error(" * Homebrew (macOS): brew install uv"),console.error(" * Cargo (cross-platform): cargo install uv"),console.error("");return}if(u.type==="http"&&u.url&&!u.httpUrl&&(u.httpUrl=u.url,delete u.url),!u.command&&!u.url&&!u.httpUrl&&!u.tcp){console.error(O.t("mcpAddJson.errors.noTransport"));return}let p=a.forScope(s).settings.mcpServers||{},h=!!p[t];h&&console.log(O.t("mcpAdd.info.serverAlreadyConfigured",{name:t,scope:n})),p[t]=u,a.setValue(s,"mcpServers",p),console.log(h?O.t("mcpAdd.info.serverUpdated",{name:t,scope:n}):O.t("mcpAddJson.info.serverAdded",{name:t,scope:n})),d.command?(console.log(O.t("mcpAddJson.info.transportStdio")),console.log(O.t("mcpAddJson.info.command",{command:d.command})),d.args&&Array.isArray(d.args)&&d.args.length>0&&console.log(O.t("mcpAddJson.info.arguments",{args:d.args.join(" ")}))):d.url?(console.log(O.t("mcpAddJson.info.transportSse")),console.log(O.t("mcpAddJson.info.url",{url:d.url}))):d.httpUrl?(console.log(O.t("mcpAddJson.info.transportHttp")),console.log(O.t("mcpAddJson.info.url",{url:d.httpUrl}))):d.tcp&&(console.log(O.t("mcpAddJson.info.transportWebsocket")),console.log(O.t("mcpAddJson.info.tcp",{tcp:d.tcp}))),d.description&&console.log(O.t("mcpAddJson.info.description",{description:d.description})),d.env&&typeof d.env=="object"&&Object.keys(d.env).length>0&&console.log(O.t("mcpAddJson.info.envVars",{vars:Object.keys(d.env).join(", ")})),d.headers&&typeof d.headers=="object"&&Object.keys(d.headers).length>0&&console.log(O.t("mcpAddJson.info.headers",{headers:Object.keys(d.headers).join(", ")})),d.oauth?.enabled&&console.log(O.t("mcpAddJson.info.oauthEnabled"))}var vii={command:"add-json <name> <json>",describe:O.t("mcpAddJson.description"),builder:t=>t.usage(O.t("mcpAddJson.usage")).positional("name",{describe:O.t("mcpAdd.options.name"),type:"string",demandOption:!0}).positional("json",{describe:O.t("mcpAddJson.options.json"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:O.t("mcpAdd.options.scope"),type:"string",default:"project",choices:["user","project"]}),handler:async t=>{await Aca(t.name,t.json,{scope:t.scope})}};_l();Gt();async function yca(){let t=yl(process.cwd()),e=rM(process.cwd()),r={...t.merged.mcpServers||{}};for(let n of e)Object.entries(n.config.mcpServers||{}).forEach(([o,s])=>{r[o]||(r[o]={...s,extensionName:n.config.name})});return r}async function _ca(t){let e=await yca();if(!e[t]){console.log(O.t("mcpGet.errors.serverNotFound",{name:t}));return}let r=e[t];if(console.log(O.t("mcpGet.info.serverTitle",{name:t})),console.log(),console.log(O.t("mcpGet.info.configuration")),r.command?(console.log(O.t("mcpGet.info.transportStdio")),console.log(O.t("mcpGet.info.command",{command:r.command})),r.args&&r.args.length>0&&(console.log(O.t("mcpGet.info.arguments")),r.args.forEach((n,o)=>{console.log(O.t("mcpGet.info.argumentItem",{index:o,arg:n}))}))):r.url?(console.log(O.t("mcpGet.info.transportSse")),console.log(O.t("mcpGet.info.url",{url:r.url}))):r.httpUrl?(console.log(O.t("mcpGet.info.transportHttp")),console.log(O.t("mcpGet.info.url",{url:r.httpUrl}))):console.log(O.t("mcpGet.info.transportUnknown")),r.env&&Object.keys(r.env).length>0){console.log(O.t("mcpGet.info.environmentVariables"));for(let[n,o]of Object.entries(r.env))console.log(O.t("mcpGet.info.envVar",{key:n,value:o}))}if(r.headers&&Object.keys(r.headers).length>0){console.log(O.t("mcpGet.info.headers"));for(let[n,o]of Object.entries(r.headers))console.log(O.t("mcpGet.info.header",{key:n,value:o}))}r.description&&console.log(O.t("mcpGet.info.description",{description:r.description})),r.timeout!==void 0&&console.log(O.t("mcpGet.info.timeout",{timeout:r.timeout})),r.trust!==void 0&&console.log(O.t("mcpGet.info.trusted",{trusted:r.trust?O.t("mcpGet.common.yes"):O.t("mcpGet.common.no")})),r.includeTools&&r.includeTools.length>0&&(console.log(O.t("mcpGet.info.includeTools")),r.includeTools.forEach((n,o)=>{console.log(O.t("mcpGet.info.toolItem",{index:o,tool:n}))})),r.excludeTools&&r.excludeTools.length>0&&(console.log(O.t("mcpGet.info.excludeTools")),r.excludeTools.forEach((n,o)=>{console.log(O.t("mcpGet.info.toolItem",{index:o,tool:n}))})),r.extensionName&&console.log(O.t("mcpGet.info.extension",{extension:r.extensionName})),console.log(),console.log(O.t("mcpGet.info.rawJsonConfiguration")),console.log(JSON.stringify(r,null,2))}var bii={command:"get <name>",describe:O.t("mcpGet.description"),builder:t=>t.usage(O.t("mcpGet.usage")).positional("name",{describe:O.t("mcpGet.options.name"),type:"string",demandOption:!0}),handler:async t=>{await _ca(t.name)}};fG();Gt();import*as Xtt from"fs";import*as Cii from"path";async function Eca(){let t=process.cwd();try{let e=await Jv("**/.mcp.json",{cwd:t,absolute:!0,ignore:["**/node_modules/**","**/.*/**"]});if(e.length===0){console.log(O.t("mcpResetProjectChoices.info.noFilesFound"));return}console.log(O.t("mcpResetProjectChoices.info.foundFiles",{count:e.length}));let r=0,n=0;for(let o of e){let s=Cii.relative(t,o);try{let a=Xtt.readFileSync(o,"utf8"),c;try{c=JSON.parse(a)}catch{console.log(O.t("mcpResetProjectChoices.info.invalidJson",{path:s}));continue}c.approvedServers||c.rejectedServers||c.mcpServerChoices?(Xtt.unlinkSync(o),console.log(O.t("mcpResetProjectChoices.info.fileDeleted",{path:s})),r++):console.log(O.t("mcpResetProjectChoices.info.noChoicesSkipping",{path:s}))}catch(a){console.log(O.t("mcpResetProjectChoices.errors.fileError",{path:s,error:a})),n++}}console.log(),console.log(O.t("mcpResetProjectChoices.info.summary")),console.log(O.t("mcpResetProjectChoices.info.deletedFiles",{count:r})),n>0&&console.log(O.t("mcpResetProjectChoices.info.errorFiles",{count:n})),r>0&&(console.log(),console.log(O.t("mcpResetProjectChoices.info.resetComplete")),console.log(O.t("mcpResetProjectChoices.info.extensionPrompt")))}catch(e){console.error(O.t("mcpResetProjectChoices.errors.searchError"),e)}}var Sii={command:"reset-project-choices",describe:O.t("mcpResetProjectChoices.description"),builder:t=>t.usage(O.t("mcpResetProjectChoices.usage")),handler:async()=>{await Eca()}};Gt();var xii={command:"mcp",describe:O.t("mcpCommand.description"),builder:t=>t.command(yii).command(_ii).command(Eii).command(vii).command(bii).command(Sii).demandCommand(1,O.t("mcpCommand.demandCommand")).version(!1),handler:()=>{}};Qer();Ger();_l();Gt();import kg from"fs/promises";import z5 from"path";import ola from"os";var sla=async(t,e=1,r=20)=>{try{if(!t)return{success:!1,message:O.t("workflowAdd.pleaseAuthenticate")};let o=await fetch("https://apis.iflow.cn/v1/workflows/list",{method:"POST",headers:{"User-Agent":"iFlow-Cli","Content-Type":"application/json"},body:JSON.stringify({page:e,size:r,usePage:!0})});if(!o.ok){let c=O.t("workflowAdd.unableToLoadWorkflows");return o.status===401?c=O.t("workflowAdd.authenticationFailed"):o.status===403?c=O.t("workflowAdd.accessDenied"):o.status===404?c=O.t("workflowAdd.serviceNotFound"):o.status>=500&&(c=O.t("workflowAdd.serverError")),{success:!1,message:c}}let s=await o.json();return s.success?{success:!0,workflows:Array.isArray(s.data.data)?s.data.data:[],total:s.data.total||0}:{success:!1,message:s.message||O.t("workflowAdd.failedToLoadFromServer")}}catch(n){let o=O.t("workflowAdd.connectionError");return n instanceof Error&&n.message.includes("Failed to fetch")&&(o=O.t("workflowAdd.networkError")),{success:!1,message:o}}},ala=async(t,e)=>{try{let r=await fetch(`https://apis.iflow.cn/v1/workflows/get/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);let n=await r.json();if(!n.success)throw new Error(n.message||O.t("workflowAdd.failedToFetchDetails"));return n.data||null}catch(r){return console.error(O.t("workflowAdd.failedToFetchDetails"),r),null}},cla=async(t,e)=>{let r=await fetch(t);if(!r.ok)throw new Error(`Failed to download file: ${r.status} ${r.statusText}`);let n=await r.arrayBuffer();await kg.writeFile(e,Buffer.from(n))},lla=t=>{let e=new URL(t).pathname;return z5.extname(e).toLowerCase()},ula=async t=>{let{exec:e}=await import("child_process"),{promisify:r}=await import("util"),n=r(e);try{let o=process.platform==="win32"?`where ${t}`:`which ${t}`;return await n(o),!0}catch{return!1}},dla=async(t,e)=>{let{exec:r}=await import("child_process"),{promisify:n}=await import("util"),o=n(r),s=process.platform==="win32",a=[];s?a.push({name:"Windows tar",command:`tar -xf "${t}" -C "${e}"`,check:"tar"},{name:"PowerShell",command:`powershell -Command "Expand-Archive -Path '${t}' -DestinationPath '${e}' -Force"`,check:"powershell"},{name:"7-Zip",command:`7z x "${t}" -o"${e}" -y`,check:"7z"},{name:"WinRAR",command:`winrar x "${t}" "${e}\\"`,check:"winrar"}):a.push({name:"unzip",command:`unzip -q "${t}" -d "${e}"`,check:"unzip"},{name:"tar",command:`tar -xf "${t}" -C "${e}"`,check:"tar"});let c=null;for(let d of a)try{if(d.check&&!await ula(d.check)){console.log(`\u23ED\uFE0F Skipping ${d.name} (not available)`);continue}console.log(`\u{1F527} Trying to extract with ${d.name}...`),await o(d.command),console.log(`\u2714 Successfully extracted using ${d.name}`);return}catch(f){console.log(`\u274C ${d.name} failed: ${f instanceof Error?f.message:String(f)}`),c=f instanceof Error?f:new Error(String(f))}let u=a.map(d=>d.name).join(", ");throw new Error(`Failed to extract ZIP file. Tried all available methods: ${u}. Last error: ${c?.message||"Unknown error"}. Please install one of: ${s?"7-Zip, WinRAR, or ensure PowerShell is available":"unzip or tar"}`)},fla=async(t,e,r)=>{try{switch(r){case".zip":await dla(t,e);break;case".tgz":case".tar.gz":case".tar":case".tar.bz2":case".tbz2":case".tar.xz":case".txz":{let{exec:n}=await import("child_process"),{promisify:o}=await import("util"),s=o(n),a;switch(r){case".tgz":case".tar.gz":a=`tar -xzf "${t}" -C "${e}"`;break;case".tar":a=`tar -xf "${t}" -C "${e}"`;break;case".tar.bz2":case".tbz2":a=`tar -xjf "${t}" -C "${e}"`;break;case".tar.xz":case".txz":a=`tar -xJf "${t}" -C "${e}"`;break;default:throw new Error(`Unsupported tar format: ${r}`)}await s(a);break}default:throw new Error(`Unsupported archive format: ${r}`)}}catch(n){throw new Error(`Failed to extract ${r} file. Original error: ${n}`)}},pla=async t=>{try{let e=await kg.readFile(t,{flag:"r"});if(e.length>=4){let r=e.readUInt32BE(0);return r===333319||r===333312}return!1}catch{return!1}},toi=async t=>{try{let e=await kg.readdir(t,{withFileTypes:!0});for(let r of e){let n=z5.join(t,r.name);if(r.isDirectory())await toi(n),r.name==="__MACOSX"&&await kg.rm(n,{recursive:!0,force:!0});else{let o=!1;(r.name===".DS_Store"||r.name.startsWith("._")&&await pla(n))&&(o=!0),o&&await kg.rm(n,{force:!0})}}}catch(e){console.warn(`Warning: Failed to clean up macOS files in ${t}: ${e}`)}},hla=async(t,e,r)=>{try{let n;try{n=JSON.parse(t.extInfo)}catch(u){return{success:!1,message:O.t("workflowAdd.invalidExtInfo",{error:u instanceof Error?u.message:String(u)})}}if(!n.url)return{success:!1,message:O.t("workflowAdd.noDownloadUrl")};let o=lla(n.url),s=await kg.mkdtemp(z5.join(ola.tmpdir(),"iflow-workflow-")),a=z5.join(s,`workflow${o}`),c=z5.join(s,"extracted");try{console.log(O.t("workflowAdd.downloading",{url:n.url})),await cla(n.url,a),console.log(O.t("workflowAdd.extracting")),await kg.mkdir(c,{recursive:!0}),await fla(a,c,o),await toi(c);let u=await mla(c);console.log(O.t("workflowAdd.copyingFiles"));let d=e||process.cwd(),f=await kg.readdir(c);for(let p of f){let h=z5.join(c,p),m=z5.join(d,p);(await kg.stat(h)).isDirectory()?(console.log(`Copying directory: ${h} -> ${m}`),await roi(h,m)):(console.log(`\u{1F4C4} Copying file: ${h} -> ${m}`),await kg.copyFile(h,m))}return u&&await gla(d),await kg.rm(s,{recursive:!0,force:!0}),{success:!0,message:O.t("workflowAdd.installSuccess",{workflowName:r,targetDir:d})}}catch(u){try{await kg.rm(s,{recursive:!0,force:!0})}catch{}throw u}}catch(n){let o=n instanceof Error?n.message:String(n);return{success:!1,message:O.t("workflowAdd.installFailed",{workflowName:r,error:o})}}},roi=async(t,e)=>{await kg.mkdir(e,{recursive:!0});let r=await kg.readdir(t,{withFileTypes:!0});for(let n of r){let o=z5.join(t,n.name),s=z5.join(e,n.name);n.isDirectory()?await roi(o,s):await kg.copyFile(o,s)}},mla=async t=>{let e=z5.join(t,"command_setup.sh");try{return await kg.access(e,kg.constants.F_OK),console.log("\u{1F50D} Detected command_setup.sh in workflow"),!0}catch{return!1}},gla=async t=>{let e=z5.join(t,"command_setup.sh");try{console.log("\u{1F527} Executing command_setup.sh..."),await kg.chmod(e,493);let{exec:r}=await import("child_process"),{promisify:n}=await import("util"),o=n(r),{stdout:s,stderr:a}=await o("bash command_setup.sh",{cwd:t,timeout:3e5});s&&(console.log("\u{1F4CB} Setup script output:"),console.log(s)),a&&(console.warn("\u26A0\uFE0F Setup script warnings:"),console.warn(a)),console.log("\u2714 command_setup.sh executed successfully")}catch(r){console.error("\u274C Failed to execute command_setup.sh:"),console.error(r instanceof Error?r.message:String(r)),console.warn("\u26A0\uFE0F Workflow installation completed but setup script failed"),console.warn("\u{1F4A1} Please manually execute command_setup.sh if needed")}};async function Ala(t){let r=yl(process.cwd()).merged.apiKey;r||(console.error(O.t("workflowAdd.apiKeyNotFound")),console.error(O.t("workflowAdd.pleaseAuthenticate")),process.exit(1)),console.log(O.t("workflowAdd.searching",{nameOrId:t}));try{let n=null;if(/^\d+$/.test(t)){let u=parseInt(t,10);n=await ala(r,u)}if(!n){let u=await sla(r,1,500);u.success||(console.error(O.t("workflowAdd.error",{error:u.message})),process.exit(1)),n=u.workflows?.find(d=>d.workflowId?.toLowerCase()===t.toLowerCase())||u.workflows?.[0]||null}n||(console.error(O.t("workflowAdd.notFoundInRepo",{nameOrId:t})),process.exit(1));let o=n.name||"Unknown";try{if(n.name){let u=JSON.parse(n.name);u.en&&(o=u.en)}}catch{}console.log(O.t("workflowAdd.foundWorkflow",{name:o}));let s=n.description||"No description available";try{if(n.description){let u=JSON.parse(n.description);u.en&&(s=u.en)}}catch{}console.log(O.t("workflowAdd.workflowDescription",{description:s})),console.log(O.t("workflowAdd.installing"));let a=process.cwd(),c=await hla(n,a,o);c.success?console.log(c.message):(console.error(c.message),process.exit(1))}catch(n){console.error(O.t("workflowAdd.errorAdding",{error:n})),process.exit(1)}}var noi={command:"add <name-or-id>",describe:O.t("workflowAdd.description"),builder:t=>t.usage(O.t("workflowAdd.usage")).positional("name-or-id",{describe:O.t("workflowAdd.workflowIdOrNumericIdOption"),type:"string",demandOption:!0}),handler:async t=>{await Ala(t["name-or-id"])}};Gt();var ioi={command:"workflow",describe:O.t("workflowCommand.description"),builder:t=>t.command(noi).demandCommand(1,O.t("workflowCommand.demandCommand")).version(!1),handler:()=>{}};var Her={debug:(...t)=>console.debug("[DEBUG]",...t),warn:(...t)=>console.warn("[WARN]",...t),error:(...t)=>console.error("[ERROR]",...t)};function _la(t){let e=[],r=new Set(["-p","--prompt"]);for(let n=0;n<t.length;n++){let o=t[n];if(r.has(o)&&n+1<t.length){let s=t[n+1];if(s.startsWith("-")){e.push(`${o}=${s}`),n++;continue}}e.push(o)}return e}async function nrt(){let t=_la(fm.argv),e=jti(BZt(t)).locale("en").scriptName("iflow").usage(`Usage: iflow [options] [command]
|
|
4501
4501
|
|
|
4502
4502
|
iFlow CLI - Launch an interactive CLI, use -p/--prompt for non-interactive mode`).command("$0 [query]","Launch iFlow CLI",o=>o.positional("query",{type:"string",description:"Optional query to process (equivalent to -p for non-interactive or -i for interactive mode)"}).option("model",{alias:"m",type:"string",description:"Model",default:fm.env.modelName||fm.env.MODELNAME||fm.env.MODEL_NAME||fm.env.model_name||fm.env.model||fm.env.MODEL}).option("prompt",{alias:"p",type:"string",description:"Prompt. Appended to input on stdin (if any)."}).option("prompt-interactive",{alias:"i",type:"string",description:"Execute the provided prompt and continue in interactive mode"}).option("continue",{alias:"c",type:"boolean",description:"Start the application and load the most recent conversation from current directory",default:!1}).option("resume",{alias:"r",description:"Resume conversation from a specific session file. If no session ID is provided, shows interactive session selector.",coerce:s=>s===!0?!0:s}).option("sandbox",{alias:"s",type:"boolean",description:"Run in sandbox?"}).option("sandbox-image",{type:"string",description:"Sandbox image URI."}).option("debug",{alias:"d",type:"boolean",description:"Run in debug mode?",default:!1}).option("all-files",{alias:["a"],type:"boolean",description:"Include ALL files in context?",default:!1}).option("all_files",{type:"boolean",description:"Include ALL files in context?",default:!1}).deprecateOption("all_files","Use --all-files instead. We will be removing --all_files in the coming weeks.").option("show-memory-usage",{type:"boolean",description:"Show memory usage in status bar",default:!1}).option("show_memory_usage",{type:"boolean",description:"Show memory usage in status bar",default:!1}).deprecateOption("show_memory_usage","Use --show-memory-usage instead. We will be removing --show_memory_usage in the coming weeks.").option("yolo",{alias:"y",type:"boolean",description:"Automatically accept all actions (aka YOLO mode, see https://www.youtube.com/watch?v=xvFZjo5PgG0 for more details)?",default:!0}).option("default",{type:"boolean",description:"Use default mode (manual approval for actions)"}).option("plan",{type:"boolean",description:"Use plan mode (planning without execution)"}).option("autoEdit",{type:"boolean",description:"Use auto-edit mode"}).option("telemetry",{type:"boolean",description:"Enable telemetry? This flag specifically controls if telemetry is sent. Other --telemetry-* flags set specific values but do not enable telemetry on their own."}).option("telemetry-target",{type:"string",choices:["local","gcp"],description:"Set the telemetry target (local or gcp). Overrides settings files."}).option("telemetry-otlp-endpoint",{type:"string",description:"Set the OTLP endpoint for telemetry. Overrides environment variables and settings files."}).option("telemetry-log-prompts",{type:"boolean",description:"Enable or disable logging of user prompts for telemetry. Overrides settings files."}).option("telemetry-outfile",{type:"string",description:"Redirect all telemetry output to the specified file."}).option("checkpointing",{type:"boolean",description:"Enables checkpointing of file edits",default:!0}).option("experimental-acp",{type:"boolean",description:"Starts the agent in ACP mode"}).option("port",{type:"number",description:"Port number for ACP server (used with --experimental-acp)"}).option("allowed-mcp-server-names",{type:"array",string:!0,description:"Allowed MCP server names"}).option("include-directories",{alias:"add-dir",type:"array",string:!0,description:"Additional directories to include in the workspace (comma-separated or multiple --include-directories)",coerce:s=>s.flatMap(a=>a.split(",").map(c=>c.trim()))}).option("max-turns",{type:"number",description:"Maximum number of model calls (assistant rounds) before terminating"}).option("max_turns",{type:"number",description:"Maximum number of model calls (assistant rounds) before terminating"}).deprecateOption("max_turns","Use --max-turns instead. We will be removing --max_turns in the coming weeks.").option("max-tokens",{type:"number",description:"Maximum total token usage (input + output) before terminating"}).option("max_tokens",{type:"number",description:"Maximum total token usage (input + output) before terminating"}).deprecateOption("max_tokens","Use --max-tokens instead. We will be removing --max_tokens in the coming weeks.").option("timeout",{type:"number",description:"Maximum execution time in seconds before terminating"}).option("output-file",{alias:"o",type:"string",description:"Output file path to save execution information (non-interactive mode only)"}).option("output_file",{type:"string",description:"Output file path to save execution information (non-interactive mode only)"}).deprecateOption("output_file","Use --output-file instead. We will be removing --output_file in the coming weeks.").check(s=>{if(s.prompt&&s.promptInteractive)throw new Error("Cannot use both --prompt (-p) and --prompt-interactive (-i) together");if(s.maxTurns!==void 0&&s.maxTurns!==null&&typeof s.maxTurns=="number"&&s.maxTurns<=0)throw new Error("--max-turns must be a positive number");if(s.max_turns!==void 0&&s.max_turns!==null&&typeof s.max_turns=="number"&&s.max_turns<=0)throw new Error("--max_turns must be a positive number");if(s.maxTokens!==void 0&&s.maxTokens!==null&&typeof s.maxTokens=="number"&&s.maxTokens<=0)throw new Error("--max-tokens must be a positive number");if(s.max_tokens!==void 0&&s.max_tokens!==null&&typeof s.max_tokens=="number"&&s.max_tokens<=0)throw new Error("--max_tokens must be a positive number");if(s.timeout!==void 0&&s.timeout!==null&&typeof s.timeout=="number"&&s.timeout<=0)throw new Error("--timeout must be a positive number");return!0})).command(xii).command(Uer).command(jer).command(ioi).strict().version(await aM()).alias("v","version").help().alias("h","help").demandCommand(0,0);e.wrap(e.terminalWidth());let r=await e.parse(),n=r.query||(r._&&r._.length>0&&r._[0]!==void 0&&r._[0]!==null?String(r._[0]):void 0);return n&&!r.prompt&&(r.promptInteractive===""||!!r.promptInteractive?r.promptInteractive=n:r.prompt=n),r._.length>0&&r._[0]==="mcp"&&fm.exit(0),r._.length>0&&r._[0]==="workflow"&&fm.exit(0),r}async function Ver(t,e,r,n,o=[],s="tree",a){let c=$er.realpathSync(qer.resolve(t)),u=$er.realpathSync(qer.resolve(yla())),f=c===u?"":t;return e&&Her.debug(`CLI: Delegating hierarchical memory load to server for CWD: ${t} (memoryImportFormat: ${s})`),T$(f,e,r,o,s,a,n.memoryDiscoveryMaxDirs)}async function TH(t,e,r,n,o=fm.cwd()){let s=n.debug||[fm.env.DEBUG,fm.env.DEBUG_MODE].some(S=>S==="true"||S==="1")||!1,a=t.memoryImportFormat||"tree",c=vri(e,n.extensions||[]),u=e.filter((S,w)=>c[w].isActive);t.contextFileName?cne(t.contextFileName):cne(lne());let d=u.flatMap(S=>S.contextFiles),f=new _$(o),p={...lie,...t.fileFiltering};i6t(t.errorLog);let{memoryContent:h,fileCount:m}=await Ver(o,s,f,t,d,a,p),g=Ela(t,u),A=vla(t,u),y=[];if(!n.allowedMcpServerNames){if(t.allowMCPServers){let S=new Set(t.allowMCPServers.filter(Boolean));S.size>0&&(g=Object.fromEntries(Object.entries(g).filter(([w])=>S.has(w))))}if(t.excludeMCPServers){let S=new Set(t.excludeMCPServers.filter(Boolean));S.size>0&&(g=Object.fromEntries(Object.entries(g).filter(([w])=>!S.has(w))))}}if(n.allowedMcpServerNames){let S=new Set(n.allowedMcpServerNames.filter(Boolean));S.size>0?g=Object.fromEntries(Object.entries(g).filter(([w,R])=>{let D=S.has(w);return D||y.push({name:w,extensionName:R.extensionName||""}),D})):(y.push(...Object.entries(g).map(([w,R])=>({name:w,extensionName:R.extensionName||""}))),g={})}let E=await Aii(t,n),v=new tp,b=!1;try{await v.initialize(),b=!0}catch(S){Her.error("History manager initialization failed. History features will be disabled.",S)}return new Gye({cna:t.cna,language:t.language,sessionId:r,embeddingModel:oJ,sandbox:E,targetDir:o||fm.cwd(),includeDirectories:t.includeDirectories||n.includeDirectories,debugMode:s,question:n.promptInteractive||n.prompt||"",fullContext:n.allFiles||n.all_files||!1,coreTools:t.coreTools||void 0,excludeTools:A,toolDiscoveryCommand:t.toolDiscoveryCommand,toolCallCommand:t.toolCallCommand,mcpServerCommand:t.mcpServerCommand,mcpServers:g,userMemory:h,geminiMdFileCount:m,approvalMode:t.approvalMode||(n.default?ii.DEFAULT:n.autoEdit?ii.AUTO_EDIT:n.plan?ii.PLAN:n.yolo?ii.YOLO:ii.DEFAULT),showMemoryUsage:n.showMemoryUsage||n.show_memory_usage||t.showMemoryUsage||!1,accessibility:t.accessibility,telemetry:{enabled:n.telemetry??t.telemetry?.enabled,target:n.telemetryTarget??t.telemetry?.target,otlpEndpoint:n.telemetryOtlpEndpoint??fm.env.OTEL_EXPORTER_OTLP_ENDPOINT??t.telemetry?.otlpEndpoint,logPrompts:n.telemetryLogPrompts??t.telemetry?.logPrompts,outfile:n.telemetryOutfile??t.telemetry?.outfile},usageStatisticsEnabled:t.usageStatisticsEnabled??!0,fileFiltering:{respectGitIgnore:t.fileFiltering?.respectGitIgnore,respectGeminiIgnore:t.fileFiltering?.respectGeminiIgnore,enableRecursiveFileSearch:t.fileFiltering?.enableRecursiveFileSearch},checkpointing:n.checkpointing!==void 0?n.checkpointing:t.checkpointing?.enabled??!0,maxCheckpoints:t.checkpointing?.maxCheckpoints??50,proxy:n.proxy||fm.env.HTTPS_PROXY||fm.env.https_proxy||fm.env.HTTP_PROXY||fm.env.http_proxy,cwd:o,fileDiscoveryService:f,bugCommand:t.bugCommand,model:n.model||t.modelName||Pd,extensionContextFilePaths:d,maxSessionTurns:n.maxTurns||n.max_turns||(t.maxSessionTurns??-1),experimentalAcp:n.experimentalAcp||!1,acpPort:n.port,listExtensions:n.listExtensions||!1,extensions:c,blockedMcpServers:y,noBrowser:!!fm.env.NO_BROWSER,summarizeToolOutput:t.toolSummarizationSettings,searchApiKey:t.searchApiKey,hookManager:t.hookManager??!0,compressionTokenThreshold:t.compressionTokenThreshold,useRipgrep:t.useRipgrep,maxTokens:n.maxTokens||n.max_tokens,timeout:n.timeout,tokensLimit:t.tokensLimit,skipNextSpeakerCheck:t.skipNextSpeakerCheck??!0,shellTimeout:t.shellTimeout,temperature:t.temperature,topP:t.topP,historyManager:b?v:void 0,isNonInteractive:!!n.prompt&&!n.promptInteractive&&!n.continue&&(!n.resume||typeof n.resume=="string")||n.experimentalAcp,disableTelemetry:t.disableTelemetry??!1,enableBuildInTask:t.enableBuildInTask,outputStyle:t.outputStyle,shouldUseNodePtyShell:t.enableInteractiveShell??!1,hasIdeOnboardingBeenShown:t.hasIdeOnboardingBeenShown})}function Ela(t,e){let r={...t.mcpServers||{}};for(let n of e)Object.entries(n.config.mcpServers||{}).forEach(([o,s])=>{if(r[o]){Her.warn(`Skipping extension MCP config for server with key "${o}" as it already exists.`);return}r[o]={...s,extensionName:n.config.name}});return r}function vla(t,e){let r=new Set(t.excludeTools||[]);for(let n of e)for(let o of n.config.excludeTools||[])r.add(o);return[...r]}Gt();import{promises as bla}from"fs";import{join as Cla}from"path";var Sla=[];function j6e(t){Sla.push(t)}async function ooi(){let t=n1(process.cwd()),e=Cla(t,"checkpoints");try{await bla.rm(e,{recursive:!0,force:!0})}catch{}}import{EventEmitter as xla}from"events";var qs=new xla;qs.setMaxListeners(20);Gt();Gt();import*as fae from"fs";import*as irt from"path";function ort(t,e){let r=process.argv[1];if(!r)return{packageManager:"unknown",isGlobal:!1};try{let n=fae.realpathSync(r).replace(/\\/g,"/"),o=t?.replace(/\\/g,"/");if(Nu(process.cwd())&&o&&n.startsWith(o)&&!n.includes("/node_modules/"))return{packageManager:"unknown",isGlobal:!1,updateMessage:'Running from a local git clone. Please update with "git pull".'};if(n.includes("/.npm/_npx")||n.includes("/npm/_npx"))return{packageManager:"npx",isGlobal:!1,updateMessage:"Running via npx, update not applicable."};if(n.includes("/.pnpm/_pnpx"))return{packageManager:"pnpx",isGlobal:!1,updateMessage:"Running via pnpx, update not applicable."};if(n.includes("/.pnpm/global")){let u="pnpm add -g @iflow-ai/iflow-cli@latest";return{packageManager:"pnpm",isGlobal:!0,updateCommand:u,updateMessage:e?`Please run ${u} to update`:"Installed with pnpm. Attempting to automatically update now..."}}if(n.includes("/.yarn/global")){let u="yarn global add @iflow-ai/iflow-cli@latest";return{packageManager:"yarn",isGlobal:!0,updateCommand:u,updateMessage:e?`Please run ${u} to update`:"Installed with yarn. Attempting to automatically update now..."}}if(n.includes("/.bun/install/cache"))return{packageManager:"bunx",isGlobal:!1,updateMessage:"Running via bunx, update not applicable."};if(n.includes("/.bun/bin")){let u="bun add -g @iflow-ai/iflow-cli@latest";return{packageManager:"bun",isGlobal:!0,updateCommand:u,updateMessage:e?`Please run ${u} to update`:"Installed with bun. Attempting to automatically update now..."}}if(o&&n.startsWith(`${o}/node_modules`)){let u="npm";return fae.existsSync(irt.join(t,"yarn.lock"))?u="yarn":fae.existsSync(irt.join(t,"pnpm-lock.yaml"))?u="pnpm":fae.existsSync(irt.join(t,"bun.lockb"))&&(u="bun"),{packageManager:u,isGlobal:!1,updateMessage:"Locally installed. Please update via your project's package.json."}}let c="global"==="aone"?"npm install -g @ali/iflow-cli@latest":"npm install -g @iflow-ai/iflow-cli@latest";return{packageManager:"npm",isGlobal:!0,updateCommand:c,updateMessage:e?O.t("autoUpdate.fallback",{updateCommand:c}):O.t("autoUpdate.installWithNpm")}}catch(n){return console.log(n),{packageManager:"unknown",isGlobal:!1}}}import{EventEmitter as wla}from"events";var Bg=new wla;Ps();import{spawn as Tla}from"child_process";var srt=Tla;function soi(t,e,r,n=srt){if(!t)return;let o=ort(r,e.merged.disableAutoUpdate??!1),s=t.message;if(o.updateMessage&&(s+=`
|
|
4503
4503
|
${o.updateMessage}`),Bg.emit("update-received",{message:s}),!o.updateCommand||e.merged.disableAutoUpdate)return;let a=t.update.latest.includes("nightly"),c=t.update.latest.includes("beta"),u=o.updateCommand.replace("@latest",a?"@nightly":c?"@beta":`@${t.update.latest}`),d=n(u,{stdio:"pipe",shell:!0}),f="";return d.stderr.on("data",p=>{f+=p.toString()}),d.on("close",p=>{p===0?Bg.emit("update-success",{message:"Update successful! The new version will be used on your next run."}):Bg.emit("update-failed",{message:`Automatic update failed. Please try updating manually. (command: ${u}, stderr: ${f.trim()})`})}),d.on("error",p=>{Bg.emit("update-failed",{message:`Automatic update failed. Please try updating manually. (error: ${p.message})`})}),d}function Wer(t,e){let r=!1,n=c=>{e(c);let u=c.message;setTimeout(()=>{r||t({type:"info",text:u},Date.now()),e(null)},6e4)},o=()=>{e(null),t({type:"error",text:O.t("autoUpdate.failed")},Date.now())},s=()=>{r=!0,e(null),t({type:"info",text:O.t("autoUpdate.ok")},Date.now())},a=c=>{t({type:"info",text:c.message},Date.now())};return Bg.on("update-received",n),Bg.on("update-failed",o),Bg.on("update-success",s),Bg.on("update-info",a),()=>{Bg.off("update-received",n),Bg.off("update-failed",o),Bg.off("update-success",s),Bg.off("update-info",a)}}Rn();var W0=Ie(rr(),1);await Zr();Rn();var gae=Ie(rr(),1);await Zr();var $oi=Ie(rr(),1);await Zr();var Y5=Ie(rr(),1);import drt from"node:readline";import{PassThrough as jla}from"node:stream";var Yer="[99;5u";var Goi=Ie(Pt(),1);var Poi="\x1B[I",Moi="\x1B[O",n4="\x1B",Foi=`${n4}[200~`,Loi=`${n4}[201~`,Uoi=(0,Y5.createContext)(void 0);function Qoi(){let t=(0,Y5.useContext)(Uoi);if(!t)throw new Error("useKeypressContext must be used within a KeypressProvider");return t}function joi({children:t,kittyProtocolEnabled:e,config:r,debugKeystrokeLogging:n}){let{stdin:o,setRawMode:s}=TS(),a=(0,Y5.useRef)(new Set).current,c=(0,Y5.useCallback)(d=>{a.add(d)},[a]),u=(0,Y5.useCallback)(d=>{a.delete(d)},[a]);return(0,Y5.useEffect)(()=>{let d=o.isRaw;d===!1&&s(!0);let f=new jla,p=!1;(parseInt(process.versions.node.split(".")[0],10)<20||process.env.PASTE_WORKAROUND==="1"||process.env.PASTE_WORKAROUND==="true")&&(p=!0);let m=!1,g=Buffer.alloc(0),A="",y=null,E=!1,v=0,b=null,S=null,w=null,R=G=>{let Q=new RegExp(`^${n4}\\[Z`),V=G.match(Q);if(V)return{key:{name:"tab",ctrl:!1,meta:!1,shift:!0,paste:!1,sequence:G.slice(0,V[0].length),kittyProtocol:!0},length:V[0].length};let H=new RegExp(`^${n4}\\[1;(\\d+)Z`);if(V=G.match(H),V){let J=parseInt(V[1],10);J>=128&&(J-=128);let X=J-1,le=(X&2)===2;return{key:{name:"tab",ctrl:(X&4)===4,meta:le,shift:!0,paste:!1,sequence:G.slice(0,V[0].length),kittyProtocol:!0},length:V[0].length}}let L=new RegExp(`^${n4}\\[1;(\\d+)([ABCDHFPQSR])`);if(V=G.match(L),V){let J=parseInt(V[1],10);J>=128&&(J-=128);let X=J-1,le=(X&1)===1,Se=(X&2)===2,ue=(X&4)===4,Ce=V[2],ie={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"}[Ce]||"";return ie?{key:{name:ie,ctrl:ue,meta:Se,shift:le,paste:!1,sequence:G.slice(0,V[0].length),kittyProtocol:!0},length:V[0].length}:null}let K=new RegExp(`^${n4}\\[(\\d+)(;(\\d+))?([u~])`);if(V=G.match(K),V){let J=parseInt(V[1],10),X=V[3]?parseInt(V[3],10):1;X>=128&&(X-=128);let le=X-1,Se=(le&1)===1,ue=(le&2)===2,Ce=(le&4)===4;if(V[4]==="~"){let ye=null;switch(J){case 1:ye="home";break;case 2:ye="insert";break;case 3:ye="delete";break;case 4:ye="end";break;case 5:ye="pageup";break;case 6:ye="pagedown";break;default:break}if(ye)return{key:{name:ye,ctrl:Ce,meta:ue,shift:Se,paste:!1,sequence:G.slice(0,V[0].length),kittyProtocol:!0},length:V[0].length}}let ae={27:"escape",9:"tab",127:"backspace",13:"return",57414:"return"}[J];if(ae)return{key:{name:ae,ctrl:Ce,meta:ue,shift:Se,paste:!1,sequence:G.slice(0,V[0].length),kittyProtocol:!0},length:V[0].length};if(Ce&&J>=97&&J<=122)return{key:{name:String.fromCharCode(J),ctrl:!0,meta:ue,shift:Se,paste:!1,sequence:G.slice(0,V[0].length),kittyProtocol:!0},length:V[0].length}}let Y=new RegExp(`^${n4}\\[([ABCDHF])`);if(V=G.match(Y),V){let J=V[1];return{key:{name:{A:"up",B:"down",C:"right",D:"left",H:"home",F:"end"}[J],ctrl:!1,meta:!1,shift:!1,paste:!1,sequence:G.slice(0,V[0].length),kittyProtocol:!0},length:V[0].length}}return null},D=G=>{for(let Q of a)Q(G)},M=(G,Q)=>{if(Q.name==="paste-start"){m=!0,w=performance.now();return}if(Q.name==="paste-end"){m=!1;let H=g.toString(),L=performance.now(),K=w?L-w:0;D({name:"",ctrl:!1,meta:!1,shift:!1,paste:!0,sequence:H,...w&&{pasteDuration:K,pasteTextLength:H.length}}),g=Buffer.alloc(0),w=null;return}if(m){g=Buffer.concat([g,Buffer.from(Q.sequence)]);return}b&&Q.name!=="return"&&(S&&(clearTimeout(S),S=null),D({...b,shift:!0}),b=null);let V=Date.now();if(Q.name==="return"&&v>0&&!E)if(V-v<30)Q.shift=!0;else{b={...Q,paste:m},S=setTimeout(()=>{b&&(D(b),b=null),S=null},30),v=V;return}if(v=V,["up","down","left","right"].includes(Q.name)){D(Q);return}if(Q.ctrl&&Q.name==="c"||Q.sequence===`${n4}${Yer}`){A&&n&&console.log("[DEBUG] Kitty buffer cleared on Ctrl+C:",A),A="",Q.sequence===`${n4}${Yer}`?D({name:"c",ctrl:!0,meta:!1,shift:!1,paste:!1,sequence:Q.sequence,kittyProtocol:!0}):D(Q);return}if(e&&(A||Q.sequence.startsWith(`${n4}[`)&&!Q.sequence.startsWith(Foi)&&!Q.sequence.startsWith(Loi)&&!Q.sequence.startsWith(Poi)&&!Q.sequence.startsWith(Moi))){A+=Q.sequence,n&&console.log("[DEBUG] Kitty buffer accumulating:",A);let H=!1;for(;A;){let L=R(A);if(!L){let K=A.indexOf(`${n4}[`,1);if(K>0){n&&console.log("[DEBUG] Skipping incomplete/invalid CSI prefix:",A.slice(0,K)),A=A.slice(K);continue}break}if(n){let K=A.slice(0,L.length);A.length>L.length?console.log("[DEBUG] Kitty sequence parsed successfully (prefix):",K):console.log("[DEBUG] Kitty sequence parsed successfully:",K)}A=A.slice(L.length),D(L.key),H=!0}if(H)return;if(r?.getDebugMode()||n){let L=Array.from(A).map(K=>K.charCodeAt(0));console.warn("Kitty sequence buffer has char codes:",L)}if(A.length>32)n&&console.log("[DEBUG] Kitty buffer overflow, clearing:",A),A="";else return}Q.name==="return"&&Q.sequence===`${n4}\r`&&(Q.meta=!0),D({...Q,paste:m})},I=null,N=40,B=null,j=(G,Q)=>{if(!(Q.sequence===Poi||Q.sequence===Moi)){if(I)clearTimeout(I),I=null,!m&&B&&(w=performance.now(),g=Buffer.concat([g,Buffer.from(B.sequence)]),m=!0),I=setTimeout(()=>{m&&(D({name:"",ctrl:!1,meta:!1,shift:!1,paste:!0,sequence:g.toString(),...w&&{pasteDuration:performance.now()-w,pasteTextLength:g.length}}),g=Buffer.alloc(0),w=null,m=!1,B=null,I=null)},N);else{if(m||Q.ctrl||Q.meta||Q.name==="paste-start"||Q.name==="paste-end"||Q.name==="backspace"||Q.name==="delete"||Q.name==="left"||Q.name==="right"||Q.name==="up"||Q.name==="down"){M(G,Q);return}if(Q.name==="return"&&E){y&&(clearTimeout(y),y=null),E=!1,D({...Q,shift:!0,sequence:"\r"});return}if(Q.sequence==="\\"&&!Q.name){E=!0,y=setTimeout(()=>{E=!1,y=null,D(Q)},5);return}E&&Q.name!=="return"&&(y&&(clearTimeout(y),y=null),E=!1,D({name:"",sequence:"\\",ctrl:!1,meta:!1,shift:!1,paste:!1})),B=Q,I=setTimeout(()=>{B&&(M(G,B),B=null),I=null},N);return}M(G,Q)}},U=G=>{let Q=Buffer.from(Foi),V=Buffer.from(Loi),H=0;for(;H<G.length;){let L=G.indexOf(Q,H),K=G.indexOf(V,H),Y=L!==-1&&(K===-1||L<K),J=K!==-1&&(L===-1||K<L),X=-1,le=0;if(Y?X=L:J&&(X=K),le=V.length,X===-1){f.write(G.slice(H));return}let Se=G.slice(H,X);Se.length>0&&f.write(Se);let ue=Ce=>({name:Ce,ctrl:!1,meta:!1,shift:!1,paste:!1,sequence:""});Y?M(void 0,ue("paste-start")):J&&M(void 0,ue("paste-end")),H=X+le}},k;return p?(k=drt.createInterface({input:f,escapeCodeTimeout:0}),drt.emitKeypressEvents(f,k),f.on("keypress",j),o.on("data",U)):(k=drt.createInterface({input:o,escapeCodeTimeout:0}),drt.emitKeypressEvents(o,k),o.on("keypress",j)),()=>{p?(f.removeListener("keypress",j),o.removeListener("data",U)):o.removeListener("keypress",j),k.close(),d===!1&&s(!1),y&&(clearTimeout(y),y=null),S&&(clearTimeout(S),S=null),I&&(clearTimeout(I),I=null),m&&(D({name:"",ctrl:!1,meta:!1,shift:!1,paste:!0,sequence:g.toString()}),g=Buffer.alloc(0))}},[o,s,e,r,a,n]),(0,Goi.jsx)(Uoi.Provider,{value:{subscribe:c,unsubscribe:u},children:t})}function Tn(t,{isActive:e}){let{subscribe:r,unsubscribe:n}=Qoi();(0,$oi.useEffect)(()=>{if(e)return r(t),()=>{n(t)}},[e,t,r,n])}Rn();fi();var i4=Ie(Pt(),1);function Gla(t,e){switch(e.type){case"insert":{let r=e.payload,n=Array.from(t.value),o=Array.from(r);n.splice(t.cursorPosition,0,...o);let s=n.join(""),a=Array.from(r).length;return{value:s,cursorPosition:t.cursorPosition+a}}case"backspace":{if(t.cursorPosition>0){let r=Array.from(t.value);return r.splice(t.cursorPosition-1,1),{value:r.join(""),cursorPosition:t.cursorPosition-1}}return t}case"delete":{let r=Array.from(t.value).length;if(t.cursorPosition<r){let n=Array.from(t.value);return n.splice(t.cursorPosition,1),{value:n.join(""),cursorPosition:t.cursorPosition}}return t}case"move_cursor":{let r=Array.from(t.value).length,n=Math.max(0,Math.min(r,t.cursorPosition+e.payload));return{...t,cursorPosition:n}}case"set_cursor":{let r=Array.from(t.value).length,n=Math.max(0,Math.min(r,e.payload));return{...t,cursorPosition:n}}case"set_value":return{value:e.payload,cursorPosition:Array.from(e.payload).length};default:return t}}function LE({onSubmit:t,onCancel:e,placeholder:r,label:n,isFocused:o=!0,defaultValue:s="",allowEmpty:a=!1}){let{t:c}=fr(),u=r||c("textInput.defaultPlaceholder"),d=n||c("textInput.defaultLabel"),[f,p]=(0,gae.useReducer)(Gla,{value:s,cursorPosition:s.length}),{value:h,cursorPosition:m}=f,[g,A]=(0,gae.useState)(!0);(0,gae.useEffect)(()=>{if(!o)return;let v=setInterval(()=>{A(b=>!b)},500);return()=>clearInterval(v)},[o]),Tn(v=>{if(v.name==="return"||v.name==="enter"){(h.trim()||a)&&t(h.trim());return}if(v.name==="escape"){e?.();return}if(!(v.name==="up"||v.name==="down")){if(v.name==="left"){p({type:"move_cursor",payload:-1});return}if(v.name==="right"){p({type:"move_cursor",payload:1});return}if(v.name==="backspace"){p({type:"backspace"});return}if(v.name==="delete"){p({type:"delete"});return}if(v.paste&&v.sequence){let b=v.sequence.split("").filter(S=>{let w=S.charCodeAt(0);return w>=32&&w!==127}).join("");b&&p({type:"insert",payload:b});return}if(v.sequence&&!v.ctrl&&!v.meta){let b=v.sequence;b.split("").some(w=>{let R=w.charCodeAt(0);return R<32||R===127})||p({type:"insert",payload:b})}}},{isActive:o});let y=g&&o?"\u2502":"",E=h?(()=>{let v=Array.from(h);return v.splice(m,0,y),v.join("")})():y;return(0,i4.jsxs)(fe,{flexDirection:"column",children:[(0,i4.jsx)(fe,{children:(0,i4.jsxs)(ne,{color:me.Gray,children:[d," "]})}),(0,i4.jsx)(fe,{marginTop:1,children:(0,i4.jsx)(fe,{borderStyle:"round",borderColor:o?me.AccentBlue:me.Gray,paddingX:1,width:"100%",children:h?(0,i4.jsx)(ne,{children:E}):(0,i4.jsxs)(ne,{children:[(0,i4.jsx)(ne,{color:me.Gray,children:u}),y]})})}),(0,i4.jsx)(fe,{marginTop:1,children:(0,i4.jsx)(ne,{color:me.Gray,dimColor:!0,children:c("textInput.instructions")})})]})}fi();var dr=Ie(Pt(),1);var qoi=(0,W0.memo)(({config:t,onExit:e,onStatusUpdate:r})=>{let{t:n}=fr(),[o,s]=(0,W0.useState)("location"),[a,c]=(0,W0.useState)(0),[u,d]=(0,W0.useState)({}),[f,p]=(0,W0.useState)(null),[h,m]=(0,W0.useState)(null),[g,A]=(0,W0.useState)(!1),[y,E]=(0,W0.useState)([]),[v,b]=(0,W0.useState)([]),[S,w]=(0,W0.useState)(""),[R,D]=(0,W0.useState)(null),[M,I]=(0,W0.useState)("");(0,W0.useEffect)(()=>{(async()=>{try{let ie=await t.getToolRegistry();if(ie){let oe=["task","exit_plan_mode","save_memory"],q=ie.getAllTools().filter(z=>{let Ee="serverName"in z&&z.serverName!==void 0,Ae=oe.filter(_e=>_e===z.name).length>0;return!Ee&&!Ae}).map(z=>z.name);E(q),d(z=>({...z,selectedTools:q}))}let ae=t.getMcpServers()||{},ye=Object.keys(ae);b(ye),d(oe=>({...oe,selectedMcps:ye}))}catch(ie){console.error("Failed to initialize data:",ie)}})()},[t]);let B={location:{name:"location",title:n("agentInstallDialog.locationTitle"),description:n("agentInstallDialog.locationDescription"),type:"select",options:[{id:"project",title:n("agentInstallDialog.projectAgent"),description:n("agentInstallDialog.projectAgentDesc"),available:!0},{id:"user",title:n("agentInstallDialog.userAgent"),description:n("agentInstallDialog.userAgentDesc"),available:!0}]},method:{name:"method",title:n("agentInstallDialog.methodTitle"),description:n("agentInstallDialog.methodDescription"),type:"select",options:[{id:"iFlow",title:n("agentInstallDialog.generateWithIFlow"),description:n("agentInstallDialog.generateWithIFlowDesc"),available:!0},{id:"template",title:n("agentInstallDialog.manualConfig"),description:n("agentInstallDialog.manualConfigDesc"),available:!0},{id:"online",title:n("agentInstallDialog.fromOnlineRepo"),description:n("agentInstallDialog.fromOnlineRepoDesc"),available:!0}]},agentGoal:{name:"agentGoal",title:n("agentInstallDialog.agentGoalTitle"),description:n("agentInstallDialog.agentGoalDescription"),type:"input",placeholder:n("agentInstallDialog.agentGoalPlaceholder")},agentType:{name:"agentType",title:n("agentInstallDialog.agentTypeTitle"),description:n("agentInstallDialog.agentTypeDescription"),type:"input",placeholder:n("agentInstallDialog.agentTypePlaceholder")},systemPrompt:{name:"systemPrompt",title:n("agentInstallDialog.systemPromptTitle"),description:n("agentInstallDialog.systemPromptDescription"),type:"input",placeholder:n("agentInstallDialog.systemPromptPlaceholder")},description:{name:"description",title:n("agentInstallDialog.descriptionTitle"),description:n("agentInstallDialog.descriptionDescription"),type:"input",placeholder:n("agentInstallDialog.descriptionPlaceholder")},tools:{name:"tools",title:n("agentInstallDialog.toolsTitle"),description:n("agentInstallDialog.toolsDescription"),type:"multiselect",options:y.map(Z=>({id:Z,title:Z,description:n("agentInstallDialog.allowAccessTo",{tool:Z}),available:!0}))},mcps:{name:"mcps",title:n("agentInstallDialog.mcpsTitle"),description:n("agentInstallDialog.mcpsDescription"),type:"multiselect",options:v.map(Z=>({id:Z,title:Z,description:n("agentInstallDialog.allowMcpAccess",{mcp:Z}),available:!0}))},color:{name:"color",title:n("agentInstallDialog.colorTitle"),description:n("agentInstallDialog.colorDescription"),type:"select",options:[{id:"automatic",title:n("agentInstallDialog.automaticColor"),description:n("agentInstallDialog.automaticColorDesc"),available:!0},{id:"red",title:n("agentInstallDialog.red"),description:"",available:!0},{id:"blue",title:n("agentInstallDialog.blue"),description:"",available:!0},{id:"green",title:n("agentInstallDialog.green"),description:"",available:!0},{id:"yellow",title:n("agentInstallDialog.yellow"),description:"",available:!0},{id:"purple",title:n("agentInstallDialog.purple"),description:"",available:!0},{id:"orange",title:n("agentInstallDialog.orange"),description:"",available:!0},{id:"pink",title:n("agentInstallDialog.pink"),description:"",available:!0},{id:"cyan",title:n("agentInstallDialog.cyan"),description:"",available:!0}]},"generated-preview":{name:"generated-preview",title:n("agentInstallDialog.generatedPreviewTitle"),description:n("agentInstallDialog.generatedPreviewDescription"),type:"edit",options:[{id:"agentType",title:n("agentInstallDialog.agentTypeLabel"),description:`${u.agentType||n("agentInstallDialog.notSet")}`,available:!0},{id:"description",title:n("agentInstallDialog.descriptionLabel"),description:`${u.description||n("agentInstallDialog.notSet")}`,available:!0},{id:"systemPrompt",title:n("agentInstallDialog.systemPromptLabel"),description:`${u.systemPrompt?u.systemPrompt.length>600?u.systemPrompt.substring(0,600)+"...":u.systemPrompt:n("agentInstallDialog.notSet")}`,available:!0}]},preview:{name:"preview",title:n("agentInstallDialog.previewTitle"),description:n("agentInstallDialog.previewDescription"),type:"preview"},generating:null,installing:null,success:null,error:null}[o],j=B?.options?.filter(Z=>Z.available)||[];(0,W0.useEffect)(()=>{c(0),p(null),A(!1),D(null),I("")},[o]);let U=Z=>{let ie=["location","method","agentType","systemPrompt","description","tools","mcps","color","preview"],ae=["location","method","agentGoal","generating","generated-preview","tools","mcps","color","preview"];if(Z==="method")return u.method==="template"?"agentType":u.method==="iFlow"?"agentGoal":null;let ye=u.method==="iFlow"?ae:ie,oe=ye.indexOf(Z);return oe<ye.length-1?ye[oe+1]:null},k=Z=>{let ie=["location","method","agentType","systemPrompt","description","tools","mcps","color","preview"],ae=["location","method","agentGoal","generating","generated-preview","tools","mcps","color","preview"],ye=u.method==="iFlow"?ae:ie,oe=ye.indexOf(Z);return oe>0?ye[oe-1]:null},G=()=>{switch(o){case"agentGoal":return u.agentGoal||"";case"agentType":return u.agentType||"";case"systemPrompt":return u.systemPrompt||"";case"description":return u.description||"";default:return""}},Q=Z=>{if(o==="agentGoal"){if(d(ae=>({...ae,agentGoal:Z})),u.method==="iFlow"){K(Z);return}}else o==="agentType"?d(ae=>({...ae,agentType:Z})):o==="systemPrompt"?d(ae=>({...ae,systemPrompt:Z})):o==="description"&&d(ae=>({...ae,description:Z}));A(!1);let ie=U(o);ie&&(s(ie),c(0))},V=()=>{A(!1),D(null),I("")},H=Z=>{R==="agentType"?d(ie=>({...ie,agentType:Z})):R==="description"?d(ie=>({...ie,description:Z})):R==="systemPrompt"&&d(ie=>({...ie,systemPrompt:Z})),D(null),I("")},L=()=>{D(null),I("")},K=async Z=>{try{s("generating"),p(null),r?.(n("agentInstallDialog.generatingFromGoal"));let{generateAgentConfig:ie}=await Promise.resolve().then(()=>(Gt(),By)),ae=await ie(t,{agentGoal:Z,onProgress:ye=>{w(ye),r?.(ye)}});d(ye=>({...ye,agentType:ae.identifier,systemPrompt:ae.systemPrompt,description:ae.whenToUse})),s("generated-preview"),c(0),r?.(n("agentInstallDialog.generatedSuccessfully"))}catch(ie){s("error");let ae=ie instanceof Error?ie.message:String(ie);p(n("agentInstallDialog.failedToGenerate",{error:ae})),r?.(n("agentInstallDialog.failedGenerateStatus",{error:ae}))}},Y=async()=>{try{s("installing"),r?.(n("agentInstallDialog.creatingAgent",{agentType:u.agentType}));let{createAgent:Z}=await Promise.resolve().then(()=>(Gt(),By)),ie={agentType:u.agentType,name:u.agentType,description:u.description,whenToUse:u.description,allowedTools:u.selectedTools?.length?u.selectedTools:["*"],allowedMcps:u.selectedMcps?.length?u.selectedMcps:void 0,systemPrompt:u.systemPrompt,location:u.location==="user"?"global":"project",isInheritTools:!0,isInheritMcps:!0},ae=await Z(ie);s("success"),m(n("agentInstallDialog.successfullyCreated",{agentType:u.agentType,filePath:ae})),r?.(n("agentInstallDialog.agentCreatedSuccess",{agentType:u.agentType})),setTimeout(()=>{e()},3e3)}catch(Z){s("error");let ie=Z instanceof Error?Z.message:String(Z);p(n("agentInstallDialog.failedToCreate",{error:ie})),r?.(n("agentInstallDialog.failedCreateStatus",{error:ie}))}},J=()=>{let Z=B;if(!Z)return;if(Z.type==="select"){let ae=j[a];if(ae)if(o==="location")d(ye=>({...ye,location:ae.id}));else if(o==="method"){let ye=ae.id;if(d(pe=>({...pe,method:ye})),ye==="online"){m(n("agentInstallDialog.redirectingToOnline")),r?.(n("agentInstallDialog.useAgentsOnline")),setTimeout(()=>{e()},2e3);return}let oe=null;ye==="template"?oe="agentType":ye==="iFlow"&&(oe="agentGoal"),oe&&(s(oe),c(0),A(!1),p(null));return}else o==="color"&&d(ye=>({...ye,color:ae.id}))}else if(Z.type==="input"){if(!g){A(!0);return}}else if(Z.type==="multiselect")if(a===0){let ae=U(o);ae&&(s(ae),c(0),A(!1),p(null));return}else{let ae=j[a-1];if(o==="tools"){let ye=u.selectedTools||[],oe=ye.includes(ae.id);d(oe?pe=>({...pe,selectedTools:ye.filter(he=>he!==ae.id)}):pe=>({...pe,selectedTools:[...ye,ae.id]}))}else if(o==="mcps"){let ye=u.selectedMcps||[],oe=ye.includes(ae.id);d(oe?pe=>({...pe,selectedMcps:ye.filter(he=>he!==ae.id)}):pe=>({...pe,selectedMcps:[...ye,ae.id]}))}return}else if(Z.type==="edit"){if(R)return;if(a===0){let ae=U(o);ae&&(s(ae),c(0),A(!1),p(null))}else{let ae=j[a-1];D(ae.id);let ye="";ae.id==="agentType"?ye=u.agentType||"":ae.id==="description"?ye=u.description||"":ae.id==="systemPrompt"&&(ye=u.systemPrompt||""),I(ye)}return}else if(Z.type==="preview"){Y();return}let ie=U(o);ie&&(s(ie),c(0),A(!1),p(null))},X=()=>{if(g){A(!1);return}if(R){D(null),I("");return}let Z=k(o);Z?(s(Z),c(0),p(null)):e()};Tn(Z=>{if(g||R)return;if(Z.name==="escape"){X();return}if(Z.sequence==="q"){e();return}let ie=B;if(ie){if(ie.type==="select"||ie.type==="multiselect"||ie.type==="edit"){let ae=ie.type==="multiselect"||ie.type==="edit"?j.length:j.length-1;Z.name==="up"||Z.sequence==="k"?c(ye=>Math.max(0,ye-1)):Z.name==="down"||Z.sequence==="j"?c(ye=>Math.min(ae,ye+1)):Z.name==="return"&&J()}else if(ie.type==="input")Z.name==="return"&&J();else if(ie.type==="preview"){if(Z.name==="up"||Z.name==="down"||Z.sequence==="k"||Z.sequence==="j")return;Z.name==="return"&&J()}}},{isActive:!0});let le=()=>{if(u.method==="online"){let oe=["location","method"],pe=oe.indexOf(o);return(0,dr.jsxs)(fe,{marginBottom:1,children:[(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.stepOf",{current:pe+1,total:oe.length})}),(0,dr.jsx)(fe,{marginLeft:2,children:(0,dr.jsx)(ne,{color:me.Gray,children:oe.map((he,q)=>q<pe?"\u2713 ":q===pe?"\u25CF ":"\u25CB ").join("")})})]})}let Z=["location","method","agentType","systemPrompt","description","tools","mcps","color","preview"],ie=["location","method","agentGoal","generating","generated-preview","tools","mcps","color","preview"],ae=u.method==="iFlow"?ie:Z,ye=ae.indexOf(o);return(0,dr.jsxs)(fe,{marginBottom:1,children:[(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.stepOf",{current:ye+1,total:ae.length})}),(0,dr.jsx)(fe,{marginLeft:2,children:(0,dr.jsx)(ne,{color:me.Gray,children:ae.map((oe,pe)=>pe<ye?"\u2713 ":pe===ye?"\u25CF ":"\u25CB ").join("")})})]})},Se=()=>{if(R){let Z={agentType:n("agentInstallDialog.agentTypeLabel"),description:n("agentInstallDialog.descriptionLabel"),systemPrompt:n("agentInstallDialog.systemPromptLabel")};return(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:me.AccentCyan,children:n("agentInstallDialog.editField",{field:Z[R]})}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.modifyField",{field:R})})}),(0,dr.jsx)(fe,{marginTop:2,children:(0,dr.jsx)(LE,{onSubmit:H,onCancel:L,placeholder:n("agentInstallDialog.enterField",{field:R}),label:Z[R],defaultValue:M,isFocused:!0})})]})}return(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:me.AccentCyan,children:n("agentInstallDialog.generatedPreviewTitle")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.generatedPreviewDescription")})}),(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[(0,dr.jsxs)(fe,{marginBottom:2,flexDirection:"column",children:[(0,dr.jsx)(fe,{flexDirection:"row",children:(0,dr.jsxs)(ne,{color:a===0?me.AccentCyan:void 0,children:[a===0?"> ":" ",n("agentInstallDialog.continueToToolsSelection")]})}),(0,dr.jsx)(fe,{marginLeft:4,children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.proceedToNextStep")})})]},"continue"),j.map((Z,ie)=>{let ye=ie+1===a;return(0,dr.jsxs)(fe,{marginBottom:1,flexDirection:"column",children:[(0,dr.jsx)(fe,{flexDirection:"row",children:(0,dr.jsxs)(ne,{color:ye?me.AccentCyan:void 0,children:[ye?"> ":" ",Z.title]})}),(0,dr.jsx)(fe,{marginLeft:4,children:(0,dr.jsx)(ne,{color:me.Gray,children:Z.description})})]},Z.id)})]}),(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.navigation")}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.navigateOptions")}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.enterToEditField")}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.escToBack")}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.qToExit")})]})]})},ue=()=>(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:me.AccentCyan,children:n("agentInstallDialog.previewTitle")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.previewDescription")})}),(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,children:u.agentType}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:me.AccentBlue,children:u.description})}),(0,dr.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:me.AccentCyan,children:n("agentInstallDialog.details")}),(0,dr.jsxs)(ne,{children:[" ","\u2022"," ",n("agentInstallDialog.location",{location:u.location})]}),(0,dr.jsxs)(ne,{children:[" ","\u2022 ",n("agentInstallDialog.model",{model:"Qwen3-Coder"})]}),(0,dr.jsxs)(ne,{children:[" ","\u2022 ",n("agentInstallDialog.color",{color:u.color})]})]}),(0,dr.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:me.AccentCyan,children:n("agentInstallDialog.tools")}),(0,dr.jsx)(fe,{marginLeft:2,children:(0,dr.jsx)(ne,{children:u.selectedTools?.length?u.selectedTools.join(", "):n("agentInstallDialog.allToolsAvailable")})})]}),(0,dr.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:me.AccentCyan,children:n("agentInstallDialog.mcpServers")}),(0,dr.jsx)(fe,{marginLeft:2,children:(0,dr.jsx)(ne,{children:u.selectedMcps?.length?u.selectedMcps.join(", "):n("agentInstallDialog.allMcpServersAvailable")})})]}),u.systemPrompt&&(0,dr.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:me.AccentCyan,children:n("agentInstallDialog.systemPrompt")}),(0,dr.jsx)(fe,{marginLeft:2,children:(0,dr.jsx)(ne,{children:u.systemPrompt.length>200?`${u.systemPrompt.substring(0,200)}...`:u.systemPrompt})})]})]}),(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:me.AccentYellow,children:n("agentInstallDialog.actions")}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.enterToCreate")}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.escToBackEdit")}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.qToExit")})]})]}),Ce=()=>B?o==="preview"?ue():o==="generated-preview"?Se():o==="generating"?(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:me.AccentCyan,children:n("agentInstallDialog.generatingTitle")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.generatingDescription")})}),(0,dr.jsx)(fe,{marginTop:2,children:(0,dr.jsx)(ne,{color:me.AccentYellow,children:S||n("agentInstallDialog.startingGeneration")})}),(0,dr.jsx)(fe,{marginTop:2,children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.pleaseWait")})})]}):g&&B.type==="input"?(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:me.AccentCyan,children:B.title}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:me.Gray,children:B.description})}),(0,dr.jsx)(fe,{marginTop:2,children:(0,dr.jsx)(LE,{onSubmit:Q,onCancel:V,placeholder:B.placeholder,label:B.title,defaultValue:G(),isFocused:!0})})]}):(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:me.AccentCyan,children:B.title}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:me.Gray,children:B.description})}),B.type==="input"&&!g&&(0,dr.jsxs)(fe,{marginTop:2,children:[(0,dr.jsx)(ne,{color:me.AccentYellow,children:G()?n("agentInstallDialog.currentValue",{value:G()}):n("agentInstallDialog.currentValueNotSet")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.pressEnterToEdit")})})]}),(B.type==="select"||B.type==="multiselect")&&(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[B.type==="multiselect"&&(0,dr.jsxs)(fe,{marginBottom:2,flexDirection:"column",children:[(0,dr.jsx)(fe,{flexDirection:"row",children:(0,dr.jsxs)(ne,{color:a===0?me.AccentCyan:void 0,children:[a===0?"> ":" ",n("agentInstallDialog.continue")]})}),(0,dr.jsx)(fe,{marginLeft:4,children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.proceedToNextStep")})})]},"continue"),j.map((Z,ie)=>{let ye=(B.type==="multiselect"?ie+1:ie)===a,oe=B.type==="multiselect"?o==="tools"?(u.selectedTools||[]).includes(Z.id):(u.selectedMcps||[]).includes(Z.id):!1;return(0,dr.jsxs)(fe,{marginBottom:1,flexDirection:"column",children:[(0,dr.jsx)(fe,{flexDirection:"row",children:(0,dr.jsxs)(ne,{color:ye?me.AccentCyan:void 0,children:[ye?"> ":" ",B.type==="multiselect"&&(0,dr.jsx)(ne,{children:oe?"[\u2713] ":"[ ] "}),B.type==="select"&&Z.id==="red"&&(0,dr.jsx)(ne,{color:me.AccentRed,children:"\u2588 "}),B.type==="select"&&Z.id==="blue"&&(0,dr.jsx)(ne,{color:me.AccentBlue,children:"\u2588 "}),B.type==="select"&&Z.id==="green"&&(0,dr.jsx)(ne,{color:me.AccentGreen,children:"\u2588 "}),B.type==="select"&&Z.id==="yellow"&&(0,dr.jsx)(ne,{color:me.AccentYellow,children:"\u2588 "}),B.type==="select"&&Z.id==="purple"&&(0,dr.jsx)(ne,{color:me.AccentPurple,children:"\u2588 "}),B.type==="select"&&Z.id==="orange"&&(0,dr.jsx)(ne,{color:me.AccentYellow,children:"\u2588 "}),B.type==="select"&&Z.id==="pink"&&(0,dr.jsx)(ne,{color:me.AccentPurple,children:"\u2588 "}),B.type==="select"&&Z.id==="cyan"&&(0,dr.jsx)(ne,{color:me.AccentCyan,children:"\u2588 "}),Z.title]})}),Z.description&&(0,dr.jsx)(fe,{marginLeft:4,children:(0,dr.jsx)(ne,{color:me.Gray,children:Z.description})})]},Z.id)})]}),(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.navigation")}),B.type==="input"&&!g&&(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.enterToEdit")}),(B.type==="select"||B.type==="multiselect"||B.type==="edit")&&(0,dr.jsxs)(dr.Fragment,{children:[(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.navigateOptions")}),(0,dr.jsxs)(ne,{color:me.Gray,children:[" ","\u2022"," ",B.type==="edit"?n("agentInstallDialog.enterToEditField"):n("agentInstallDialog.enterToSelect")]})]}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.escToBack")}),(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.qToExit")})]})]}):(0,dr.jsx)(fe,{flexDirection:"column",children:(0,dr.jsx)(ne,{color:me.Gray,children:n("agentInstallDialog.generatingTitle")})});return h?(0,dr.jsxs)(fe,{borderStyle:"round",borderColor:me.AccentGreen,flexDirection:"column",padding:1,width:"100%",children:[(0,dr.jsx)(ne,{bold:!0,color:me.AccentGreen,children:n("agentInstallDialog.agentInstallation")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsxs)(ne,{color:me.AccentGreen,children:["\u2714 ",h]})})]}):(0,dr.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,dr.jsx)(ne,{bold:!0,children:n("agentInstallDialog.title")}),le(),Ce(),f&&(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsxs)(ne,{color:me.AccentRed,children:["\u274C ",f]})})]})},(t,e)=>t.config===e.config);var W8=Ie(rr(),1);await Zr();Rn();fi();var Nn=Ie(Pt(),1);function Hoi({settings:t,config:e,onExit:r,onStatusUpdate:n}){let{t:o}=fr(),[s,a]=(0,W8.useState)("loading"),[c,u]=(0,W8.useState)([]),[d,f]=(0,W8.useState)(0),[p,h]=(0,W8.useState)(0),[m,g]=(0,W8.useState)(null),[A,y]=(0,W8.useState)(null),[E,v]=(0,W8.useState)(null),b=10,S=Math.ceil(c.length/b);(0,W8.useEffect)(()=>{let I=async()=>{try{if(!t.merged.apiKey)return{success:!1,message:o("agentsOnlineDialog.authRequired")};let j=await fetch("https://apis.iflow.cn/v1/agents/list",{method:"POST",headers:{"User-Agent":"iFlow-Cli","Content-Type":"application/json"},body:JSON.stringify({page:1,size:1e3,usePage:!0,visibility:"public",publishStatus:"published"})});if(!j.ok){let k=o("agentsOnlineDialog.loadFailed");return j.status===401?k=o("agentsOnlineDialog.authFailed"):j.status===403?k=o("agentsOnlineDialog.accessDenied"):j.status===404?k=o("agentsOnlineDialog.serviceNotFound"):j.status>=500&&(k=o("agentsOnlineDialog.serverError")),{success:!1,message:k}}let U=await j.json();return U.success?{success:!0,data:U.data?.data||[]}:{success:!1,message:U.message||o("agentsOnlineDialog.serverLoadFailed")}}catch(B){let j=o("agentsOnlineDialog.connectionError");return B instanceof Error&&B.message.includes("Failed to fetch")&&(j=o("agentsOnlineDialog.networkError")),{success:!1,message:j}}};(async()=>{let B=await I();B.success&&B.data?(u(B.data),a("list"),B.data.length===0&&y(o("agentsOnlineDialog.noAgentsFound"))):(y(B.message||o("agentsOnlineDialog.loadAgentsFailed")),a("list"))})()},[t.merged.apiKey,o]);let w=async(I,N)=>{try{let{AgentRegistry:B}=await Promise.resolve().then(()=>(Gt(),By)),j=new B,U=[],k=!0,G=!0,Q,V=null;if(I.extInfo&&typeof I.extInfo=="string")try{V=JSON.parse(I.extInfo)}catch{}if(V){if(k=V["is-inherit-tools"],G=V["is-inherit-mcps"]!==void 0?V["is-inherit-mcps"]:!0,V["allowed-tools"]){let K=V["allowed-tools"].split(",").map(Y=>Y.trim()).filter(Y=>Y);K.length>0?U=K:U=V["is-inherit-tools"]?["*"]:[]}else U=V["is-inherit-tools"]?["*"]:[];if(V.mcps){let K=V.mcps.split(",").map(Y=>Y.trim()).filter(Y=>Y);K.length>0?Q=K:Q=V["is-inherit-mcps"]?void 0:[]}else Q=V["is-inherit-mcps"]?void 0:[]}else{try{let K=JSON.parse(I.tools||"[]");U=Array.isArray(K)?K:["*"]}catch{U=["*"]}if(I.mcps)try{let K=JSON.parse(I.mcps);Array.isArray(K)&&K.length>0&&(Q=K)}catch{let K=I.mcps.split(",").map(Y=>Y.trim()).filter(Y=>Y.length>0);K.length>0&&(Q=K)}}let H={agentType:I.name.toLowerCase().replace(/[^a-z0-9]/g,"-"),name:I.name,description:I.description,whenToUse:I.description,allowedTools:U,allowedMcps:Q,systemPrompt:I.detailContext||I.description,location:N==="user"?"global":"project",model:I.modelName,isInheritTools:k,isInheritMcps:G};return await j.createAgent(H)?{success:!0,message:o("agentsCommand.install.successfullyInstalled",{name:I.name,scope:N})}:{success:!1,message:o("agentsOnlineDialog.createAgentFailed",{name:I.name})}}catch(B){return{success:!1,message:o("agentsOnlineDialog.installFailedWithError",{name:I.name,error:B})}}},R=async(I,N)=>{try{n?.(o("agentsOnlineDialog.installing",{name:I.name}));let B=await w(I,N);B.success?(v(B.message),y(null),n?.(B.message)):(y(B.message),v(null),n?.(`\u274C ${B.message}`))}catch(B){let j=B instanceof Error?B.message:o("agentsOnlineDialog.installationFailed");y(j),v(null),n?.(`\u274C ${j}`)}};Tn(I=>{if(I.name==="escape"){s==="detail"?(a("list"),g(null),y(null),v(null)):r();return}if(s==="list")if(I.name==="up"||I.sequence==="k"){let N=Math.max(p-1,0);h(N);let B=Math.floor(N/b);f(B)}else if(I.name==="down"||I.sequence==="j"){let N=Math.min(p+1,c.length-1);h(N);let B=Math.floor(N/b);f(B)}else if(I.name==="left"||I.sequence==="h"){let N=Math.max(d-1,0);f(N),h(N*b)}else if(I.name==="right"||I.sequence==="l"){let N=Math.min(d+1,S-1);f(N),h(Math.min(N*b,c.length-1))}else I.name==="return"?c.length>0&&p>=0&&p<c.length&&(g(c[p]),a("detail"),y(null),v(null)):I.sequence==="q"&&r();else s==="detail"&&m&&(I.sequence==="1"?R(m,"project"):I.sequence==="2"?R(m,"user"):I.sequence==="b"?(a("list"),g(null),y(null),v(null)):I.sequence==="q"&&r())},{isActive:!0});let D=()=>{if(c.length===0)return(0,Nn.jsxs)(fe,{flexDirection:"column",children:[(0,Nn.jsx)(ne,{bold:!0,children:o("agentsOnlineDialog.availableAgents")}),(0,Nn.jsx)(fe,{marginTop:1,children:(0,Nn.jsx)(ne,{color:me.AccentRed,children:A||o("agentsOnlineDialog.noAgentsAvailable")})})]});let I=d*b,N=Math.min(I+b,c.length),B=c.slice(I,N);return(0,Nn.jsxs)(fe,{flexDirection:"column",children:[(0,Nn.jsx)(ne,{bold:!0,children:o("agentsOnlineDialog.availableAgentsWithCount",{count:c.length})}),(0,Nn.jsx)(fe,{marginTop:1,flexDirection:"column",children:B.map((j,U)=>{let G=I+U===p;return(0,Nn.jsxs)(fe,{marginBottom:1,flexDirection:"row",children:[(0,Nn.jsxs)(fe,{width:30,flexShrink:0,flexDirection:"column",children:[(0,Nn.jsxs)(ne,{color:G?me.AccentCyan:void 0,children:[G?"> ":" ",U+1,". ",j.name]}),(0,Nn.jsx)(fe,{marginLeft:4,flexDirection:"column",children:(0,Nn.jsx)(ne,{color:me.Gray,children:o("agentsOnlineDialog.category",{category:j.category})})})]}),(0,Nn.jsx)(fe,{marginLeft:3,flexGrow:1,children:(0,Nn.jsx)(ne,{color:me.Gray,children:j.description})})]},j.id)})}),(0,Nn.jsx)(fe,{marginTop:1,children:(0,Nn.jsx)(ne,{color:me.AccentBlue,children:o("agentsOnlineDialog.pageOf",{current:d+1,total:S})})}),(0,Nn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Nn.jsx)(ne,{color:me.Gray,children:o("agentsOnlineDialog.navigation")}),(0,Nn.jsxs)(ne,{color:me.Gray,children:[" ",o("agentsOnlineDialog.navigateUpDown")]}),(0,Nn.jsxs)(ne,{color:me.Gray,children:[" ",o("agentsOnlineDialog.prevNextPage")]}),(0,Nn.jsxs)(ne,{color:me.Gray,children:[" ",o("agentsOnlineDialog.viewDetails")]}),(0,Nn.jsxs)(ne,{color:me.Gray,children:[" ",o("agentsOnlineDialog.exit")]})]})]})},M=()=>m?(0,Nn.jsxs)(fe,{flexDirection:"column",children:[(0,Nn.jsx)(ne,{bold:!0,children:m.name}),(0,Nn.jsx)(fe,{marginTop:1,children:(0,Nn.jsx)(ne,{color:me.AccentBlue,children:m.description})}),(0,Nn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Nn.jsx)(ne,{color:me.AccentCyan,children:o("agentsOnlineDialog.details")}),(0,Nn.jsxs)(ne,{children:[" ","\u2022"," ",o("agentsOnlineDialog.model",{model:m.modelName})]}),(0,Nn.jsxs)(ne,{children:[" ","\u2022"," ",o("agentsOnlineDialog.categoryLabel",{category:m.category})]}),(0,Nn.jsxs)(ne,{children:[" ","\u2022"," ",o("agentsOnlineDialog.version",{version:m.version})]})]}),(()=>{let I=null;if(m.extInfo&&typeof m.extInfo=="string")try{I=JSON.parse(m.extInfo)}catch{}return I?(0,Nn.jsxs)(Nn.Fragment,{children:[(0,Nn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Nn.jsx)(ne,{color:me.AccentCyan,children:o("agentsOnlineDialog.tools")}),(0,Nn.jsx)(fe,{marginLeft:2,children:(0,Nn.jsx)(ne,{children:(()=>{let N=I["allowed-tools"]?I["allowed-tools"].split(",").map(j=>j.trim()).filter(j=>j):[],B=I["is-inherit-tools"]?o("agentsOnlineDialog.inherit"):o("agentsOnlineDialog.noInherit");return N.length>0?N.join(", ")+B:I["is-inherit-tools"]?o("agentsOnlineDialog.allToolsAvailableInherit"):o("agentsOnlineDialog.noToolsAvailableNoInherit")})()})})]}),(0,Nn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Nn.jsx)(ne,{color:me.AccentCyan,children:o("agentsOnlineDialog.mcpServers")}),(0,Nn.jsx)(fe,{marginLeft:2,children:(0,Nn.jsx)(ne,{children:(()=>{let N=I.mcps?I.mcps.split(",").map(j=>j.trim()).filter(j=>j):[],B=I["is-inherit-mcps"]?o("agentsOnlineDialog.inherit"):o("agentsOnlineDialog.noInherit");return N.length>0?N.join(", ")+B:I["is-inherit-mcps"]?o("agentsOnlineDialog.allMcpServersAvailableInherit"):o("agentsOnlineDialog.noMcpServersAvailableNoInherit")})()})})]})]}):(0,Nn.jsxs)(Nn.Fragment,{children:[(0,Nn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Nn.jsx)(ne,{color:me.AccentCyan,children:o("agentsOnlineDialog.tools")}),(0,Nn.jsx)(fe,{marginLeft:2,children:(0,Nn.jsx)(ne,{children:(()=>{if(!m.tools)return o("agentsOnlineDialog.allToolsAvailableInherit");try{let N=JSON.parse(m.tools);return Array.isArray(N)?N.length>0?N.join(", ")+o("agentsOnlineDialog.inherit"):o("agentsOnlineDialog.allToolsAvailableInherit"):(m.tools||o("agentsOnlineDialog.allToolsAvailableInherit").replace(o("agentsOnlineDialog.inherit"),""))+o("agentsOnlineDialog.inherit")}catch{return(m.tools||o("agentsOnlineDialog.allToolsAvailableInherit").replace(o("agentsOnlineDialog.inherit"),""))+o("agentsOnlineDialog.inherit")}})()})})]}),(0,Nn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Nn.jsx)(ne,{color:me.AccentCyan,children:o("agentsOnlineDialog.mcpServers")}),(0,Nn.jsx)(fe,{marginLeft:2,children:(0,Nn.jsx)(ne,{children:(()=>{if(!m.mcps||m.mcps.trim()==="")return o("agentsOnlineDialog.allMcpServersAvailableInherit");try{let N=JSON.parse(m.mcps);return Array.isArray(N)?N.length>0?N.join(", ")+o("agentsOnlineDialog.inherit"):o("agentsOnlineDialog.allMcpServersAvailableInherit"):(m.mcps||o("agentsOnlineDialog.allMcpServersAvailableInherit").replace(o("agentsOnlineDialog.inherit"),""))+o("agentsOnlineDialog.inherit")}catch{return(m.mcps||o("agentsOnlineDialog.allMcpServersAvailableInherit").replace(o("agentsOnlineDialog.inherit"),""))+o("agentsOnlineDialog.inherit")}})()})})]})]})})(),m.detailContext&&(0,Nn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Nn.jsx)(ne,{color:me.AccentCyan,children:o("agentsOnlineDialog.systemPrompt")}),(0,Nn.jsx)(fe,{marginLeft:2,children:(0,Nn.jsx)(ne,{children:m.detailContext.length>800?`${m.detailContext.substring(0,800)}...`:m.detailContext})})]}),(0,Nn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Nn.jsx)(ne,{color:me.AccentYellow,children:o("agentsOnlineDialog.actions")}),(0,Nn.jsxs)(ne,{color:me.Gray,children:[" ",o("agentsOnlineDialog.installProject")]}),(0,Nn.jsxs)(ne,{color:me.Gray,children:[" ",o("agentsOnlineDialog.installUser")]}),(0,Nn.jsxs)(ne,{color:me.Gray,children:[" ",o("agentsOnlineDialog.backToList")]}),(0,Nn.jsxs)(ne,{color:me.Gray,children:[" ",o("agentsOnlineDialog.exit")]})]}),E&&(0,Nn.jsx)(fe,{marginTop:1,children:(0,Nn.jsxs)(ne,{color:me.AccentGreen,children:["\u2714 ",E]})}),A&&(0,Nn.jsx)(fe,{marginTop:1,children:(0,Nn.jsx)(ne,{color:me.AccentRed,children:A})})]}):null;return s==="loading"?(0,Nn.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Nn.jsx)(ne,{bold:!0,children:o("agentsOnlineDialog.loadingTitle")}),(0,Nn.jsx)(fe,{marginTop:1,children:(0,Nn.jsx)(ne,{children:o("agentsOnlineDialog.loadingMessage")})})]}):(0,Nn.jsx)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:s==="list"?D():M()})}var K5=Ie(rr(),1);await Zr();Rn();var BD=Ie(rr(),1);await Zr();Rn();var UE=Ie(Pt(),1);function Lu({items:t,initialIndex:e=0,onSelect:r,onHighlight:n,isFocused:o,showScrollArrows:s=!1,maxItemsToShow:a=10,showNumbers:c=!0}){let[u,d]=(0,BD.useState)(e),[f,p]=(0,BD.useState)(0),[h,m]=(0,BD.useState)(""),g=(0,BD.useRef)(null);(0,BD.useEffect)(()=>{let y=Math.max(0,Math.min(u-a+1,t.length-a));u<f?p(u):u>=f+a&&p(y)},[u,t.length,f,a]),(0,BD.useEffect)(()=>()=>{g.current&&clearTimeout(g.current)},[]),Tn(y=>{if(!o||t.length===0)return;let E=c&&/^[0-9]$/.test(y.sequence||"");if(!E&&g.current&&(clearTimeout(g.current),m("")),y.sequence==="k"||y.name==="up"){let v=u>0?u-1:t.length-1;d(v),n?.(t[v].value);return}if(y.sequence==="j"||y.name==="down"){let v=u<t.length-1?u+1:0;d(v),n?.(t[v].value);return}if(y.name==="return"){r(t[u].value);return}if(E){g.current&&clearTimeout(g.current);let v=h+y.sequence;m(v);let b=Number.parseInt(v,10)-1;if(v==="0"){g.current=setTimeout(()=>m(""),350);return}if(b>=0&&b<t.length){let S=t[b];d(b),n?.(S.value),Number.parseInt(v+"0",10)>t.length?(r(S.value),m("")):g.current=setTimeout(()=>{r(S.value),m("")},350)}else m("")}},{isActive:!0});let A=t.slice(f,f+a);return(0,UE.jsxs)(fe,{flexDirection:"column",children:[s&&(0,UE.jsx)(ne,{color:f>0?me.Foreground:me.Gray,children:"\u25B2"}),A.map((y,E)=>{let v=f+E,b=u===v,S=me.Foreground,w=me.Foreground;b?(S=me.AccentGreen,w=me.AccentGreen):y.disabled&&(S=me.Gray,w=me.Gray),c||(w=me.Gray);let R=String(t.length).length,D=`${String(v+1).padStart(R)}.`;return(0,UE.jsxs)(fe,{alignItems:"center",children:[(0,UE.jsx)(fe,{minWidth:2,flexShrink:0,children:(0,UE.jsx)(ne,{color:b?me.AccentGreen:me.Foreground,children:b?"\u25CF":" "})}),(0,UE.jsx)(fe,{marginRight:1,flexShrink:0,minWidth:D.length,children:(0,UE.jsx)(ne,{color:w,children:D})}),y.themeNameDisplay&&y.themeTypeDisplay?(0,UE.jsxs)(ne,{color:S,wrap:"truncate",children:[y.themeNameDisplay," ",(0,UE.jsx)(ne,{color:me.Gray,children:y.themeTypeDisplay})]}):(0,UE.jsx)(ne,{color:S,wrap:"truncate",children:y.label})]},y.label)}),s&&(0,UE.jsx)(ne,{color:f+a<t.length?me.Foreground:me.Gray,children:"\u25BC"})]})}var Aae=Ie(rr(),1);await Zr();Rn();var $la=/^[a-zA-Z0-9!@#$%^&*()\-_=+\[\]{}|\\:;"'<>,.?/~]+$/;function frt(t){return!t||t.trim().length===0?!1:$la.test(t)}fi();var QE=Ie(Pt(),1);function yae({onSubmit:t,onCancel:e,placeholder:r,label:n,isFocused:o=!0,validateApiKey:s=!1,validationError:a}){let{t:c}=fr(),u=r||c("passwordInput.defaultPlaceholder"),d=n||c("passwordInput.defaultLabel"),f=a||c("passwordInput.validationError"),[p,h]=(0,Aae.useState)(""),[m,g]=(0,Aae.useState)(!0),[A,y]=(0,Aae.useState)(null);(0,Aae.useEffect)(()=>{if(!o)return;let b=setInterval(()=>{g(S=>!S)},500);return()=>clearInterval(b)},[o]),Tn(b=>{if(b.name==="return"||b.name==="enter"){if(p.trim()){let S=p.trim().replace(/^~+|~+$/g,"");if(s&&!frt(S)){y(f);return}y(null),t(S)}return}if(b.name==="escape"){e?.();return}if(b.name==="backspace"||b.name==="delete"){h(S=>S.slice(0,-1));return}if(b.paste&&b.sequence){let S=b.sequence.split("").filter(w=>{let R=w.charCodeAt(0);return R>=32&&R!==127||s&&frt(w)}).join("");S&&h(w=>w+S);return}if(b.sequence&&!b.ctrl&&!b.meta){if(b.sequence.length===1){let S=b.sequence;(S.charCodeAt(0)>=32&&S.charCodeAt(0)!==127||s&&frt(S))&&h(w=>w+S)}else if(b.sequence.length>1){let S=b.sequence;/[\x00-\x1F\x7F]/.test(S)||h(w=>w+S)}}},{isActive:o});let E="\u2022".repeat(p.length),v=m&&o?"\u2502":"";return(0,QE.jsxs)(fe,{flexDirection:"column",children:[(0,QE.jsx)(fe,{children:(0,QE.jsxs)(ne,{color:me.Gray,children:[d," "]})}),(0,QE.jsx)(fe,{marginTop:1,children:(0,QE.jsx)(fe,{borderStyle:"round",borderColor:A?me.AccentRed:o?me.AccentBlue:me.Gray,paddingX:1,width:"100%",children:(0,QE.jsxs)(ne,{children:[E||(0,QE.jsx)(ne,{color:me.Gray,children:u}),v]})})}),A&&(0,QE.jsx)(fe,{marginTop:1,children:(0,QE.jsx)(ne,{color:me.AccentRed,children:A})}),(0,QE.jsx)(fe,{marginTop:1,children:(0,QE.jsx)(ne,{color:me.Gray,dimColor:!0,children:c("passwordInput.instructions")})})]})}_l();Gt();fi();import{exec as qla}from"child_process";import{promisify as Hla}from"util";var lM=class{id;display;desc;owner;supportType;multimodal;internal;defaultConfig;constructor(e){this.id=e.id,this.display=e.display,this.desc=e.desc,this.owner=e.owner,this.supportType=e.supportType,this.multimodal=e.multimodal,this.internal=e.internal,this.defaultConfig=e.defaultConfig}};var uM=class{default;type;constructor(e){this.default=e.default,this.type=e.type}};var prt=class t{label;value;constructor(e,r){this.label=e,this.value=r}static fromModelInfo(e){return new t(e.display,e.id)}};var hrt=class{repoPath;securityLevel;constructor(e){this.repoPath=e.repoPath,this.securityLevel=e.securityLevel}isC3(){return this.securityLevel==="C3"}};var Vla=Hla(qla);async function mrt(t){try{let e=await fetch("https://ducky.code.alibaba-inc.com/v1/models",{headers:{Authorization:`Bearer ${t}`}});if(!e.ok)throw new Error(`Failed to fetch models: ${e.status} ${e.statusText}`);return(await e.json()).map(n=>new lM({id:n.id,display:n.display,desc:n.desc,owner:n.owner,supportType:n.supportType,multimodal:n.multimodal,internal:n.internal,defaultConfig:new uM(n.defaultConfig)}))}catch(e){return console.error("Error fetching models:",e),Wla()}}function Wla(){return[new lM({id:"ide-whale/qwen3-coder",display:"Qwen3-Coder",desc:"Qwen3-Coder",owner:"",supportType:["chat","llm","agent"],multimodal:!1,internal:!0,defaultConfig:new uM({default:!0})}),new lM({id:"ide-idealab/claude4-sonnet",display:"Claude-4-Sonnet",desc:"Claude-4-Sonnet",owner:"",supportType:["chat","llm","agent"],multimodal:!0,defaultConfig:new uM({})}),new lM({id:"ide-whale/deepseek-v3.2-exp",display:"DeepSeek-V3.2-Whale",desc:"DeepSeek-V3.2",owner:"",supportType:["agent","chat","llm"],multimodal:!1,internal:!0,defaultConfig:new uM({})}),new lM({id:"ide-whale/kimi_k2",display:"Kimi-K2",desc:"Kimi-K2",owner:"",supportType:["chat","llm"],multimodal:!1,internal:!0,defaultConfig:new uM({})})]}function grt(t){return t.map(e=>prt.fromModelInfo(e))}async function zla(t){try{let e=t?{cwd:t}:{},{stdout:r,stderr:n}=await Vla("git remote get-url origin",e);return n&&console.error("Git command stderr:",n),r.trim()}catch(e){return console.error("Error getting git remote URL:",e),null}}function Yla(t){if(!t)return null;try{let e=t.trim();e.endsWith(".git")&&(e=e.slice(0,-4));let r=e.match(/^git@[^:]+:(.+)$/);if(r)return r[1];let n=e.match(/^https?:\/\/[^/]+\/(.+)$/);return n?n[1]:null}catch(e){return console.error("Error extracting repo path from git URL:",e),null}}async function Kla(t,e){try{let r=`https://code.alibaba-inc.com/api/v4/projects/settings/security_level?private_token=${e}&repos=${t}`,n=await fetch(r);if(!n.ok)return console.error(`Failed to fetch security level: ${n.status} ${n.statusText}`),null;let o=await n.json();return o.length===0?null:new hrt({repoPath:o[0].repo_path,securityLevel:o[0].security_level})}catch(r){return console.error("Error fetching security level:",r),null}}function Art(t){return t.filter(e=>{let r=e.supportType.includes("agent"),n=e.id.toLowerCase().includes("gpt-5")||e.display.toLowerCase().includes("gpt-5"),o=e.id.toLowerCase().includes("deepseek")||e.display.toLowerCase().includes("deepseek");return r&&!n&&!o})}function yrt(t,e){return!e||!e.isC3()?t:t.filter(r=>r.internal===!0)}async function IH(t,e){let r=await zla(e);if(!r)return console.error("Failed to get git remote URL"),null;let n=Yla(r);return n?Kla(n,t):(console.error("Failed to extract repo path from git URL:",r),null)}function _rt(t){return[...t].sort((e,r)=>{let n=e.id.toLowerCase().includes("qwen3-coder")||e.display.toLowerCase().includes("qwen3-coder"),o=r.id.toLowerCase().includes("qwen3-coder")||r.display.toLowerCase().includes("qwen3-coder");return n&&!o?-1:!n&&o?1:e.display.localeCompare(r.display)})}var $6e=Ie(rr(),1);await Zr();import{spawn as Voi}from"child_process";import*as Ert from"fs/promises";import*as Woi from"path";import*as zoi from"os";var Yoi=t=>t.startsWith("@")||/\s@/.test(t),Koi=t=>{if(!t.startsWith("/")||t.startsWith("//")||t.startsWith("/*"))return!1;let e=t.substring(1);return e.includes("/")&&!/\s+\//.test(e)?!1:e===""?!0:!!e.match(/^([a-zA-Z0-9_-]+)/)},Xoi=t=>t==="/init",Joi=t=>t.startsWith("$"),_ae=async t=>{let e=(n,o,s)=>new Promise((a,c)=>{let u=s?Voi(n,o,s):Voi(n,o),d="";u.stderr&&u.stderr.on("data",f=>d+=f.toString()),u.on("error",c),u.on("close",f=>{if(f===0)return a();let p=d.trim();c(new Error(`'${n}' exited with code ${f}${p?`: ${p}`:""}`))}),u.stdin?(u.stdin.on("error",c),u.stdin.write(t),u.stdin.end()):c(new Error("Child process has no stdin stream to write to."))}),r={stdio:["pipe","inherit","pipe"]};switch(process.platform){case"win32":return(async()=>{let n=Woi.join(zoi.tmpdir(),`iflow-clipboard-${Date.now()}.txt`);try{await Ert.writeFile(n,t,"utf8"),await e("powershell",["-NoProfile","-NonInteractive","-Command",`Get-Content -Path '${n}' -Encoding UTF8 -Raw | Set-Clipboard`])}finally{try{await Ert.unlink(n)}catch{}}})();case"darwin":return e("pbcopy",[]);case"linux":try{await e("xclip",["-selection","clipboard"],r)}catch(n){try{await e("xsel",["--clipboard","--input"],r)}catch(o){let s=n instanceof Error&&n.code==="ENOENT",a=o instanceof Error&&o.code==="ENOENT";if(s&&a)throw new Error("Please ensure xclip or xsel is installed and configured.");let c=n instanceof Error?n.message:String(n);s&&(c="xclip not found");let u=o instanceof Error?o.message:String(o);throw a&&(u="xsel not found"),new Error(`All copy commands failed. "${c}", "${u}". `)}}return;default:throw new Error(`Unsupported platform: ${process.platform}`)}},Zoi=()=>{let t;switch(process.platform){case"darwin":t="open";break;case"win32":t="start";break;case"linux":t="xdg-open";break;default:t="xdg-open",console.warn(`Unknown platform: ${process.platform}. Attempting to open URLs with: ${t}.`);break}return t};Rn();fi();var q6e=Ie(Pt(),1);function esi({text:t}){let{t:e}=fr(),[r,n]=(0,$6e.useState)(!1),[o,s]=(0,$6e.useState)(!0),a=async()=>{try{await _ae(t),n(!0),setTimeout(()=>{n(!1)},2e3)}catch{}};return Tn(c=>{if(!o)return;let u=c.name||c.sequence;(u==="c"||u==="C")&&(c.ctrl||c.meta)&&a()},{isActive:o}),(0,$6e.useEffect)(()=>(s(!0),()=>{s(!1)}),[]),(0,q6e.jsxs)(fe,{marginTop:1,flexDirection:"column",gap:1,paddingX:1,children:[(0,q6e.jsx)(ne,{color:me.AccentBlue,children:t}),(0,q6e.jsx)(ne,{color:"gray",children:r?e("copyableUrlBox.copied"):""})]})}var Yn=Ie(Pt(),1);function tsi(t){return t&&Object.values(Yt).includes(t)?t:null}function rsi({onSelect:t,settings:e,initialErrorMessage:r}){let{t:n}=fr(),[o,s]=(0,K5.useState)("select"),[a,c]=(0,K5.useState)(null),[u,d]=(0,K5.useState)({baseUrl:"",apiKey:""}),[f,p]=(0,K5.useState)("baseUrl"),[h,m]=(0,K5.useState)(""),[g,A]=(0,K5.useState)(""),[y,E]=(0,K5.useState)(""),[v,b]=(0,K5.useState)([]),[S,w]=(0,K5.useState)(!1),[R,D]=(0,K5.useState)(()=>{if(r)return r;let Y=tsi(process.env.GEMINI_DEFAULT_AUTH_TYPE);return null}),M="global",I=[M==="global"&&{label:n("authDialog.loginWithIFlowRecommend"),value:Yt.LOGIN_WITH_IFLOW},M==="global"&&{label:n("authDialog.loginWithIFlowApiKey"),value:Yt.IFLOW},M==="aone"&&{label:n("authDialog.loginWithAoneRecommend"),value:Yt.LOGIN_WITH_AONE},M==="aone"&&{label:n("authDialog.loginWithAoneApiKey"),value:Yt.AONE},{label:n("authDialog.openaiCompatibleApi"),value:Yt.OPENAI_COMPATIBLE}].filter(Boolean),N=Math.max(0,I.findIndex(Y=>{if(e.merged.selectedAuthType)return Y.value===e.merged.selectedAuthType;let J=tsi(process.env.GEMINI_DEFAULT_AUTH_TYPE);return J?Y.value===J:M==="aone"?Y.value===Yt.LOGIN_WITH_AONE:Y.value===Yt.LOGIN_WITH_IFLOW})),B=Y=>{if(Y===Yt.LOGIN_WITH_IFLOW){let J=e.merged.isServerOAuth2==="true";if(!WR()||J){c(Y);let X=pSe();E(X),s("input-oauth-code"),D(null)}else{let X=XP(Y);X?D(X):(D(null),t(Y,"User"))}}else if(O_.includes(Y))c(Y),s("input-api-key"),D(null);else if(Y===Yt.OPENAI_COMPATIBLE)c(Y),s("input-openai-config"),p("baseUrl"),d({baseUrl:"",apiKey:""}),D(null);else{let J=XP(Y);J?D(J):(D(null),t(Y,"User"))}},j=async Y=>{if(a&&O_.includes(a)){if(A(Y),a===Yt.AONE){w(!0);try{let J=Buffer.from(Y,"utf8").toString("base64"),X=await mrt(J),le=Art(X),Se=await IH(Y);Se?.isC3()&&(le=yrt(le,Se));let ue=_rt(le),Ce=grt(ue);b(Ce)}catch(J){console.error("Failed to load models:",J),b([{label:"Qwen3-Coder",value:"ide-whale/qwen3-coder"},{label:"Claude-4-Sonnet",value:"ide-idealab/claude4-sonnet"},{label:"DeepSeek-V3.2-Whale",value:"ide-whale/deepseek-v3.2-exp"},{label:"Kimi-K2",value:"ide-whale/kimi_k2"}])}finally{w(!1)}}else a===Yt.IFLOW&&b([{label:`GLM-4.6(${n("modelDialog.recommend")})`,value:"glm-4.6"},{label:"DeepSeek-V3.2",value:"deepseek-v3.2-chat"},{label:"Qwen3-Coder-Plus",value:"qwen3-coder-plus"},{label:"Kimi-K2-Thinking",value:"kimi-k2-thinking"},{label:"MiniMax-M2",value:"minimax-m2"},{label:"Kimi-K2-0905",value:"kimi-k2-0905"}]);s("input-model-name"),m("")}},U=Y=>{if(f==="baseUrl")d(J=>({...J,baseUrl:Y})),p("apiKey");else if(f==="apiKey")d(J=>({...J,apiKey:Y})),p("modelName");else if(f==="modelName"){d(X=>({...X,modelName:Y})),m(Y);let J={...u,modelName:Y};t(a,"User",J)}},k=()=>{s("select"),c(null),D(null)},G=()=>{f==="modelName"?p("apiKey"):f==="apiKey"?p("baseUrl"):(s("select"),c(null),d({baseUrl:"",apiKey:""}),p("baseUrl"),D(null))},Q=Y=>{if(a&&O_.includes(a))if(m(Y),a===Yt.IFLOW){let J={baseUrl:"https://apis.iflow.cn/v1",apiKey:g,modelName:Y,searchApiKey:g};t(a,"User",J)}else if(a===Yt.AONE){let J=Buffer.from(g,"utf8").toString("base64"),X={baseUrl:"https://ducky.code.alibaba-inc.com/v1/openai",apiKey:J,modelName:Y,searchApiKey:J};t(a,"User",X)}else{let J={apiKey:g,modelName:Y};t(a,"User",J)}},V=Y=>{if(a&&O_.includes(a))if(m(Y),a===Yt.IFLOW){let J={baseUrl:"https://apis.iflow.cn/v1",apiKey:g,modelName:Y,searchApiKey:g};t(a,"User",J)}else if(a===Yt.AONE){let J=Buffer.from(g,"utf8").toString("base64"),X={baseUrl:"https://ducky.code.alibaba-inc.com/v1/openai",apiKey:J,modelName:Y,searchApiKey:J};t(a,"User",X)}else{let J={apiKey:g,modelName:Y};t(a,"User",J)}},H=()=>{a&&O_.includes(a)?s("input-api-key"):(s("input-openai-config"),p("apiKey"))},L=async Y=>{try{let J=await hSe(Y);if(J.apiKey){let X={baseUrl:"https://apis.iflow.cn/v1",apiKey:J.apiKey,modelName:"qwen3-coder-plus",searchApiKey:J.apiKey,isServerOAuth2:"true"};t(a,"User",X)}else D(n("authDialog.failedToGetApiKey"))}catch(J){D(J instanceof Error?J.message:n("authDialog.authFailed"))}},K=()=>{s("select"),c(null),E(""),D(null)};return Tn(Y=>{if(Y.name==="escape"){if(R)return;if(e.merged.selectedAuthType===void 0){D(n("authDialog.mustSelectAuth"));return}t(void 0,"User")}},{isActive:!0}),o==="input-oauth-code"?(0,Yn.jsxs)(fe,{flexDirection:"column",padding:1,width:"100%",children:[(0,Yn.jsx)(ne,{bold:!0,children:n("authDialog.iflowOAuthLogin")}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.oauthStep1")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(esi,{text:y})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.oauthStep2")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.oauthStep3")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(LE,{onSubmit:L,onCancel:K,label:n("authDialog.authCodeLabel"),placeholder:n("authDialog.authCodePlaceholder"),isFocused:!0})}),R&&(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{color:me.AccentRed,children:R})})]}):o==="input-api-key"?a===Yt.IFLOW?(0,Yn.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Yn.jsx)(ne,{bold:!0,children:n("authDialog.iflowAuth")}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.enterIFlowApiKey")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(yae,{onSubmit:j,onCancel:k,label:n("authDialog.apiKeyLabel"),placeholder:n("authDialog.apiKeyPlaceholder"),isFocused:!0,validateApiKey:!0})})]}):(0,Yn.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Yn.jsx)(ne,{bold:!0,children:n("authDialog.aoneAuth")}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.enterAoneApiKey")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(yae,{onSubmit:j,onCancel:k,label:n("authDialog.apiKeyLabel"),placeholder:n("authDialog.privateTokenPlaceholder"),isFocused:!0,validateApiKey:!0})})]}):o==="input-model-name"?a===Yt.IFLOW||a===Yt.AONE?S?(0,Yn.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Yn.jsx)(ne,{bold:!0,children:n("authDialog.modelConfig")}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{color:me.AccentBlue,children:n("modelDialog.loading")})})]}):(0,Yn.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Yn.jsx)(ne,{bold:!0,children:n("authDialog.modelConfig")}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.selectModel")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{color:me.AccentBlue,children:n("authDialog.defaultSelection")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(Lu,{items:v,initialIndex:0,onSelect:V,isFocused:!0})})]}):(0,Yn.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Yn.jsx)(ne,{bold:!0,children:n("authDialog.modelConfig")}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.enterModelName")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(LE,{onSubmit:Q,onCancel:H,label:n("authDialog.modelNameLabel"),placeholder:n("authDialog.modelNamePlaceholder"),isFocused:!0})})]}):o==="input-openai-config"?(0,Yn.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Yn.jsx)(ne,{bold:!0,children:n("authDialog.openaiConfig")}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n(f==="baseUrl"?"authDialog.enterBaseUrl":f==="apiKey"?"authDialog.enterApiKey":"authDialog.enterOpenaiModelName")})}),(0,Yn.jsx)(fe,{marginTop:1,children:f==="baseUrl"?(0,Yn.jsx)(LE,{onSubmit:U,onCancel:G,label:n("authDialog.baseUrlLabel"),placeholder:n("authDialog.baseUrlPlaceholder"),isFocused:!0}):f==="apiKey"?(0,Yn.jsx)(yae,{onSubmit:U,onCancel:G,label:n("authDialog.apiKeyLabel"),placeholder:n("authDialog.openaiApiKeyPlaceholder"),isFocused:!0,validateApiKey:!0}):(0,Yn.jsx)(LE,{onSubmit:U,onCancel:G,label:n("authDialog.modelNameLabel"),placeholder:n("authDialog.openaiModelPlaceholder"),isFocused:!0})}),f==="baseUrl"&&u.baseUrl&&(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{color:me.Gray,children:n("authDialog.current",{value:u.baseUrl})})})]}):(0,Yn.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Yn.jsx)(ne,{bold:!0,children:n("authDialog.getStarted")}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.howToAuth")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(Lu,{items:I,initialIndex:N,onSelect:B,isFocused:!0})}),R&&(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{color:me.AccentRed,children:R})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{color:me.Gray,children:n("authDialog.useEnterToSelect")})}),(0,Yn.jsx)(fe,{marginTop:1,children:(0,Yn.jsx)(ne,{children:n("authDialog.termsOfService")})})]})}await Zr();var Eae=Ie(rr(),1);await Zr();var asi=Ie(ssi(),1);function Jla({type:t="dots"}){let[e,r]=(0,Eae.useState)(0),n=asi.default[t];return(0,Eae.useEffect)(()=>{let o=setInterval(()=>{r(s=>s===n.frames.length-1?0:s+1)},n.interval);return()=>{clearInterval(o)}},[n]),Eae.default.createElement(ne,null,n.frames[e])}var vae=Jla;var brt=Ie(rr(),1);fi();Rn();var Py=Ie(Pt(),1);function csi({onTimeout:t,authUrl:e}){let{t:r}=fr(),[n,o]=(0,brt.useState)(!1);return Tn(s=>{s.name==="escape"&&t()},{isActive:!0}),(0,brt.useEffect)(()=>{let s=setTimeout(()=>{o(!0),t()},18e4);return()=>clearTimeout(s)},[t]),(0,Py.jsx)(fe,{flexDirection:"column",padding:1,width:"100%",children:n?(0,Py.jsx)(ne,{color:me.AccentRed,children:r("authInProgress.authTimeout")}):(0,Py.jsxs)(Py.Fragment,{children:[e&&(0,Py.jsxs)(fe,{flexDirection:"column",children:[(0,Py.jsx)(ne,{color:me.Gray,children:r("authInProgress.copyUrlPrompt")}),(0,Py.jsx)(fe,{marginTop:1,children:(0,Py.jsx)(ne,{color:me.AccentBlue,wrap:"wrap",children:e})})]}),(0,Py.jsx)(fe,{marginTop:e?1:0,children:(0,Py.jsxs)(ne,{children:[(0,Py.jsx)(vae,{type:"dots"})," ",r("authInProgress.waitingForAuth")]})})]})})}await Zr();Rn();Gt();fi();var H6e=Ie(Pt(),1);var lsi=({approvalMode:t})=>{let{t:e}=fr(),r="",n="",o="";switch(t){case ii.AUTO_EDIT:r=me.AccentGreen,n=e("input.acceptingEdits"),o=e("input.toggleHint");break;case ii.PLAN:r=me.AccentGreen,n=e("input.planMode"),o=e("input.toggleHint");break;case ii.YOLO:r=me.AccentRed,n=e("input.yoloMode"),o=e("input.toggleHint");break;case ii.DEFAULT:r=me.AccentGreen,n=e("input.defaultMode"),o=e("input.toggleHint");break;default:break}return(0,H6e.jsx)(fe,{children:(0,H6e.jsxs)(ne,{color:r,children:[n,o&&(0,H6e.jsx)(ne,{color:me.Gray,children:o})]})})};await Zr();Rn();fi();var DH=Ie(Pt(),1);var usi=({enabled:t,supported:e})=>{let{t:r}=fr();return e?(0,DH.jsx)(fe,{marginRight:1,children:(0,DH.jsxs)(ne,{color:t?me.AccentGreen:me.Gray,children:[r("input.thinkingMode"),":",r(t?"input.thinkingOn":"input.thinkingOff"),(0,DH.jsx)(ne,{color:me.Gray,children:r("input.thinkingToggleHint")})]})}):(0,DH.jsx)(fe,{marginRight:1,children:(0,DH.jsxs)(ne,{color:me.Gray,children:[r("input.thinkingMode"),":",r("input.thinkingNotSupported")]})})};var Crt=Ie(rr(),1);await Zr();fi();Rn();var Uu=Ie(Pt(),1);import*as Srt from"fs/promises";function dsi({onConfirm:t,onCancel:e,config:r,projectRoot:n}){let{t:o}=fr(),[s,a]=(0,Crt.useState)({sessionCount:0,diskUsage:o("cleanupHistoryDialog.calculating"),projectPath:"",isLoading:!0});(0,Crt.useEffect)(()=>{(async()=>{if(!r){a({sessionCount:0,diskUsage:o("cleanupHistoryDialog.unknown"),projectPath:"",isLoading:!1});return}try{let{FileSystemUtil:f,ProjectNameGenerator:p}=await Promise.resolve().then(()=>(W5(),eer)),h=p.fromPath(n),m=f.getProjectDir(h),g=0,A=0;try{let v=(await Srt.readdir(m)).filter(b=>b.endsWith(".jsonl"));g=v.length;for(let b of v){let S=`${m}/${b}`,w=await Srt.stat(S);A+=w.size}}catch(E){if(E&&typeof E=="object"&&"code"in E&&E.code!=="ENOENT")throw E}let y=(A/1024/1024).toFixed(2);a({sessionCount:g,diskUsage:`${y} MB`,projectPath:n,isLoading:!1})}catch{a({sessionCount:0,diskUsage:o("cleanupHistoryDialog.calculationFailed"),projectPath:n,isLoading:!1})}})()},[r,n,o]),Tn(d=>{d.name==="escape"&&e()},{isActive:!0});let c=[{label:o("cleanupHistoryDialog.confirmOption"),value:"confirm"},{label:o("cleanupHistoryDialog.cancelOption"),value:"cancel"}],u=async d=>{d==="confirm"?await t():e()};return s.isLoading?(0,Uu.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Uu.jsxs)(ne,{bold:!0,children:["\u26A0\uFE0F ",o("cleanupHistoryDialog.title")]}),(0,Uu.jsx)(fe,{marginTop:1,children:(0,Uu.jsx)(ne,{color:me.AccentBlue,children:o("cleanupHistoryDialog.loadingStats")})})]}):(0,Uu.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Uu.jsxs)(ne,{bold:!0,children:["\u26A0\uFE0F ",o("cleanupHistoryDialog.title")]}),(0,Uu.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Uu.jsx)(ne,{children:o("cleanupHistoryDialog.currentStatus")}),(0,Uu.jsxs)(fe,{marginLeft:2,flexDirection:"column",children:[(0,Uu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.projectPath"),(0,Uu.jsx)(ne,{color:me.AccentBlue,children:s.projectPath})]}),(0,Uu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.sessions"),(0,Uu.jsxs)(ne,{color:me.AccentGreen,children:[s.sessionCount," ",o("cleanupHistoryDialog.sessionsUnit")]})]}),(0,Uu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.diskUsage")," ",(0,Uu.jsx)(ne,{color:me.AccentGreen,children:s.diskUsage})]})]})]}),(0,Uu.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Uu.jsx)(ne,{color:me.AccentRed,children:o("cleanupHistoryDialog.warningTitle")}),(0,Uu.jsxs)(fe,{marginLeft:2,flexDirection:"column",children:[(0,Uu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.warningDeleteHistory")]}),(0,Uu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.warningFreeSpace")]})]})]}),(0,Uu.jsx)(fe,{marginTop:1,children:(0,Uu.jsx)(Lu,{items:c,initialIndex:1,onSelect:u,isFocused:!0})}),(0,Uu.jsx)(fe,{marginTop:1,children:(0,Uu.jsx)(ne,{color:me.Gray,children:o("cleanupHistoryDialog.instructions")})})]})}var xrt=Ie(rr(),1);await Zr();fi();Rn();Gt();var El=Ie(Pt(),1);import*as fsi from"path";function psi({onConfirm:t,onCancel:e,gitService:r,config:n,projectRoot:o}){let{t:s}=fr(),[a,c]=(0,xrt.useState)({checkpointCount:0,commitCount:0,diskUsage:s("cleanupCheckpointDialog.calculating"),isLoading:!0});(0,xrt.useEffect)(()=>{(async()=>{if(!r||!n){c({checkpointCount:0,commitCount:0,diskUsage:s("cleanupCheckpointDialog.unknown"),isLoading:!1});return}try{let p=n.getProjectTempDir()?fsi.join(n.getProjectTempDir(),"checkpoints"):void 0;if(!p)throw new Error(s("cleanupCheckpointDialog.cannotGetCheckpointDir"));let m=await new KP(r,p).getCheckpointCount(),g=await r.getCommitCount(),A=r.getHistoryDir(),E=(await r.getDirectorySize(A)/1024/1024).toFixed(2);c({checkpointCount:m,commitCount:g,diskUsage:`${E} MB`,isLoading:!1})}catch{c({checkpointCount:0,commitCount:0,diskUsage:s("cleanupCheckpointDialog.calculationFailed"),isLoading:!1})}})()},[r,n,o,s]),Tn(f=>{f.name==="escape"&&e()},{isActive:!0});let u=[{label:s("cleanupCheckpointDialog.confirmOption"),value:"confirm"},{label:s("cleanupCheckpointDialog.cancelOption"),value:"cancel"}],d=async f=>{f==="confirm"?await t():e()};return a.isLoading?(0,El.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,El.jsxs)(ne,{bold:!0,children:["\u26A0\uFE0F ",s("cleanupCheckpointDialog.title")]}),(0,El.jsx)(fe,{marginTop:1,children:(0,El.jsx)(ne,{color:me.AccentBlue,children:s("cleanupCheckpointDialog.loadingStats")})})]}):(0,El.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,El.jsxs)(ne,{bold:!0,children:["\u26A0\uFE0F ",s("cleanupCheckpointDialog.title")]}),(0,El.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,El.jsx)(ne,{children:s("cleanupCheckpointDialog.currentStatus")}),(0,El.jsxs)(fe,{marginLeft:2,flexDirection:"column",children:[(0,El.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.projectPath"),(0,El.jsx)(ne,{color:me.AccentBlue,children:o})]}),(0,El.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.checkpoints"),(0,El.jsxs)(ne,{color:me.AccentGreen,children:[a.checkpointCount," ",s("cleanupCheckpointDialog.checkpointsUnit")]})," ",s("cleanupCheckpointDialog.jsonFiles")]}),(0,El.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.gitHistory"),(0,El.jsxs)(ne,{color:me.AccentGreen,children:[a.commitCount," ",s("cleanupCheckpointDialog.commits")]})]}),(0,El.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.diskUsage")," ",(0,El.jsx)(ne,{color:me.AccentGreen,children:a.diskUsage})]})]})]}),(0,El.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,El.jsx)(ne,{color:me.AccentRed,children:s("cleanupCheckpointDialog.warningTitle")}),(0,El.jsxs)(fe,{marginLeft:2,flexDirection:"column",children:[(0,El.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.warningDeleteHistory")]}),(0,El.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.warningFreeSpace")]}),(0,El.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.warningNoRestore")]})]})]}),(0,El.jsx)(fe,{marginTop:1,children:(0,El.jsx)(Lu,{items:u,initialIndex:1,onSelect:d,isFocused:!0})}),(0,El.jsx)(fe,{marginTop:1,children:(0,El.jsx)(ne,{color:me.Gray,children:s("cleanupCheckpointDialog.instructions")})})]})}var X5=Ie(rr(),1);await Zr();Rn();fi();import Ker from"fs/promises";import Xer from"path";import Zla from"os";var Pi=Ie(Pt(),1);function hsi({settings:t,config:e,onExit:r,onStatusUpdate:n}){let{t:o}=fr(),[s,a]=(0,X5.useState)("loading"),[c,u]=(0,X5.useState)([]),[d,f]=(0,X5.useState)(1),[p,h]=(0,X5.useState)(0),[m,g]=(0,X5.useState)(null),[A,y]=(0,X5.useState)(null),[E,v]=(0,X5.useState)(null),[b,S]=(0,X5.useState)(0),w=10,R=Math.ceil(b/w);(0,X5.useEffect)(()=>{let U=async G=>{try{if(!t.merged.apiKey)throw new Error(o("commandsOnlineDialog.apiKeyNotFound"));let V=new URL("https://apis.iflow.cn/v1/commands/list"),H=await fetch(V.toString(),{method:"POST",headers:{"User-Agent":"iFlow-Cli","Content-Type":"application/json"},body:JSON.stringify({page:G,size:w,usePage:!0,visibility:"public",publishStatus:"published"})});if(!H.ok){let J=o("commandsOnlineDialog.unableToLoadCommands");throw H.status===401?J=o("commandsOnlineDialog.authenticationFailed"):H.status===403?J=o("commandsOnlineDialog.accessDenied"):H.status===404?J=o("commandsOnlineDialog.serviceNotFound"):H.status>=500&&(J=o("commandsOnlineDialog.serverError")),new Error(J)}let L=await H.json();if(!L.success)throw new Error(L.message||o("commandsOnlineDialog.failedToFetchCommands"));let K=Array.isArray(L.data?.data)?L.data.data:[],Y=L.data?.total||K.length;return{commands:K,total:Y}}catch(Q){throw new Error(o("commandsOnlineDialog.failedToFetchCommandsWithError",{error:Q}))}};(async()=>{try{let G=await U(d);u(G.commands),S(G.total),a("list"),h(0),G.commands.length===0&&y(o("commandsOnlineDialog.noCommandsFound"))}catch(G){y(G instanceof Error?G.message:o("commandsOnlineDialog.failedToLoadCommands")),a("list"),h(0)}})()},[d,t,o]);let D=U=>U.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),M=U=>U==="user"?Xer.join(Zla.homedir(),".iflow","commands"):Xer.join(process.cwd(),".iflow","commands"),I=async(U,k)=>{try{let G=M(k);await Ker.mkdir(G,{recursive:!0});let Q=`${D(U.name)}.toml`,V=Xer.join(G,Q);try{return await Ker.access(V),{success:!1,message:o("commandsOnlineDialog.commandAlreadyInstalled",{name:U.name,scope:k})}}catch{}let H=`# Command: ${U.name}
|
|
@@ -4560,7 +4560,7 @@ ${O.t("textTruncation.truncatedCharactersAndLines",{characters:c,lines:a})}
|
|
|
4560
4560
|
`)}`}break;case"todo_read":return" Reading current todo list";case"read_file":case"read":if(r?.file_path)return` ${mM(r.file_path)}`;break;case"write_file":case"write":if(r?.file_path)return` ${mM(r.file_path)}`;break;case"edit_file":case"edit":if(r?.file_path)return` ${mM(r.file_path)}`;break;case"run_shell_command":case"bash":case"shell":if(r?.command)return` ${r.command.slice(0,60)}${r.command.length>60?"...":""}`;break;case"search_file_content":case"grep":if(r?.pattern)return` "${r.pattern}"${r.path?` in ${mM(r.path)}`:""}`;break;case"list_directory":case"ls":return r?.path?` ${mM(r.path)}`:" Current directory";case"glob":if(r?.pattern)return` "${r.pattern}"${r.path?` in ${mM(r.path)}`:""}`;break;case"task":if(r?.prompt){let n=r.prompt.replace(/\\n/g,`
|
|
4561
4561
|
`);return` "${n.slice(0,80)}${n.length>80?"...":""}"`}if(r?.description)return` "${r.description.replace(/\\n/g,`
|
|
4562
4562
|
`)}"`;break;case"web_fetch":if(r?.url){let n=new URL(r.url);return` ${n.hostname}${n.pathname.slice(0,30)}`}break;default:return""}}catch{return""}return""}function $rt(t,e){return t.map(r=>{let n=bfa(r);if(!n&&r.request.args)try{if(typeof r.request.args=="object"){let a=r.request.args;a.prompt?n=`"${a.prompt.slice(0,200)}${a.prompt.length>200?"...":""}"`:a.description?n=`"${a.description}"`:a.file_path?n=`${mM(a.file_path)}`:a.command?n=`${a.command}`:n=Object.entries(a).slice(0,3).map(([c,u])=>typeof u=="string"?`${c.includes("path")||c.includes("file")?mM(u):u.slice(0,200)}`:`${JSON.stringify(u).slice(0,200)}`).join(", ")}else n=String(r.request.args)}catch{n=O.t("subAgentDisplay.invalidArgs")}let o=vfa(r.request.name,e),s=Cfa(r.status);return{callId:r.request.callId,name:o,description:n||`${o} tool call`,resultDisplay:r.response?.resultDisplay?typeof r.response.resultDisplay=="string"&&r.response.resultDisplay.length>200?"..."+r.response.resultDisplay.slice(-200).trim():r.response.resultDisplay:void 0,status:s,confirmationDetails:void 0,renderOutputAsMarkdown:!0,duration:r.duration}})}function Cfa(t){switch(t){case"scheduled":return"Pending";case"executing":return"Executing";case"success":return"Success";case"error":return"Error";default:return"Pending"}}Ps();fi();var $a=Ie(Pt(),1);var Sfa=tS.default.memo(({agentToolCalls:t,constrainHeight:e,streamingState:r,childWidth:n,config:o})=>{let{t:s}=fr(),a=!1,c=a?t.slice(-5):t,u=t.length-c.length,d=(0,tS.useMemo)(()=>c.map(f=>{let p=$rt([f],o)[0];return(0,$a.jsx)(fe,{marginBottom:0,children:(0,$a.jsx)(Grt,{...p,terminalWidth:n-kae,emphasis:"low",status:p.status,renderOutputAsMarkdown:!1,displayMarginTop:0})},f.request.callId)}),[c,o,n,c.map(f=>f.status).join("-")]);return(0,$a.jsxs)(fe,{marginLeft:1,flexDirection:"column",children:[a&&(r==="idle"||r==="responding"||r==="waiting_for_confirmation")&&(0,$a.jsx)(fe,{marginBottom:0,children:(0,$a.jsx)(ne,{color:me.Gray,wrap:"truncate",children:s("subAgentToolMessage.showingLast",{shown:5,total:t.length,hidden:u})})}),d]})}),kae=3,Kci=({subAgentState:t,terminalWidth:e,config:r,taskToolCallId:n,taskInstanceId:o,constrainHeight:s=!0})=>{let a=(0,tS.useId)(),{t:c}=fr(),{addOverflowingId:u,removeOverflowingId:d}=wrt()||{},f=hM(),p=(0,tS.useMemo)(()=>Array.from(t.agents.values()).filter(A=>!o||!A.id?!0:A.id.includes(o)),[t.agents,o]),h=(0,tS.useMemo)(()=>p.some(A=>{let y=t.toolCalls.get(A.id)||[];return s&&y.length>5}),[p,t.toolCalls,s]);(0,tS.useEffect)(()=>(h?u?.(a):d?.(a),()=>{d?.(a)}),[a,h,u,d]);let m=(0,tS.useMemo)(()=>{let A=new Map;return p.forEach(y=>{let E=y.taskPrompt.slice(0,4e3)+(y.taskPrompt.length>4e3?"...":"");A.set(y.id,E)}),A},[p]);if(p.length===0)return(0,$a.jsx)(fe,{paddingX:1,paddingY:0,flexDirection:"column",children:(0,$a.jsxs)(fe,{minHeight:1,children:[(0,$a.jsx)(fe,{minWidth:kae,children:(0,$a.jsx)(ne,{color:me.Gray,children:"\u{1F916}"})}),(0,$a.jsx)(fe,{children:(0,$a.jsx)(ne,{color:me.Gray,children:c("subAgentToolMessage.initializingAgents")})})]})});let g=e-3;return(0,$a.jsx)(fe,{paddingX:1,paddingY:0,flexDirection:"column",children:p.map(A=>{let y=t.toolCalls.get(A.id)||[],E=GI.get(A.sessionConfig.color)||"\u{1F916}",v=m.get(A.id);return(0,$a.jsxs)(fe,{flexDirection:"column",marginBottom:1,children:[(0,$a.jsxs)(fe,{minHeight:1,children:[(0,$a.jsx)(fe,{minWidth:kae,children:(0,$a.jsx)(ne,{color:A.sessionConfig.color,children:E})}),(0,$a.jsxs)(fe,{children:[(0,$a.jsx)(ne,{color:me.Foreground,bold:!0,children:c("subAgentToolMessage.agentTitle",{type:A.sessionConfig.agentType})}),(0,$a.jsxs)(ne,{color:me.Gray,children:[" ",xfa(A.status)]}),A.currentRound>0&&(0,$a.jsxs)(ne,{color:me.Gray,children:[" (",c("subAgentToolMessage.round",{count:A.currentRound}),")"]}),(0,$a.jsxs)(ne,{color:me.Gray,children:[" - ",c("subAgentToolMessage.messageCount",{count:A.messageCount})]}),A.status==="completed"&&(0,$a.jsxs)(ne,{color:me.Gray,children:[" \u2022 ",x2(Date.now()-A.startTime)]})]})]}),A.sessionConfig.model&&(0,$a.jsxs)(fe,{paddingLeft:kae,marginTop:1,flexDirection:"column",children:[(0,$a.jsxs)(ne,{color:me.Gray,children:[c("subAgentToolMessage.model"),": ",(0,$a.jsx)(ne,{color:me.Foreground,children:A.sessionConfig.model})]}),A.originalRequestedModel&&A.originalRequestedModel!==A.sessionConfig.model&&(0,$a.jsxs)(ne,{color:me.AccentYellow,children:["\u26A0 ",c("subAgentToolMessage.originallyRequested",{model:A.originalRequestedModel,reason:A.modelFallbackReason})]})]}),(0,$a.jsxs)(fe,{paddingLeft:kae,marginTop:1,children:[(0,$a.jsxs)(ne,{color:me.Gray,children:[c("subAgentToolMessage.task"),": "]}),(0,$a.jsx)(ne,{wrap:"wrap",children:v})]}),y.length>0&&(0,$a.jsxs)(fe,{paddingLeft:kae,marginTop:1,flexDirection:"column",children:[(0,$a.jsxs)(ne,{color:me.Gray,children:[c("subAgentToolMessage.tools"),":"]}),(0,$a.jsx)(Sfa,{agentToolCalls:y,constrainHeight:s,streamingState:f,childWidth:g,config:r})]})]},A.id)})})};function xfa(t){switch(t){case"created":return O.t("subAgentToolMessage.status.created");case"running":return O.t("subAgentToolMessage.status.running");case"completed":return O.t("subAgentToolMessage.status.completed");case"failed":return O.t("subAgentToolMessage.status.failed");default:return O.t("subAgentToolMessage.status.unknown")}}var ec=Ie(Pt(),1);var wfa=1,Tfa=5,$tr=3,Ifa=2,Xci=1e6,Zci=({callId:t,name:e,description:r,resultDisplay:n,status:o,availableTerminalHeight:s,terminalWidth:a,emphasis:c="medium",renderOutputAsMarkdown:u=!0,subAgentState:d,config:f,constrainHeight:p=!0})=>{let h=s?Math.max(s-wfa-Tfa,Ifa+1):void 0;h&&(u=!0);let m=a-3;return typeof n=="string"&&n.length>Xci&&(n="..."+n.slice(-Xci)),(0,ec.jsxs)(fe,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[(0,ec.jsxs)(fe,{minHeight:1,children:[(0,ec.jsx)(Dfa,{status:o}),(0,ec.jsx)(Rfa,{name:!1?"":e,status:o,description:r,emphasis:c}),c==="high"&&(0,ec.jsx)(Nfa,{})]}),(0,ec.jsx)(fe,{paddingLeft:$tr,marginTop:0,minHeight:2,children:d?(0,ec.jsx)(Kci,{subAgentState:d,terminalWidth:m,config:f,taskToolCallId:t,taskInstanceId:t,constrainHeight:p}):(0,ec.jsx)(fe,{})}),(0,ec.jsx)(fe,{paddingLeft:$tr,width:"100%",marginTop:0,minHeight:1,children:(0,ec.jsx)(fe,{flexDirection:"column",children:n?(0,ec.jsxs)(ec.Fragment,{children:[typeof n=="string"&&u&&(0,ec.jsx)(fe,{flexDirection:"column",children:(0,ec.jsx)(K8,{text:n,isPending:!1,availableTerminalHeight:h,terminalWidth:m})}),typeof n=="string"&&!u&&(0,ec.jsx)(Y0,{maxHeight:h,maxWidth:m,children:(0,ec.jsx)(fe,{children:(0,ec.jsx)(ne,{wrap:"wrap",children:n})})}),typeof n!="string"&&(0,ec.jsx)(X8,{diffContent:n.fileDiff,filename:n.fileName,availableTerminalHeight:h,terminalWidth:m})]}):null})})]})},Dfa=({status:t})=>(0,ec.jsxs)(fe,{minWidth:$tr,children:[t==="Pending"&&(0,ec.jsx)(ne,{color:me.AccentGreen,children:"o"}),t==="Executing"&&(0,ec.jsx)(Oae,{spinnerType:"toggle",nonRespondingDisplay:"\u22B7"}),t==="Success"&&(0,ec.jsx)(ne,{color:me.AccentGreen,children:"\u2714"}),t==="Confirming"&&(0,ec.jsx)(ne,{color:me.AccentYellow,children:"?"}),t==="Canceled"&&(0,ec.jsx)(ne,{color:me.AccentYellow,bold:!0,children:"-"}),t==="Error"&&(0,ec.jsx)(ne,{color:me.AccentRed,bold:!0,children:"x"})]}),Rfa=({name:t,description:e,status:r,emphasis:n})=>{let o=Jci.default.useMemo(()=>{switch(n){case"high":return me.Foreground;case"medium":return me.Foreground;case"low":return me.Gray;default:return n}},[n]);return(0,ec.jsx)(fe,{children:(0,ec.jsxs)(ne,{wrap:"truncate-end",strikethrough:r==="Canceled",children:[(0,ec.jsx)(ne,{color:o,bold:!0,children:t})," ",(0,ec.jsx)(ne,{color:me.Gray,children:e})]})})},Nfa=()=>(0,ec.jsxs)(ne,{color:me.Foreground,wrap:"truncate",children:[" ","\u2190"]});var Hrt=Ie(rr(),1);await Zr();Ps();Rn();fi();var Ro=Ie(Pt(),1);var Ofa=1,kfa=5,Bfa=2,qrt=3,Pfa=({latestToolCall:t,config:e})=>{let{t:r}=fr(),n=Hrt.default.useMemo(()=>$rt([t],e)[0],[t,e]),o=()=>{let s=n.name,a=n.description,c=50,u=a.length>c?a.slice(0,c)+r("taskAbbreviationMessage.expandHint"):a;return`\u23BF ${s} ${u}`};return(0,Ro.jsx)(fe,{flexDirection:"row",alignItems:"center",children:(0,Ro.jsx)(ne,{color:me.Foreground,children:o()})})},tli=({callId:t,name:e,status:r,emphasis:n="medium",subAgentState:o,resultDisplay:s,renderOutputAsMarkdown:a,availableTerminalHeight:c,terminalWidth:u})=>{let{t:d}=fr(),f=c?Math.max(c-Ofa-kfa,Bfa+1):void 0,p=u-3,h=Hrt.default.useMemo(()=>o?Array.from(o.agents.values()).filter(E=>!t||!E.id?!0:E.id.includes(t)):[],[o,t]),m=Hrt.default.useMemo(()=>{let E=new Map;return h.forEach(v=>{let b=v.taskPrompt.replace(/\s+/g," ").slice(0,50)+(v.taskPrompt.length>50?d("taskAbbreviationMessage.expandHint"):"").trim();E.set(v.id,b)}),E},[h]),g=t?.includes("dollar-task-")||!1,A=E=>{if(!E)return"";let v=Math.floor(E/6e4),b=Math.floor(E%6e4/1e3);return v>0?`${v}m ${b}s`:`${b}s`},y=E=>E>=1e3?`${(E/1e3).toFixed(1)}k`:E.toString();return h.length===0?(0,Ro.jsxs)(fe,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[(0,Ro.jsxs)(fe,{minHeight:1,flexDirection:"row",alignItems:"center",children:[(0,Ro.jsx)(eli,{status:r}),(0,Ro.jsx)(ne,{color:me.Foreground,bold:!0,children:e}),(0,Ro.jsxs)(ne,{color:me.Gray,children:[" ","- ",d("taskAbbreviationMessage.initializing")]})]}),(0,Ro.jsx)(fe,{paddingLeft:qrt,minHeight:1,children:(0,Ro.jsxs)(ne,{color:me.Gray,children:["(",d("taskAbbreviationMessage.expandInstructions"),")"]})})]}):(0,Ro.jsxs)(fe,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[h.map((E,v)=>{let b=o?.toolCalls.get(E.id)||[],S=m.get(E.id);return(0,Ro.jsxs)(fe,{flexDirection:"column",marginBottom:v<h.length-1?1:0,children:[(0,Ro.jsxs)(fe,{minHeight:1,flexDirection:"row",alignItems:"center",children:[(0,Ro.jsx)(eli,{status:r}),(0,Ro.jsxs)(fe,{flexDirection:"row",alignItems:"center",flexShrink:1,children:[(0,Ro.jsx)(ne,{color:jtr(E.sessionConfig.color),backgroundColor:Qtr(E.sessionConfig.color),bold:!0,children:E.sessionConfig.agentType}),S&&(0,Ro.jsx)(Ro.Fragment,{children:(0,Ro.jsxs)(ne,{color:me.Gray,children:[" ",S]})})]})]}),b.length>0&&(0,Ro.jsx)(fe,{paddingLeft:qrt,minHeight:1,children:E.status==="running"?(0,Ro.jsxs)(fe,{flexDirection:"column",children:[(0,Ro.jsx)(Pfa,{latestToolCall:b[b.length-1],config:void 0}),b.length>1&&(0,Ro.jsx)(fe,{paddingLeft:3,children:(0,Ro.jsx)(ne,{color:me.Gray,children:d("taskAbbreviationMessage.moreToolUses",{count:b.length-1,expandHint:d("taskAbbreviationMessage.expandInstructions")})})})]}):E.status==="completed"?(0,Ro.jsx)(ne,{color:me.Gray,children:d("taskAbbreviationMessage.completedStats",{toolCount:b.length,tokens:E.totalTokens?y(E.totalTokens):"",duration:E.endTime&&E.startTime?A(E.endTime-E.startTime):"",expandHint:d("taskAbbreviationMessage.expandInstructions")})}):(0,Ro.jsx)(fe,{paddingLeft:3,children:(0,Ro.jsx)(ne,{color:me.Gray,children:d("taskAbbreviationMessage.moreToolUses",{count:b.length,expandHint:d("taskAbbreviationMessage.expandInstructions")})})})})]},E.id)}),(0,Ro.jsx)(fe,{paddingLeft:qrt,width:"100%",marginTop:0,minHeight:1,children:(0,Ro.jsx)(fe,{flexDirection:"column",children:s&&g?(0,Ro.jsxs)(Ro.Fragment,{children:[typeof s=="string"&&a&&(0,Ro.jsx)(fe,{flexDirection:"column",children:(0,Ro.jsx)(K8,{text:s,isPending:!1,availableTerminalHeight:f,terminalWidth:p})}),typeof s=="string"&&!a&&(0,Ro.jsx)(Y0,{maxHeight:f,maxWidth:p,children:(0,Ro.jsx)(fe,{children:(0,Ro.jsx)(ne,{wrap:"wrap",children:s})})}),typeof s!="string"&&(0,Ro.jsx)(X8,{diffContent:s.fileDiff,filename:s.fileName,availableTerminalHeight:f,terminalWidth:p})]}):null})})]})},eli=({status:t})=>(0,Ro.jsxs)(fe,{minWidth:qrt,children:[t==="Pending"&&(0,Ro.jsx)(ne,{color:me.AccentGreen,children:"o"}),t==="Executing"&&(0,Ro.jsx)(ne,{color:me.AccentYellow,children:"\u22B7"}),t==="Success"&&(0,Ro.jsx)(ne,{color:me.AccentGreen,children:"\u2714"}),t==="Confirming"&&(0,Ro.jsx)(ne,{color:me.AccentYellow,children:"?"}),t==="Canceled"&&(0,Ro.jsx)(ne,{color:me.AccentYellow,bold:!0,children:"-"}),t==="Error"&&(0,Ro.jsx)(ne,{color:me.AccentRed,bold:!0,children:"x"})]});var Vrt=Ie(rr(),1);await Zr();Rn();Gt();fi();var yd=Ie(Pt(),1);var rli=({confirmationDetails:t,config:e,isFocused:r=!0,availableTerminalHeight:n,terminalWidth:o,hookManager:s})=>{let{t:a}=fr(),{onConfirm:c}=t,u=o-2,d=(0,Vrt.useCallback)(async()=>{if(!(!s||!e))try{let A="";if(t.type==="edit")A=a("toolConfirmationMessage.applyChangeQuestion");else if(t.type==="exec")A=a("toolConfirmationMessage.allowExecutionQuestion",{command:t.rootCommand});else if(t.type==="info")A=a("toolConfirmationMessage.proceedQuestion");else if(t.type==="mcp"){let y=t;A=a("toolConfirmationMessage.allowMcpToolQuestion",{toolName:y.toolName,serverName:y.serverName})}if(A){let y={sessionId:e.getSessionId?.()||"",transcriptPath:"",cwd:process.cwd(),projectDir:e.getProjectRoot?.()},v=(await s.executeNotification(A,y)).map(b=>b.exitCode===2&&b.stderr||!b.success&&b.stderr?b.stderr:null).filter(b=>b!==null);v.length>0&&console.log("Notification hook messages:",v.join(`
|
|
4563
|
-
`))}}catch(A){console.warn("Failed to execute notification hook:",A)}},[s,e,t,a]);(0,Vrt.useEffect)(()=>{d()},[d]),Tn(A=>{r&&A.name==="escape"&&c(xn.Cancel)},{isActive:r});let f=A=>c(A),p=null,h,m=new Array;function g(){if(m.length===0)throw new Error("Options not provided for confirmation message");if(n===void 0)return;let A=2,y=1,E=1,v=1,b=m.length,S=A+y+E+v+b;return Math.max(n-S,1)}if(t.type==="edit"){if(t.isModifying)return(0,yd.jsxs)(fe,{minWidth:"90%",borderStyle:"round",borderColor:me.Gray,justifyContent:"space-around",padding:1,overflow:"hidden",children:[(0,yd.jsxs)(ne,{children:[a("toolConfirmationMessage.modifyInProgress")," "]}),(0,yd.jsx)(ne,{color:me.AccentGreen,children:a("toolConfirmationMessage.saveAndCloseEditor")})]});h=a("toolConfirmationMessage.applyChangeQuestion"),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:xn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlways"),value:xn.ProceedAlways},{label:a("toolConfirmationMessage.modifyWithEditor"),value:xn.ModifyWithEditor},{label:a("toolConfirmationMessage.noSuggestChanges"),value:xn.Cancel}),p=(0,yd.jsx)(X8,{diffContent:t.fileDiff,filename:t.fileName,availableTerminalHeight:g(),terminalWidth:u})}else if(t.type==="exec"){let A=t;h=a("toolConfirmationMessage.allowExecutionQuestion",{command:A.rootCommand}),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:xn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlwaysEllipsis"),value:xn.ProceedAlways},{label:a("toolConfirmationMessage.noSuggestChanges"),value:xn.Cancel});let y=g();y!==void 0&&(y-=2),p=(0,yd.jsx)(fe,{flexDirection:"column",children:(0,yd.jsx)(fe,{paddingX:1,marginLeft:1,children:(0,yd.jsx)(Y0,{maxHeight:y,maxWidth:Math.max(u-4,1),children:(0,yd.jsx)(fe,{children:(0,yd.jsx)(ne,{color:me.AccentCyan,children:A.command})})})})})}else if(t.type==="info"){let A=t,y=A.urls&&!(A.urls.length===1&&A.urls[0]===A.prompt);h=a("toolConfirmationMessage.proceedQuestion"),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:xn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlways"),value:xn.ProceedAlways},{label:a("toolConfirmationMessage.noSuggestChanges"),value:xn.Cancel}),p=(0,yd.jsxs)(fe,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,yd.jsx)(ne,{color:me.AccentCyan,children:A.prompt}),y&&A.urls&&A.urls.length>0&&(0,yd.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,yd.jsx)(ne,{children:a("toolConfirmationMessage.urlsToFetch")}),A.urls.map(E=>(0,yd.jsxs)(ne,{children:[" - ",E]},E))]})]})}else{let A=t;p=(0,yd.jsxs)(fe,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,yd.jsxs)(ne,{color:me.AccentCyan,children:[a("toolConfirmationMessage.mcpServer"),": ",A.serverName]}),(0,yd.jsxs)(ne,{color:me.AccentCyan,children:[a("toolConfirmationMessage.tool"),": ",A.toolName]})]}),h=a("toolConfirmationMessage.allowMcpToolQuestion",{toolName:A.toolName,serverName:A.serverName}),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:xn.ProceedOnce},{label:a("toolConfirmationMessage.yesAlwaysAllowTool",{toolName:A.toolName,serverName:A.serverName}),value:xn.ProceedAlwaysTool},{label:a("toolConfirmationMessage.yesAlwaysAllowAllTools",{serverName:A.serverName}),value:xn.ProceedAlwaysServer},{label:a("toolConfirmationMessage.noSuggestChanges"),value:xn.Cancel})}return(0,yd.jsxs)(fe,{flexDirection:"column",padding:1,width:u,children:[(0,yd.jsx)(fe,{flexGrow:1,flexShrink:1,overflow:"hidden",marginBottom:1,children:p}),(0,yd.jsx)(fe,{marginBottom:1,flexShrink:0,children:(0,yd.jsx)(ne,{wrap:"truncate",children:h})}),(0,yd.jsx)(fe,{flexShrink:0,children:(0,yd.jsx)(Lu,{items:m,onSelect:f,isFocused:r})})]})};var PD=Ie(Pt(),1);var Gtr=({toolCalls:t,availableTerminalHeight:e,terminalWidth:r,config:n,isFocused:o=!0,subAgentState:s,taskTool:a,constrainHeight:c=!0,isTaskAbbreviated:u=!0,hookManager:d})=>{let p=r-4,h=(0,nli.useMemo)(()=>t.find(y=>y.status==="Confirming"),[t]),m=0;for(let y of t)y.resultDisplay!==void 0&&y.resultDisplay!==""&&m++;let g=t.length-m,A=e?Math.max(Math.floor((e-3-g)/Math.max(1,m)),1):void 0;return(0,PD.jsx)(fe,{flexDirection:"column",width:"100%",marginLeft:1,children:t.map(y=>{let E=h?.callId===y.callId;return(0,PD.jsxs)(fe,{flexDirection:"column",minHeight:1,children:[(0,PD.jsx)(fe,{flexDirection:"row",alignItems:"center",children:y.name.toLowerCase()==="task"?u?(0,PD.jsx)(tli,{callId:y.callId,name:y.name,description:y.description,resultDisplay:y.resultDisplay,status:y.status,confirmationDetails:y.confirmationDetails,terminalWidth:p,availableTerminalHeight:A,emphasis:E?"high":h?"low":"medium",subAgentState:s,taskTool:a,renderOutputAsMarkdown:y.renderOutputAsMarkdown}):(0,PD.jsx)(Zci,{callId:y.callId,name:y.name,description:y.description,resultDisplay:y.resultDisplay,status:y.status,confirmationDetails:y.confirmationDetails,availableTerminalHeight:A,terminalWidth:p,emphasis:E?"high":h?"low":"medium",renderOutputAsMarkdown:y.renderOutputAsMarkdown,subAgentState:s,config:n,taskTool:a,constrainHeight:c}):(0,PD.jsx)(Grt,{callId:y.callId,name:y.name,description:y.description,resultDisplay:y.resultDisplay,status:y.status,confirmationDetails:y.confirmationDetails,availableTerminalHeight:A,terminalWidth:p,emphasis:E?"high":h?"low":"medium",renderOutputAsMarkdown:y.renderOutputAsMarkdown,subAgentState:s,config:n,taskTool:a,isTaskAbbreviated:u})}),y.status==="Confirming"&&E&&y.confirmationDetails&&(0,PD.jsx)(rli,{confirmationDetails:y.confirmationDetails,config:n,isFocused:o,availableTerminalHeight:A,terminalWidth:p,hookManager:d})]},y.callId)})})};await Zr();Rn();fi();var Lp=Ie(Pt(),1);var qtr=({compression:t,showDetails:e=!1})=>{let{t:r}=fr();return t.isPending?(0,Lp.jsxs)(fe,{flexDirection:"row",children:[(0,Lp.jsx)(fe,{marginRight:1,children:(0,Lp.jsx)(vae,{type:"dots"})}),(0,Lp.jsx)(fe,{children:(0,Lp.jsx)(ne,{color:me.AccentPurple,children:r("compressionMessage.compressingHistory")})})]}):(0,Lp.jsxs)(fe,{flexDirection:"column",children:[(0,Lp.jsx)(fe,{marginY:1,children:(0,Lp.jsxs)(ne,{color:me.Gray,children:["==================== ",r("compressionMessage.previousConversationCompressed")," ===================="]})}),(0,Lp.jsxs)(fe,{flexDirection:"row",alignItems:"center",children:[(0,Lp.jsx)(ne,{color:me.AccentPurple,children:"\xB7"}),(0,Lp.jsx)(ne,{color:me.AccentPurple,children:r("compressionMessage.contextCompressed",{originalTokenCount:t.originalTokenCount?.toLocaleString()??"unknown",newTokenCount:t.newTokenCount?.toLocaleString()??"unknown"})}),(0,Lp.jsx)(ne,{color:me.Gray,children:r("compressionMessage.expandCollapseHint",{action:r(e?"compressionMessage.collapse":"compressionMessage.expand")})})]}),e&&t.summary&&(0,Lp.jsxs)(fe,{flexDirection:"column",marginTop:1,marginLeft:2,children:[(0,Lp.jsx)(fe,{marginBottom:1,children:(0,Lp.jsx)(ne,{color:me.Gray,children:r("compressionMessage.summaryLabel")})}),(0,Lp.jsx)(fe,{children:(0,Lp.jsx)(ne,{color:me.Foreground,wrap:"wrap",children:t.summary})}),(0,Lp.jsx)(fe,{marginTop:1,children:(0,Lp.jsx)(ne,{color:me.Gray,children:r("compressionMessage.collapseHint")})})]})]})};await Zr();Rn();var Wrt=Ie(Pt(),1);var ili=({text:t})=>(0,Wrt.jsx)(fe,{borderStyle:"round",borderColor:me.AccentPurple,flexDirection:"row",paddingX:2,paddingY:0,marginY:0,alignSelf:"flex-start",children:(0,Wrt.jsx)(fe,{flexGrow:1,children:(0,Wrt.jsx)(ne,{wrap:"wrap",color:me.Gray,children:t})})});await Zr();await Zr();var Vtr=Ie(Pt(),1);await Zr();Lle();import nve from"node:process";import Htr from"node:process";import Mfa from"node:os";import oli from"node:tty";function o4(t,e=globalThis.Deno?globalThis.Deno.args:Htr.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}var{env:zd}=Htr,zrt;o4("no-color")||o4("no-colors")||o4("color=false")||o4("color=never")?zrt=0:(o4("color")||o4("colors")||o4("color=true")||o4("color=always"))&&(zrt=1);function Ffa(){if(!("FORCE_COLOR"in zd))return;if(zd.FORCE_COLOR==="true")return 1;if(zd.FORCE_COLOR==="false")return 0;if(zd.FORCE_COLOR.length===0)return 1;let t=Math.min(Number.parseInt(zd.FORCE_COLOR,10),3);if([0,1,2,3].includes(t))return t}function Lfa(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Ufa(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let n=Ffa();n!==void 0&&(zrt=n);let o=r?zrt:n;if(o===0)return 0;if(r){if(o4("color=16m")||o4("color=full")||o4("color=truecolor"))return 3;if(o4("color=256"))return 2}if("TF_BUILD"in zd&&"AGENT_NAME"in zd)return 1;if(t&&!e&&o===void 0)return 0;let s=o||0;if(zd.TERM==="dumb")return s;if(Htr.platform==="win32"){let a=Mfa.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in zd)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(a=>a in zd)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(a=>a in zd)||zd.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in zd)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(zd.TEAMCITY_VERSION)?1:0;if(zd.COLORTERM==="truecolor"||zd.TERM==="xterm-kitty"||zd.TERM==="xterm-ghostty"||zd.TERM==="wezterm")return 3;if("TERM_PROGRAM"in zd){let a=Number.parseInt((zd.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(zd.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(zd.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(zd.TERM)||"COLORTERM"in zd?1:s}function Yrt(t,e={}){let r=Ufa(t,{streamIsTTY:t&&t.isTTY,...e});return Lfa(r)}var Yel={stdout:Yrt({isTTY:oli.isatty(1)}),stderr:Yrt({isTTY:oli.isatty(2)})};import Qfa from"process";function gM(t,e=Qfa.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}function sli(t=""){if(/^\d{3,4}$/.test(t)){let r=/(\d{1,2})(\d{2})/.exec(t)??[];return{major:0,minor:Number.parseInt(r[1],10),patch:Number.parseInt(r[2],10)}}let e=(t??"").split(".").map(r=>Number.parseInt(r,10));return{major:e[0],minor:e[1],patch:e[2]}}function ali(t){let{CI:e,CURSOR_TRACE_ID:r,FORCE_HYPERLINK:n,NETLIFY:o,TEAMCITY_VERSION:s,TERM_PROGRAM:a,TERM_PROGRAM_VERSION:c,VTE_VERSION:u,TERM:d}=nve.env;if(n)return!(n.length>0&&Number.parseInt(n,10)===0);if(gM("no-hyperlink")||gM("no-hyperlinks")||gM("hyperlink=false")||gM("hyperlink=never"))return!1;if(gM("hyperlink=true")||gM("hyperlink=always")||o)return!0;if(!Yrt(t)||t&&!t.isTTY)return!1;if("WT_SESSION"in nve.env)return!0;if(nve.platform==="win32"||e||s)return!1;if(a){let f=sli(c);switch(a){case"iTerm.app":return f.major===3?f.minor>=1:f.major>3;case"WezTerm":return/^0-unstable-\d{4}-\d{2}-\d{2}$/.test(c)?c.slice(11)>="2020-06-20":f.major>=20200620;case"vscode":return r?!0:f.major>1||f.major===1&&f.minor>=72;case"ghostty":return!0}}if(u){if(u==="0.50.0")return!1;let f=sli(u);return f.major>0||f.minor>=50}switch(d){case"alacritty":return!0;case"xterm-kitty":return!0}return!1}var jfa={stdout:ali(nve.stdout),stderr:ali(nve.stderr)},Krt=jfa;function UH(t,e,{target:r="stdout",...n}={}){return Krt[r]?Kp.link(t,e):n.fallback===!1?t:typeof n.fallback=="function"?n.fallback(t,e):`${t} ${e}`}UH.isSupported=Krt.stdout;UH.stderr=(t,e,r={})=>UH(t,e,{target:"stderr",...r});UH.stderr.isSupported=Krt.stderr;var Gfa=({children:t,url:e,fallback:r=!0})=>(0,Vtr.jsx)(lz,{transform:n=>UH(n,e,{fallback:r}),children:(0,Vtr.jsx)(ne,{children:t})}),cli=Gfa;Rn();var Bae="800d4c3 (local modifications)";fi();var No=Ie(Pt(),1);var lli=({cliVersion:t,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:o,gcpProject:s})=>{let{t:a}=fr();return(0,No.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,marginY:1,width:"100%",children:[(0,No.jsx)(fe,{marginBottom:1,children:(0,No.jsx)(ne,{bold:!0,color:me.AccentPurple,children:a("about.title")})}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.cliVersion")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:t})})]}),Bae&&!["N/A"].includes(Bae)&&(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.gitCommit")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:Bae})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.model")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:n})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.sandbox")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:r})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.os")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:e})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.authMethod")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:o.startsWith("oauth")?"OAuth":o})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.serviceAgreement")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(cli,{url:"https://terms.alicdn.com/legal-agreement/terms/common_product_agreement/20250225145154377/20250225145154377.html",children:(0,No.jsx)(ne,{color:me.AccentPurple,children:a("about.viewTermsOfService")})})})]}),s&&(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.gcpProject")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:s})})]})]})};await Zr();Rn();var qE=Ie(rr(),1);Gt();var fli=Ie(Pt(),1);var uli=(0,qE.createContext)(void 0),dli=({children:t})=>{let[e,r]=(0,qE.useState)({sessionStartTime:new Date,metrics:R_.getMetrics(),lastPromptTokenCount:0,promptCount:0});(0,qE.useEffect)(()=>{let a=({metrics:c,lastPromptTokenCount:u})=>{r(d=>({...d,metrics:c,lastPromptTokenCount:u}))};return R_.on("update",a),a({metrics:R_.getMetrics(),lastPromptTokenCount:R_.getLastPromptTokenCount()}),()=>{R_.off("update",a)}},[]);let n=(0,qE.useCallback)(()=>{r(a=>({...a,promptCount:a.promptCount+1}))},[]),o=(0,qE.useCallback)(()=>e.promptCount,[e.promptCount]),s=(0,qE.useMemo)(()=>({stats:e,startNewPrompt:n,getPromptCount:o}),[e,n,o]);return(0,fli.jsx)(uli.Provider,{value:s,children:t})},s4=()=>{let t=(0,qE.useContext)(uli);if(t===void 0)throw new Error("useSessionStats must be used within a SessionStatsProvider");return t};Rn();var Xrt=95,Jrt=85,Zrt=75,ent=45;var Pae=(t,e,r={})=>t>=e.green?me.AccentGreen:t>=e.yellow?me.AccentYellow:r.defaultColor||me.AccentRed;function pli(t){return t.api.totalRequests===0?0:t.api.totalErrors/t.api.totalRequests*100}function hli(t){return t.api.totalRequests===0?0:t.api.totalLatencyMs/t.api.totalRequests}function mli(t){return t.tokens.prompt===0?0:t.tokens.cached/t.tokens.prompt*100}var gli=t=>{let{models:e,tools:r}=t,n=Object.values(e).reduce((g,A)=>g+A.api.totalLatencyMs,0),o=r.totalDurationMs,s=n+o,a=s>0?n/s*100:0,c=s>0?o/s*100:0,u=Object.values(e).reduce((g,A)=>g+A.tokens.cached,0),d=Object.values(e).reduce((g,A)=>g+A.tokens.prompt,0),f=d>0?u/d*100:0,p=r.totalDecisions.accept+r.totalDecisions.reject+r.totalDecisions.modify,h=r.totalCalls>0?r.totalSuccess/r.totalCalls*100:0,m=p>0?r.totalDecisions.accept/p*100:0;return{totalApiTime:n,totalToolTime:o,agentActiveTime:s,apiTimePercent:a,toolTimePercent:c,cacheEfficiency:f,totalDecisions:p,successRate:h,agreementRate:m,totalCachedTokens:u,totalPromptTokens:d}};fi();var gi=Ie(Pt(),1);var ive=({title:t,children:e})=>(0,gi.jsxs)(fe,{children:[(0,gi.jsx)(fe,{width:28,children:(0,gi.jsx)(ne,{color:me.LightBlue,children:t})}),e]}),Ali=({title:t,children:e})=>(0,gi.jsxs)(fe,{paddingLeft:2,children:[(0,gi.jsx)(fe,{width:26,children:(0,gi.jsxs)(ne,{children:["\xBB ",t]})}),e]}),yli=({title:t,children:e})=>(0,gi.jsxs)(fe,{flexDirection:"column",width:"100%",marginBottom:1,children:[(0,gi.jsx)(ne,{bold:!0,children:t}),e]}),$fa=({models:t,totalCachedTokens:e,cacheEfficiency:r})=>{let{t:n}=fr(),o=25,s=8,a=15,c=15;return(0,gi.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,gi.jsxs)(fe,{children:[(0,gi.jsx)(fe,{width:o,children:(0,gi.jsx)(ne,{bold:!0,children:n("statsDisplay.modelUsage")})}),(0,gi.jsx)(fe,{width:s,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{bold:!0,children:n("statsDisplay.requests")})}),(0,gi.jsx)(fe,{width:a,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{bold:!0,children:n("statsDisplay.inputTokens")})}),(0,gi.jsx)(fe,{width:c,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{bold:!0,children:n("statsDisplay.outputTokens")})})]}),(0,gi.jsx)(fe,{borderStyle:"round",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:o+s+a+c}),Object.entries(t).map(([u,d])=>(0,gi.jsxs)(fe,{children:[(0,gi.jsx)(fe,{width:o,children:(0,gi.jsx)(ne,{children:u.replace("-001","")})}),(0,gi.jsx)(fe,{width:s,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{children:d.api.totalRequests})}),(0,gi.jsx)(fe,{width:a,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{color:me.AccentYellow,children:d.tokens.prompt.toLocaleString()})}),(0,gi.jsx)(fe,{width:c,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{color:me.AccentYellow,children:d.tokens.candidates.toLocaleString()})})]},u)),r>0&&(0,gi.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,gi.jsxs)(ne,{children:[(0,gi.jsx)(ne,{color:me.AccentGreen,children:n("statsDisplay.savingsHighlight")})," ",e.toLocaleString()," (",r.toFixed(1),"%) ",n("statsDisplay.cacheReduction")]}),(0,gi.jsx)(fe,{height:1}),(0,gi.jsxs)(ne,{color:me.Gray,children:["\xBB ",n("statsDisplay.tokenBredownTip")]})]})]})},tnt=({duration:t,title:e})=>{let{t:r}=fr(),{stats:n}=s4(),{metrics:o}=n,{models:s,tools:a}=o,c=gli(o),u={green:Xrt,yellow:Jrt},d={green:Zrt,yellow:ent},f=Pae(c.successRate,u),p=Pae(c.agreementRate,d),h=()=>e?me.GradientColors&&me.GradientColors.length>0?(0,gi.jsx)(bae,{colors:me.GradientColors,children:(0,gi.jsx)(ne,{bold:!0,children:e})}):(0,gi.jsx)(ne,{bold:!0,color:me.AccentPurple,children:e}):(0,gi.jsx)(ne,{bold:!0,color:me.AccentPurple,children:r("statsDisplay.sessionStats")});return(0,gi.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[h(),(0,gi.jsx)(fe,{height:1}),a.totalCalls>0&&(0,gi.jsxs)(yli,{title:r("statsDisplay.interactionSummary"),children:[(0,gi.jsx)(ive,{title:r("statsDisplay.toolCalls"),children:(0,gi.jsxs)(ne,{children:[a.totalCalls," ("," ",(0,gi.jsxs)(ne,{color:me.AccentGreen,children:["\u2714 ",a.totalSuccess]})," ",(0,gi.jsxs)(ne,{color:me.AccentRed,children:["\u2716 ",a.totalFail]})," )"]})}),(0,gi.jsx)(ive,{title:r("statsDisplay.successRate"),children:(0,gi.jsxs)(ne,{color:f,children:[c.successRate.toFixed(1),"%"]})}),c.totalDecisions>0&&(0,gi.jsx)(ive,{title:r("statsDisplay.userAgreement"),children:(0,gi.jsxs)(ne,{color:p,children:[c.agreementRate.toFixed(1),"%"," ",(0,gi.jsxs)(ne,{color:me.Gray,children:["(",c.totalDecisions," ",r("statsDisplay.reviewed"),")"]})]})})]}),(0,gi.jsxs)(yli,{title:r("statsDisplay.performance"),children:[(0,gi.jsx)(ive,{title:r("statsDisplay.wallTime"),children:(0,gi.jsx)(ne,{children:t})}),(0,gi.jsx)(ive,{title:r("statsDisplay.agentActive"),children:(0,gi.jsx)(ne,{children:x2(c.agentActiveTime)})}),(0,gi.jsx)(Ali,{title:r("statsDisplay.apiTime"),children:(0,gi.jsxs)(ne,{children:[x2(c.totalApiTime)," ",(0,gi.jsxs)(ne,{color:me.Gray,children:["(",c.apiTimePercent.toFixed(1),"%)"]})]})}),(0,gi.jsx)(Ali,{title:r("statsDisplay.toolTime"),children:(0,gi.jsxs)(ne,{children:[x2(c.totalToolTime)," ",(0,gi.jsxs)(ne,{color:me.Gray,children:["(",c.toolTimePercent.toFixed(1),"%)"]})]})})]}),Object.keys(s).length>0&&(0,gi.jsx)($fa,{models:s,totalCachedTokens:c.totalCachedTokens,cacheEfficiency:c.cacheEfficiency})]})};await Zr();Rn();fi();var tc=Ie(Pt(),1);var _li=28,Eli=22,rS=({title:t,values:e,isSubtle:r=!1,isSection:n=!1})=>(0,tc.jsxs)(fe,{children:[(0,tc.jsx)(fe,{width:_li,children:(0,tc.jsx)(ne,{bold:n,color:n?void 0:me.LightBlue,children:r?` \u21B3 ${t}`:t})}),e.map((o,s)=>(0,tc.jsx)(fe,{width:Eli,children:(0,tc.jsx)(ne,{children:o})},s))]}),vli=()=>{let{t}=fr(),{stats:e}=s4(),{models:r}=e.metrics,n=Object.entries(r).filter(([,d])=>d.api.totalRequests>0);if(n.length===0)return(0,tc.jsx)(fe,{borderStyle:"round",borderColor:me.Gray,paddingY:1,paddingX:2,children:(0,tc.jsx)(ne,{children:t("modelStatsDisplay.noApiCalls")})});let o=n.map(([d])=>d),s=d=>n.map(([,f])=>d(f)),a=n.some(([,d])=>d.tokens.thoughts>0),c=n.some(([,d])=>d.tokens.tool>0),u=n.some(([,d])=>d.tokens.cached>0);return(0,tc.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[(0,tc.jsx)(ne,{bold:!0,color:me.AccentPurple,children:t("modelStatsDisplay.title")}),(0,tc.jsx)(fe,{height:1}),(0,tc.jsxs)(fe,{children:[(0,tc.jsx)(fe,{width:_li,children:(0,tc.jsx)(ne,{bold:!0,children:t("modelStatsDisplay.metric")})}),o.map(d=>(0,tc.jsx)(fe,{width:Eli,children:(0,tc.jsx)(ne,{bold:!0,children:d})},d))]}),(0,tc.jsx)(fe,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.api"),values:[],isSection:!0}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.requests"),values:s(d=>d.api.totalRequests.toLocaleString())}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.errors"),values:s(d=>{let f=pli(d);return(0,tc.jsxs)(ne,{color:d.api.totalErrors>0?me.AccentRed:me.Foreground,children:[d.api.totalErrors.toLocaleString()," (",f.toFixed(1),"%)"]})})}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.avgLatency"),values:s(d=>{let f=hli(d);return x2(f)})}),(0,tc.jsx)(fe,{height:1}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.tokens"),values:[],isSection:!0}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.total"),values:s(d=>(0,tc.jsx)(ne,{color:me.AccentYellow,children:d.tokens.total.toLocaleString()}))}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.prompt"),isSubtle:!0,values:s(d=>d.tokens.prompt.toLocaleString())}),u&&(0,tc.jsx)(rS,{title:t("modelStatsDisplay.cached"),isSubtle:!0,values:s(d=>{let f=mli(d);return(0,tc.jsxs)(ne,{color:me.AccentGreen,children:[d.tokens.cached.toLocaleString()," (",f.toFixed(1),"%)"]})})}),a&&(0,tc.jsx)(rS,{title:t("modelStatsDisplay.thoughts"),isSubtle:!0,values:s(d=>d.tokens.thoughts.toLocaleString())}),c&&(0,tc.jsx)(rS,{title:t("modelStatsDisplay.tool"),isSubtle:!0,values:s(d=>d.tokens.tool.toLocaleString())}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.output"),isSubtle:!0,values:s(d=>d.tokens.candidates.toLocaleString())})]})};await Zr();Rn();fi();var Gi=Ie(Pt(),1);var QH=25,jH=8,GH=15,$H=15,qfa=({name:t,stats:e})=>{let r=e.count>0?e.success/e.count*100:0,n=e.count>0?e.durationMs/e.count:0,o=Pae(r,{green:Xrt,yellow:Jrt});return(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH,children:(0,Gi.jsx)(ne,{color:me.LightBlue,children:t})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:e.count})}),(0,Gi.jsx)(fe,{width:GH,justifyContent:"flex-end",children:(0,Gi.jsxs)(ne,{color:o,children:[r.toFixed(1),"%"]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:x2(n)})})]})},bli=()=>{let{t}=fr(),{stats:e}=s4(),{tools:r}=e.metrics,n=Object.entries(r.byName).filter(([,u])=>u.count>0);if(n.length===0)return(0,Gi.jsx)(fe,{borderStyle:"round",borderColor:me.Gray,paddingY:1,paddingX:2,children:(0,Gi.jsx)(ne,{children:t("toolStatsDisplay.noToolCalls")})});let o=Object.values(r.byName).reduce((u,d)=>(u.accept+=d.decisions.accept,u.reject+=d.decisions.reject,u.modify+=d.decisions.modify,u),{accept:0,reject:0,modify:0}),s=o.accept+o.reject+o.modify,a=s>0?o.accept/s*100:0,c=Pae(a,{green:Zrt,yellow:ent});return(0,Gi.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",paddingY:1,paddingX:2,width:70,children:[(0,Gi.jsx)(ne,{bold:!0,color:me.AccentPurple,children:t("toolStatsDisplay.title")}),(0,Gi.jsx)(fe,{height:1}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH,children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.toolName")})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.calls")})}),(0,Gi.jsx)(fe,{width:GH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.successRate")})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.avgDuration")})})]}),(0,Gi.jsx)(fe,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:"100%"}),n.map(([u,d])=>(0,Gi.jsx)(qfa,{name:u,stats:d},u)),(0,Gi.jsx)(fe,{height:1}),(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.userDecisionSummary")}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsx)(ne,{color:me.LightBlue,children:t("toolStatsDisplay.totalReviewedSuggestions")})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:s})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.accepted")]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:me.AccentGreen,children:o.accept})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.rejected")]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:me.AccentRed,children:o.reject})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.modified")]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:me.AccentYellow,children:o.modify})})]}),(0,Gi.jsx)(fe,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:"100%"}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsxs)(ne,{children:[" ",t("toolStatsDisplay.overallAgreementRate")]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,color:s>0?c:void 0,children:s>0?`${a.toFixed(1)}%`:"--"})})]})]})};fi();var Sli=Ie(Pt(),1);var Cli=({duration:t})=>{let{t:e}=fr();return(0,Sli.jsx)(tnt,{title:e("session.agentPoweringDown"),duration:t})};var rnt=Ie(rr(),1);await Zr();Rn();Gt();var I2=Ie(Pt(),1);function Hfa(t,e){if(!t)return"";let r=t.replace(/\n\s*\n\s*\n/g,`
|
|
4563
|
+
`))}}catch(A){console.warn("Failed to execute notification hook:",A)}},[s,e,t,a]);(0,Vrt.useEffect)(()=>{d()},[d]),Tn(A=>{r&&A.name==="escape"&&c(xn.Cancel)},{isActive:r});let f=A=>c(A),p=null,h,m=new Array;function g(){if(m.length===0)throw new Error("Options not provided for confirmation message");if(n===void 0)return;let A=2,y=1,E=1,v=1,b=m.length,S=A+y+E+v+b;return Math.max(n-S,1)}if(t.type==="edit"){if(t.isModifying)return(0,yd.jsxs)(fe,{minWidth:"90%",borderStyle:"round",borderColor:me.Gray,justifyContent:"space-around",padding:1,overflow:"hidden",children:[(0,yd.jsxs)(ne,{children:[a("toolConfirmationMessage.modifyInProgress")," "]}),(0,yd.jsx)(ne,{color:me.AccentGreen,children:a("toolConfirmationMessage.saveAndCloseEditor")})]});h=a("toolConfirmationMessage.applyChangeQuestion"),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:xn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlways"),value:xn.ProceedAlways},{label:a("toolConfirmationMessage.modifyWithEditor"),value:xn.ModifyWithEditor},{label:a("toolConfirmationMessage.noSuggestChanges"),value:xn.Cancel}),p=(0,yd.jsx)(X8,{diffContent:t.fileDiff,filename:t.fileName,availableTerminalHeight:g(),terminalWidth:u})}else if(t.type==="exec"){let A=t;h=a("toolConfirmationMessage.allowExecutionQuestion",{command:A.rootCommand}),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:xn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlwaysEllipsis"),value:xn.ProceedAlways},{label:a("toolConfirmationMessage.noSuggestChanges"),value:xn.Cancel});let y=g();y!==void 0&&(y-=2),p=(0,yd.jsx)(fe,{flexDirection:"column",children:(0,yd.jsx)(fe,{paddingX:1,marginLeft:1,children:(0,yd.jsx)(Y0,{maxHeight:y,maxWidth:Math.max(u-4,1),children:(0,yd.jsx)(fe,{children:(0,yd.jsx)(ne,{color:me.AccentCyan,children:A.command})})})})})}else if(t.type==="info"){let A=t,y=A.urls&&!(A.urls.length===1&&A.urls[0]===A.prompt);h=a("toolConfirmationMessage.proceedQuestion"),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:xn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlways"),value:xn.ProceedAlways},{label:a("toolConfirmationMessage.noSuggestChanges"),value:xn.Cancel}),p=(0,yd.jsxs)(fe,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,yd.jsx)(ne,{color:me.AccentCyan,children:A.prompt}),y&&A.urls&&A.urls.length>0&&(0,yd.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,yd.jsx)(ne,{children:a("toolConfirmationMessage.urlsToFetch")}),A.urls.map(E=>(0,yd.jsxs)(ne,{children:[" - ",E]},E))]})]})}else{let A=t;p=(0,yd.jsxs)(fe,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,yd.jsxs)(ne,{color:me.AccentCyan,children:[a("toolConfirmationMessage.mcpServer"),": ",A.serverName]}),(0,yd.jsxs)(ne,{color:me.AccentCyan,children:[a("toolConfirmationMessage.tool"),": ",A.toolName]})]}),h=a("toolConfirmationMessage.allowMcpToolQuestion",{toolName:A.toolName,serverName:A.serverName}),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:xn.ProceedOnce},{label:a("toolConfirmationMessage.yesAlwaysAllowTool",{toolName:A.toolName,serverName:A.serverName}),value:xn.ProceedAlwaysTool},{label:a("toolConfirmationMessage.yesAlwaysAllowAllTools",{serverName:A.serverName}),value:xn.ProceedAlwaysServer},{label:a("toolConfirmationMessage.noSuggestChanges"),value:xn.Cancel})}return(0,yd.jsxs)(fe,{flexDirection:"column",padding:1,width:u,children:[(0,yd.jsx)(fe,{flexGrow:1,flexShrink:1,overflow:"hidden",marginBottom:1,children:p}),(0,yd.jsx)(fe,{marginBottom:1,flexShrink:0,children:(0,yd.jsx)(ne,{wrap:"truncate",children:h})}),(0,yd.jsx)(fe,{flexShrink:0,children:(0,yd.jsx)(Lu,{items:m,onSelect:f,isFocused:r})})]})};var PD=Ie(Pt(),1);var Gtr=({toolCalls:t,availableTerminalHeight:e,terminalWidth:r,config:n,isFocused:o=!0,subAgentState:s,taskTool:a,constrainHeight:c=!0,isTaskAbbreviated:u=!0,hookManager:d})=>{let p=r-4,h=(0,nli.useMemo)(()=>t.find(y=>y.status==="Confirming"),[t]),m=0;for(let y of t)y.resultDisplay!==void 0&&y.resultDisplay!==""&&m++;let g=t.length-m,A=e?Math.max(Math.floor((e-3-g)/Math.max(1,m)),1):void 0;return(0,PD.jsx)(fe,{flexDirection:"column",width:"100%",marginLeft:1,children:t.map(y=>{let E=h?.callId===y.callId;return(0,PD.jsxs)(fe,{flexDirection:"column",minHeight:1,children:[(0,PD.jsx)(fe,{flexDirection:"row",alignItems:"center",children:y.name.toLowerCase()==="task"?u?(0,PD.jsx)(tli,{callId:y.callId,name:y.name,description:y.description,resultDisplay:y.resultDisplay,status:y.status,confirmationDetails:y.confirmationDetails,terminalWidth:p,availableTerminalHeight:A,emphasis:E?"high":h?"low":"medium",subAgentState:s,taskTool:a,renderOutputAsMarkdown:y.renderOutputAsMarkdown}):(0,PD.jsx)(Zci,{callId:y.callId,name:y.name,description:y.description,resultDisplay:y.resultDisplay,status:y.status,confirmationDetails:y.confirmationDetails,availableTerminalHeight:A,terminalWidth:p,emphasis:E?"high":h?"low":"medium",renderOutputAsMarkdown:y.renderOutputAsMarkdown,subAgentState:s,config:n,taskTool:a,constrainHeight:c}):(0,PD.jsx)(Grt,{callId:y.callId,name:y.name,description:y.description,resultDisplay:y.resultDisplay,status:y.status,confirmationDetails:y.confirmationDetails,availableTerminalHeight:A,terminalWidth:p,emphasis:E?"high":h?"low":"medium",renderOutputAsMarkdown:y.renderOutputAsMarkdown,subAgentState:s,config:n,taskTool:a,isTaskAbbreviated:u})}),y.status==="Confirming"&&E&&y.confirmationDetails&&(0,PD.jsx)(rli,{confirmationDetails:y.confirmationDetails,config:n,isFocused:o,availableTerminalHeight:A,terminalWidth:p,hookManager:d})]},y.callId)})})};await Zr();Rn();fi();var Lp=Ie(Pt(),1);var qtr=({compression:t,showDetails:e=!1})=>{let{t:r}=fr();return t.isPending?(0,Lp.jsxs)(fe,{flexDirection:"row",children:[(0,Lp.jsx)(fe,{marginRight:1,children:(0,Lp.jsx)(vae,{type:"dots"})}),(0,Lp.jsx)(fe,{children:(0,Lp.jsx)(ne,{color:me.AccentPurple,children:r("compressionMessage.compressingHistory")})})]}):(0,Lp.jsxs)(fe,{flexDirection:"column",children:[(0,Lp.jsx)(fe,{marginY:1,children:(0,Lp.jsxs)(ne,{color:me.Gray,children:["==================== ",r("compressionMessage.previousConversationCompressed")," ===================="]})}),(0,Lp.jsxs)(fe,{flexDirection:"row",alignItems:"center",children:[(0,Lp.jsx)(ne,{color:me.AccentPurple,children:"\xB7"}),(0,Lp.jsx)(ne,{color:me.AccentPurple,children:r("compressionMessage.contextCompressed",{originalTokenCount:t.originalTokenCount?.toLocaleString()??"unknown",newTokenCount:t.newTokenCount?.toLocaleString()??"unknown"})}),(0,Lp.jsx)(ne,{color:me.Gray,children:r("compressionMessage.expandCollapseHint",{action:r(e?"compressionMessage.collapse":"compressionMessage.expand")})})]}),e&&t.summary&&(0,Lp.jsxs)(fe,{flexDirection:"column",marginTop:1,marginLeft:2,children:[(0,Lp.jsx)(fe,{marginBottom:1,children:(0,Lp.jsx)(ne,{color:me.Gray,children:r("compressionMessage.summaryLabel")})}),(0,Lp.jsx)(fe,{children:(0,Lp.jsx)(ne,{color:me.Foreground,wrap:"wrap",children:t.summary})}),(0,Lp.jsx)(fe,{marginTop:1,children:(0,Lp.jsx)(ne,{color:me.Gray,children:r("compressionMessage.collapseHint")})})]})]})};await Zr();Rn();var Wrt=Ie(Pt(),1);var ili=({text:t})=>(0,Wrt.jsx)(fe,{borderStyle:"round",borderColor:me.AccentPurple,flexDirection:"row",paddingX:2,paddingY:0,marginY:0,alignSelf:"flex-start",children:(0,Wrt.jsx)(fe,{flexGrow:1,children:(0,Wrt.jsx)(ne,{wrap:"wrap",color:me.Gray,children:t})})});await Zr();await Zr();var Vtr=Ie(Pt(),1);await Zr();Lle();import nve from"node:process";import Htr from"node:process";import Mfa from"node:os";import oli from"node:tty";function o4(t,e=globalThis.Deno?globalThis.Deno.args:Htr.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}var{env:zd}=Htr,zrt;o4("no-color")||o4("no-colors")||o4("color=false")||o4("color=never")?zrt=0:(o4("color")||o4("colors")||o4("color=true")||o4("color=always"))&&(zrt=1);function Ffa(){if(!("FORCE_COLOR"in zd))return;if(zd.FORCE_COLOR==="true")return 1;if(zd.FORCE_COLOR==="false")return 0;if(zd.FORCE_COLOR.length===0)return 1;let t=Math.min(Number.parseInt(zd.FORCE_COLOR,10),3);if([0,1,2,3].includes(t))return t}function Lfa(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Ufa(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let n=Ffa();n!==void 0&&(zrt=n);let o=r?zrt:n;if(o===0)return 0;if(r){if(o4("color=16m")||o4("color=full")||o4("color=truecolor"))return 3;if(o4("color=256"))return 2}if("TF_BUILD"in zd&&"AGENT_NAME"in zd)return 1;if(t&&!e&&o===void 0)return 0;let s=o||0;if(zd.TERM==="dumb")return s;if(Htr.platform==="win32"){let a=Mfa.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in zd)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(a=>a in zd)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(a=>a in zd)||zd.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in zd)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(zd.TEAMCITY_VERSION)?1:0;if(zd.COLORTERM==="truecolor"||zd.TERM==="xterm-kitty"||zd.TERM==="xterm-ghostty"||zd.TERM==="wezterm")return 3;if("TERM_PROGRAM"in zd){let a=Number.parseInt((zd.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(zd.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(zd.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(zd.TERM)||"COLORTERM"in zd?1:s}function Yrt(t,e={}){let r=Ufa(t,{streamIsTTY:t&&t.isTTY,...e});return Lfa(r)}var Yel={stdout:Yrt({isTTY:oli.isatty(1)}),stderr:Yrt({isTTY:oli.isatty(2)})};import Qfa from"process";function gM(t,e=Qfa.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}function sli(t=""){if(/^\d{3,4}$/.test(t)){let r=/(\d{1,2})(\d{2})/.exec(t)??[];return{major:0,minor:Number.parseInt(r[1],10),patch:Number.parseInt(r[2],10)}}let e=(t??"").split(".").map(r=>Number.parseInt(r,10));return{major:e[0],minor:e[1],patch:e[2]}}function ali(t){let{CI:e,CURSOR_TRACE_ID:r,FORCE_HYPERLINK:n,NETLIFY:o,TEAMCITY_VERSION:s,TERM_PROGRAM:a,TERM_PROGRAM_VERSION:c,VTE_VERSION:u,TERM:d}=nve.env;if(n)return!(n.length>0&&Number.parseInt(n,10)===0);if(gM("no-hyperlink")||gM("no-hyperlinks")||gM("hyperlink=false")||gM("hyperlink=never"))return!1;if(gM("hyperlink=true")||gM("hyperlink=always")||o)return!0;if(!Yrt(t)||t&&!t.isTTY)return!1;if("WT_SESSION"in nve.env)return!0;if(nve.platform==="win32"||e||s)return!1;if(a){let f=sli(c);switch(a){case"iTerm.app":return f.major===3?f.minor>=1:f.major>3;case"WezTerm":return/^0-unstable-\d{4}-\d{2}-\d{2}$/.test(c)?c.slice(11)>="2020-06-20":f.major>=20200620;case"vscode":return r?!0:f.major>1||f.major===1&&f.minor>=72;case"ghostty":return!0}}if(u){if(u==="0.50.0")return!1;let f=sli(u);return f.major>0||f.minor>=50}switch(d){case"alacritty":return!0;case"xterm-kitty":return!0}return!1}var jfa={stdout:ali(nve.stdout),stderr:ali(nve.stderr)},Krt=jfa;function UH(t,e,{target:r="stdout",...n}={}){return Krt[r]?Kp.link(t,e):n.fallback===!1?t:typeof n.fallback=="function"?n.fallback(t,e):`${t} ${e}`}UH.isSupported=Krt.stdout;UH.stderr=(t,e,r={})=>UH(t,e,{target:"stderr",...r});UH.stderr.isSupported=Krt.stderr;var Gfa=({children:t,url:e,fallback:r=!0})=>(0,Vtr.jsx)(lz,{transform:n=>UH(n,e,{fallback:r}),children:(0,Vtr.jsx)(ne,{children:t})}),cli=Gfa;Rn();var Bae="4902cb7 (local modifications)";fi();var No=Ie(Pt(),1);var lli=({cliVersion:t,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:o,gcpProject:s})=>{let{t:a}=fr();return(0,No.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",padding:1,marginY:1,width:"100%",children:[(0,No.jsx)(fe,{marginBottom:1,children:(0,No.jsx)(ne,{bold:!0,color:me.AccentPurple,children:a("about.title")})}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.cliVersion")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:t})})]}),Bae&&!["N/A"].includes(Bae)&&(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.gitCommit")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:Bae})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.model")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:n})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.sandbox")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:r})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.os")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:e})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.authMethod")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:o.startsWith("oauth")?"OAuth":o})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.serviceAgreement")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(cli,{url:"https://terms.alicdn.com/legal-agreement/terms/common_product_agreement/20250225145154377/20250225145154377.html",children:(0,No.jsx)(ne,{color:me.AccentPurple,children:a("about.viewTermsOfService")})})})]}),s&&(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:me.LightBlue,children:a("about.gcpProject")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:s})})]})]})};await Zr();Rn();var qE=Ie(rr(),1);Gt();var fli=Ie(Pt(),1);var uli=(0,qE.createContext)(void 0),dli=({children:t})=>{let[e,r]=(0,qE.useState)({sessionStartTime:new Date,metrics:R_.getMetrics(),lastPromptTokenCount:0,promptCount:0});(0,qE.useEffect)(()=>{let a=({metrics:c,lastPromptTokenCount:u})=>{r(d=>({...d,metrics:c,lastPromptTokenCount:u}))};return R_.on("update",a),a({metrics:R_.getMetrics(),lastPromptTokenCount:R_.getLastPromptTokenCount()}),()=>{R_.off("update",a)}},[]);let n=(0,qE.useCallback)(()=>{r(a=>({...a,promptCount:a.promptCount+1}))},[]),o=(0,qE.useCallback)(()=>e.promptCount,[e.promptCount]),s=(0,qE.useMemo)(()=>({stats:e,startNewPrompt:n,getPromptCount:o}),[e,n,o]);return(0,fli.jsx)(uli.Provider,{value:s,children:t})},s4=()=>{let t=(0,qE.useContext)(uli);if(t===void 0)throw new Error("useSessionStats must be used within a SessionStatsProvider");return t};Rn();var Xrt=95,Jrt=85,Zrt=75,ent=45;var Pae=(t,e,r={})=>t>=e.green?me.AccentGreen:t>=e.yellow?me.AccentYellow:r.defaultColor||me.AccentRed;function pli(t){return t.api.totalRequests===0?0:t.api.totalErrors/t.api.totalRequests*100}function hli(t){return t.api.totalRequests===0?0:t.api.totalLatencyMs/t.api.totalRequests}function mli(t){return t.tokens.prompt===0?0:t.tokens.cached/t.tokens.prompt*100}var gli=t=>{let{models:e,tools:r}=t,n=Object.values(e).reduce((g,A)=>g+A.api.totalLatencyMs,0),o=r.totalDurationMs,s=n+o,a=s>0?n/s*100:0,c=s>0?o/s*100:0,u=Object.values(e).reduce((g,A)=>g+A.tokens.cached,0),d=Object.values(e).reduce((g,A)=>g+A.tokens.prompt,0),f=d>0?u/d*100:0,p=r.totalDecisions.accept+r.totalDecisions.reject+r.totalDecisions.modify,h=r.totalCalls>0?r.totalSuccess/r.totalCalls*100:0,m=p>0?r.totalDecisions.accept/p*100:0;return{totalApiTime:n,totalToolTime:o,agentActiveTime:s,apiTimePercent:a,toolTimePercent:c,cacheEfficiency:f,totalDecisions:p,successRate:h,agreementRate:m,totalCachedTokens:u,totalPromptTokens:d}};fi();var gi=Ie(Pt(),1);var ive=({title:t,children:e})=>(0,gi.jsxs)(fe,{children:[(0,gi.jsx)(fe,{width:28,children:(0,gi.jsx)(ne,{color:me.LightBlue,children:t})}),e]}),Ali=({title:t,children:e})=>(0,gi.jsxs)(fe,{paddingLeft:2,children:[(0,gi.jsx)(fe,{width:26,children:(0,gi.jsxs)(ne,{children:["\xBB ",t]})}),e]}),yli=({title:t,children:e})=>(0,gi.jsxs)(fe,{flexDirection:"column",width:"100%",marginBottom:1,children:[(0,gi.jsx)(ne,{bold:!0,children:t}),e]}),$fa=({models:t,totalCachedTokens:e,cacheEfficiency:r})=>{let{t:n}=fr(),o=25,s=8,a=15,c=15;return(0,gi.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,gi.jsxs)(fe,{children:[(0,gi.jsx)(fe,{width:o,children:(0,gi.jsx)(ne,{bold:!0,children:n("statsDisplay.modelUsage")})}),(0,gi.jsx)(fe,{width:s,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{bold:!0,children:n("statsDisplay.requests")})}),(0,gi.jsx)(fe,{width:a,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{bold:!0,children:n("statsDisplay.inputTokens")})}),(0,gi.jsx)(fe,{width:c,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{bold:!0,children:n("statsDisplay.outputTokens")})})]}),(0,gi.jsx)(fe,{borderStyle:"round",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:o+s+a+c}),Object.entries(t).map(([u,d])=>(0,gi.jsxs)(fe,{children:[(0,gi.jsx)(fe,{width:o,children:(0,gi.jsx)(ne,{children:u.replace("-001","")})}),(0,gi.jsx)(fe,{width:s,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{children:d.api.totalRequests})}),(0,gi.jsx)(fe,{width:a,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{color:me.AccentYellow,children:d.tokens.prompt.toLocaleString()})}),(0,gi.jsx)(fe,{width:c,justifyContent:"flex-end",children:(0,gi.jsx)(ne,{color:me.AccentYellow,children:d.tokens.candidates.toLocaleString()})})]},u)),r>0&&(0,gi.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,gi.jsxs)(ne,{children:[(0,gi.jsx)(ne,{color:me.AccentGreen,children:n("statsDisplay.savingsHighlight")})," ",e.toLocaleString()," (",r.toFixed(1),"%) ",n("statsDisplay.cacheReduction")]}),(0,gi.jsx)(fe,{height:1}),(0,gi.jsxs)(ne,{color:me.Gray,children:["\xBB ",n("statsDisplay.tokenBredownTip")]})]})]})},tnt=({duration:t,title:e})=>{let{t:r}=fr(),{stats:n}=s4(),{metrics:o}=n,{models:s,tools:a}=o,c=gli(o),u={green:Xrt,yellow:Jrt},d={green:Zrt,yellow:ent},f=Pae(c.successRate,u),p=Pae(c.agreementRate,d),h=()=>e?me.GradientColors&&me.GradientColors.length>0?(0,gi.jsx)(bae,{colors:me.GradientColors,children:(0,gi.jsx)(ne,{bold:!0,children:e})}):(0,gi.jsx)(ne,{bold:!0,color:me.AccentPurple,children:e}):(0,gi.jsx)(ne,{bold:!0,color:me.AccentPurple,children:r("statsDisplay.sessionStats")});return(0,gi.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[h(),(0,gi.jsx)(fe,{height:1}),a.totalCalls>0&&(0,gi.jsxs)(yli,{title:r("statsDisplay.interactionSummary"),children:[(0,gi.jsx)(ive,{title:r("statsDisplay.toolCalls"),children:(0,gi.jsxs)(ne,{children:[a.totalCalls," ("," ",(0,gi.jsxs)(ne,{color:me.AccentGreen,children:["\u2714 ",a.totalSuccess]})," ",(0,gi.jsxs)(ne,{color:me.AccentRed,children:["\u2716 ",a.totalFail]})," )"]})}),(0,gi.jsx)(ive,{title:r("statsDisplay.successRate"),children:(0,gi.jsxs)(ne,{color:f,children:[c.successRate.toFixed(1),"%"]})}),c.totalDecisions>0&&(0,gi.jsx)(ive,{title:r("statsDisplay.userAgreement"),children:(0,gi.jsxs)(ne,{color:p,children:[c.agreementRate.toFixed(1),"%"," ",(0,gi.jsxs)(ne,{color:me.Gray,children:["(",c.totalDecisions," ",r("statsDisplay.reviewed"),")"]})]})})]}),(0,gi.jsxs)(yli,{title:r("statsDisplay.performance"),children:[(0,gi.jsx)(ive,{title:r("statsDisplay.wallTime"),children:(0,gi.jsx)(ne,{children:t})}),(0,gi.jsx)(ive,{title:r("statsDisplay.agentActive"),children:(0,gi.jsx)(ne,{children:x2(c.agentActiveTime)})}),(0,gi.jsx)(Ali,{title:r("statsDisplay.apiTime"),children:(0,gi.jsxs)(ne,{children:[x2(c.totalApiTime)," ",(0,gi.jsxs)(ne,{color:me.Gray,children:["(",c.apiTimePercent.toFixed(1),"%)"]})]})}),(0,gi.jsx)(Ali,{title:r("statsDisplay.toolTime"),children:(0,gi.jsxs)(ne,{children:[x2(c.totalToolTime)," ",(0,gi.jsxs)(ne,{color:me.Gray,children:["(",c.toolTimePercent.toFixed(1),"%)"]})]})})]}),Object.keys(s).length>0&&(0,gi.jsx)($fa,{models:s,totalCachedTokens:c.totalCachedTokens,cacheEfficiency:c.cacheEfficiency})]})};await Zr();Rn();fi();var tc=Ie(Pt(),1);var _li=28,Eli=22,rS=({title:t,values:e,isSubtle:r=!1,isSection:n=!1})=>(0,tc.jsxs)(fe,{children:[(0,tc.jsx)(fe,{width:_li,children:(0,tc.jsx)(ne,{bold:n,color:n?void 0:me.LightBlue,children:r?` \u21B3 ${t}`:t})}),e.map((o,s)=>(0,tc.jsx)(fe,{width:Eli,children:(0,tc.jsx)(ne,{children:o})},s))]}),vli=()=>{let{t}=fr(),{stats:e}=s4(),{models:r}=e.metrics,n=Object.entries(r).filter(([,d])=>d.api.totalRequests>0);if(n.length===0)return(0,tc.jsx)(fe,{borderStyle:"round",borderColor:me.Gray,paddingY:1,paddingX:2,children:(0,tc.jsx)(ne,{children:t("modelStatsDisplay.noApiCalls")})});let o=n.map(([d])=>d),s=d=>n.map(([,f])=>d(f)),a=n.some(([,d])=>d.tokens.thoughts>0),c=n.some(([,d])=>d.tokens.tool>0),u=n.some(([,d])=>d.tokens.cached>0);return(0,tc.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[(0,tc.jsx)(ne,{bold:!0,color:me.AccentPurple,children:t("modelStatsDisplay.title")}),(0,tc.jsx)(fe,{height:1}),(0,tc.jsxs)(fe,{children:[(0,tc.jsx)(fe,{width:_li,children:(0,tc.jsx)(ne,{bold:!0,children:t("modelStatsDisplay.metric")})}),o.map(d=>(0,tc.jsx)(fe,{width:Eli,children:(0,tc.jsx)(ne,{bold:!0,children:d})},d))]}),(0,tc.jsx)(fe,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.api"),values:[],isSection:!0}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.requests"),values:s(d=>d.api.totalRequests.toLocaleString())}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.errors"),values:s(d=>{let f=pli(d);return(0,tc.jsxs)(ne,{color:d.api.totalErrors>0?me.AccentRed:me.Foreground,children:[d.api.totalErrors.toLocaleString()," (",f.toFixed(1),"%)"]})})}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.avgLatency"),values:s(d=>{let f=hli(d);return x2(f)})}),(0,tc.jsx)(fe,{height:1}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.tokens"),values:[],isSection:!0}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.total"),values:s(d=>(0,tc.jsx)(ne,{color:me.AccentYellow,children:d.tokens.total.toLocaleString()}))}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.prompt"),isSubtle:!0,values:s(d=>d.tokens.prompt.toLocaleString())}),u&&(0,tc.jsx)(rS,{title:t("modelStatsDisplay.cached"),isSubtle:!0,values:s(d=>{let f=mli(d);return(0,tc.jsxs)(ne,{color:me.AccentGreen,children:[d.tokens.cached.toLocaleString()," (",f.toFixed(1),"%)"]})})}),a&&(0,tc.jsx)(rS,{title:t("modelStatsDisplay.thoughts"),isSubtle:!0,values:s(d=>d.tokens.thoughts.toLocaleString())}),c&&(0,tc.jsx)(rS,{title:t("modelStatsDisplay.tool"),isSubtle:!0,values:s(d=>d.tokens.tool.toLocaleString())}),(0,tc.jsx)(rS,{title:t("modelStatsDisplay.output"),isSubtle:!0,values:s(d=>d.tokens.candidates.toLocaleString())})]})};await Zr();Rn();fi();var Gi=Ie(Pt(),1);var QH=25,jH=8,GH=15,$H=15,qfa=({name:t,stats:e})=>{let r=e.count>0?e.success/e.count*100:0,n=e.count>0?e.durationMs/e.count:0,o=Pae(r,{green:Xrt,yellow:Jrt});return(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH,children:(0,Gi.jsx)(ne,{color:me.LightBlue,children:t})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:e.count})}),(0,Gi.jsx)(fe,{width:GH,justifyContent:"flex-end",children:(0,Gi.jsxs)(ne,{color:o,children:[r.toFixed(1),"%"]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:x2(n)})})]})},bli=()=>{let{t}=fr(),{stats:e}=s4(),{tools:r}=e.metrics,n=Object.entries(r.byName).filter(([,u])=>u.count>0);if(n.length===0)return(0,Gi.jsx)(fe,{borderStyle:"round",borderColor:me.Gray,paddingY:1,paddingX:2,children:(0,Gi.jsx)(ne,{children:t("toolStatsDisplay.noToolCalls")})});let o=Object.values(r.byName).reduce((u,d)=>(u.accept+=d.decisions.accept,u.reject+=d.decisions.reject,u.modify+=d.decisions.modify,u),{accept:0,reject:0,modify:0}),s=o.accept+o.reject+o.modify,a=s>0?o.accept/s*100:0,c=Pae(a,{green:Zrt,yellow:ent});return(0,Gi.jsxs)(fe,{borderStyle:"round",borderColor:me.Gray,flexDirection:"column",paddingY:1,paddingX:2,width:70,children:[(0,Gi.jsx)(ne,{bold:!0,color:me.AccentPurple,children:t("toolStatsDisplay.title")}),(0,Gi.jsx)(fe,{height:1}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH,children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.toolName")})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.calls")})}),(0,Gi.jsx)(fe,{width:GH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.successRate")})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.avgDuration")})})]}),(0,Gi.jsx)(fe,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:"100%"}),n.map(([u,d])=>(0,Gi.jsx)(qfa,{name:u,stats:d},u)),(0,Gi.jsx)(fe,{height:1}),(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.userDecisionSummary")}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsx)(ne,{color:me.LightBlue,children:t("toolStatsDisplay.totalReviewedSuggestions")})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:s})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.accepted")]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:me.AccentGreen,children:o.accept})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.rejected")]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:me.AccentRed,children:o.reject})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.modified")]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:me.AccentYellow,children:o.modify})})]}),(0,Gi.jsx)(fe,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:"100%"}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:QH+jH+GH,children:(0,Gi.jsxs)(ne,{children:[" ",t("toolStatsDisplay.overallAgreementRate")]})}),(0,Gi.jsx)(fe,{width:$H,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,color:s>0?c:void 0,children:s>0?`${a.toFixed(1)}%`:"--"})})]})]})};fi();var Sli=Ie(Pt(),1);var Cli=({duration:t})=>{let{t:e}=fr();return(0,Sli.jsx)(tnt,{title:e("session.agentPoweringDown"),duration:t})};var rnt=Ie(rr(),1);await Zr();Rn();Gt();var I2=Ie(Pt(),1);function Hfa(t,e){if(!t)return"";let r=t.replace(/\n\s*\n\s*\n/g,`
|
|
4564
4564
|
|
|
4565
4565
|
`);if(e&&e>20){let n=r.split(`
|
|
4566
4566
|
`),o=[];for(let s of n)if(s.length<=e-4)o.push(s);else{let a=s.split(" "),c="";for(let u of a)(c+" "+u).length<=e-4?c=c?c+" "+u:u:(c&&o.push(c),c=u);c&&o.push(c)}r=o.join(`
|
|
@@ -5678,7 +5678,7 @@ ${O.t("gemini.errors.criticalUnhandledRejection")}
|
|
|
5678
5678
|
=========================================
|
|
5679
5679
|
${O.t("gemini.errors.reason",{reason:e})}${e instanceof Error&&e.stack?`
|
|
5680
5680
|
${O.t("gemini.errors.stackTrace")}
|
|
5681
|
-
${e.stack}`:""}`;qs.emit("log-error",n),t||(t=!0,qs.emit("open-debug-console"))})}function Dya(){console.log(O.t("gemini.crashDiagnosticsEnabled")),process.setUncaughtExceptionCaptureCallback(t=>{let e={timestamp:new Date().toISOString(),error:{name:t.name,message:t.message,stack:t.stack},memory:process.memoryUsage(),pid:process.pid,cwd:process.cwd(),nodeVersion:process.version,platform:process.platform,arch:process.arch,uptime:process.uptime(),env:{NODE_ENV:"production",SANDBOX:process.env.SANDBOX,CLI_VERSION:"0.4.
|
|
5681
|
+
${e.stack}`:""}`;qs.emit("log-error",n),t||(t=!0,qs.emit("open-debug-console"))})}function Dya(){console.log(O.t("gemini.crashDiagnosticsEnabled")),process.setUncaughtExceptionCaptureCallback(t=>{let e={timestamp:new Date().toISOString(),error:{name:t.name,message:t.message,stack:t.stack},memory:process.memoryUsage(),pid:process.pid,cwd:process.cwd(),nodeVersion:process.version,platform:process.platform,arch:process.arch,uptime:process.uptime(),env:{NODE_ENV:"production",SANDBOX:process.env.SANDBOX,CLI_VERSION:"0.4.3"}},r=`crash-${Date.now()}-${process.pid}.json`,n=Eya.join(process.cwd(),r);try{Sya.writeFileSync(n,JSON.stringify(e,null,2)),console.error(O.t("gemini.crashDetected",{crashFilePath:n})),console.error(O.t("gemini.coreDumpWillBeGenerated"))}catch(o){console.error(O.t("gemini.failedToWriteCrashFile"),o)}process.abort()}),process.on("warning",t=>{console.warn(O.t("gemini.debug.nodejsWarning"),{name:t.name,message:t.message,stack:t.stack})}),process.on("unhandledRejection",(t,e)=>{console.error(O.t("gemini.debug.unhandledPromiseRejectionDetected"),{reason:t,promise:e.toString()})})}async function P2i(){if(Iya(),B2i.platform()==="win32")try{let{execSync:g}=await import("node:child_process");g("chcp 65001",{stdio:"ignore"})}catch{}let t=process.cwd(),e=yl(t);if(!e.user.settings.cna){let g=await IOe();g&&e.setValue("User","cna",g)}if(await ooi(),e.errors.length>0){for(let g of e.errors){let A=O.t("gemini.errorInFile",{path:g.path,message:g.message});process.env.NO_COLOR||(A=`\x1B[31m${A}\x1B[0m`),console.error(A),console.error(O.t("gemini.pleaseFixFileAndTryAgain",{path:g.path}))}process.exit(1)}let r=await nrt(),n=typeof r.resume=="string";(!!r.prompt&&!r.promptInteractive&&!r.continue&&(!r.resume||n)||r.experimentalAcp)&&(process.env.IFLOW_NON_INTERACTIVE="true");let s=rM(t),a=n&&typeof r.resume=="string"?r.resume:Og.generateSessionId(),c=await TH(e.merged,s,a,r);if(O.changeLanguage(c.getLanguage()),c.getDebugMode()&&Dya(),bya.setDefaultResultOrder(xya(e.merged.dnsResolutionOrder)),r.promptInteractive&&!process.stdin.isTTY&&(console.error(O.t("gemini.errors.promptInteractiveFlagNotSupported")),process.exit(1)),c.getListExtensions()){console.debug(O.t("gemini.installedExtensions"));for(let g of s)console.debug(`- ${g.config.name}`);process.exit(0)}if(r._&&r._[0]==="agent"){let{agentCommand:g}=await Promise.resolve().then(()=>(Ger(),eoi)),A=(await Promise.resolve().then(()=>(Hir(),qir))).default;await A().scriptName("iflow").command(g).help().version(!1).parse(),process.exit(0)}if(r._&&r._[0]==="commands"){let{commandsCommand:g}=await Promise.resolve().then(()=>(Qer(),Qii)),A=(await Promise.resolve().then(()=>(Hir(),qir))).default;await A().scriptName("iflow").command(g).help().version(!1).parse(),process.exit(0)}if(e.merged.selectedAuthType||process.env.CLOUD_SHELL==="true"&&e.setValue("User","selectedAuthType",Yt.CLOUD_SHELL),Esi(c.getDebugMode()),await c.initialize(),c.getExperimentalAcp()?c.setUsageMode("sdk"):c.setUsageMode("interactive"),Js.loadCustomThemes(e.merged.customThemes),e.merged.theme&&(Js.setActiveTheme(e.merged.theme)||console.warn(O.t("gemini.themeNotFound",{theme:e.merged.theme}))),!process.env.SANDBOX){let g=e.merged.autoConfigureMaxOldSpaceSize?wya(c):[],A=c.getSandbox();if(A){if(e.merged.selectedAuthType&&!e.merged.useExternalAuth)try{let y=XP(e.merged.selectedAuthType);if(y)throw new Error(y);await c.refreshAuth(e.merged.selectedAuthType,{apiKey:e.merged.apiKey,baseUrl:e.merged.baseUrl,modelName:e.merged.modelName})}catch(y){y instanceof Error&&y.message.includes("SERVER_OAUTH2_REQUIRED")?(console.error(O.t("gemini.serverOAuth2Required")||"\u68C0\u6D4B\u5230\u670D\u52A1\u5668\u73AF\u5883\uFF0C\u9700\u8981\u624B\u52A8\u8FDB\u884COAuth2\u8BA4\u8BC1\u3002\u8BF7\u5728\u975E\u6C99\u7BB1\u6A21\u5F0F\u4E0B\u8FD0\u884CCLI\u8FDB\u884C\u8BA4\u8BC1\u3002"),console.error("\u8BF7\u5C1D\u8BD5\u4E0D\u4F7F\u7528\u6C99\u7BB1\u6A21\u5F0F\u542F\u52A8\uFF0C\u6216\u8005\u5148\u5728\u672C\u5730\u73AF\u5883\u4E0B\u5B8C\u6210\u8BA4\u8BC1\u3002")):console.error(O.t("gemini.errorAuthenticating"),y),process.exit(1)}await bAi(A,g,c),process.exit(0)}else g.length>0&&(await Tya(g),process.exit(0))}if(e.merged.selectedAuthType===Yt.LOGIN_WITH_IFLOW&&c.isBrowserLaunchSuppressed())try{await WF(e.merged.selectedAuthType,c)}catch(g){if(!(g instanceof Error&&g.message.includes("SERVER_OAUTH2_REQUIRED")))throw g}if(c.getExperimentalAcp())return c.getAcpPort()?await HAi(c,e,s,r,c.getAcpPort()):LAi(c,e,s,r);let u=c.getQuestion(),d=[...await CAi(),...await xAi(t)];if(!!r.promptInteractive||!!r.continue||!!r.resume&&!n||process.stdin.isTTY&&u?.length===0){console.clear();let g=await aM();k2i(O2i(t),e);try{await Gli()}catch(S){c.getDebugMode()&&console.warn("Failed to detect/enable Kitty protocol:",S)}try{await c.setIdeModeAndSyncConnection(!0)}catch(S){console.error(O.t("gemini.failedToConnectToIdeServer"),S)}let A,y=async()=>{try{if(console.clear(),k2i(O2i(t),e),A)try{A.unmount(),await new Promise(R=>process.nextTick(R))}catch(R){console.error(O.t("gemini.errorDuringUnmount"),R)}let{executeSessionStartHooks:S}=await Promise.resolve().then(()=>(zH(),WH)),w=await S(c,"resume");A=TCe((0,Jve.jsx)(Vir.default.StrictMode,{children:(0,Jve.jsx)(tir,{instance:()=>A,config:c,settings:e,startupWarnings:d,version:g,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,fgMode:!0,sessionStartContext:w})}),{exitOnCtrlC:!1,isScreenReaderEnabled:!1,stdout:drr(),maxFps:20})}catch(S){console.error(O.t("gemini.errorDuringResume"),S)}};process.on("SIGCONT",y),j6e(()=>{process.off("SIGCONT",y)});let E="startup";(r.continue||r.resume)&&(E="resume");let{executeSessionStartHooks:v}=await Promise.resolve().then(()=>(zH(),WH)),b=await v(c,E);A=TCe((0,Jve.jsx)(Vir.default.StrictMode,{children:(0,Jve.jsx)(tir,{instance:()=>A,config:c,settings:e,startupWarnings:d,version:g,continueMode:!!r.continue,resumeMode:!!r.resume,resumeSessionId:r.resume,sessionStartContext:b})}),{exitOnCtrlC:!1,isScreenReaderEnabled:!1,stdout:drr()}),e.merged.disableAutoUpdate||Cit().then(S=>{soi(S,e,c.getProjectRoot())}).catch(S=>{c.getDebugMode()&&console.error(O.t("gemini.updateCheckFailed"),S)}),j6e(()=>A.unmount());return}!process.stdin.isTTY&&!u&&(u+=await yAi()),u||(console.error(O.t("gemini.noInputProvidedViaStdin")),process.exit(1));let p=Math.random().toString(16).slice(2);nJ(c,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:u,prompt_id:p,auth_type:c.getContentGeneratorConfig()?.authType,prompt_length:u.length});let h=await Rya(c,s,e,r),m=r.outputFile||r.output_file;await IAi(h,u,p,m),process.exit(0)}function k2i(t,e){if(!e.merged.hideWindowTitle){let r=(process.env.CLI_TITLE||`iFlow - ${t}`).replace(/[\x00-\x1F\x7F]/g,"");process.stdout.write(`\x1B]2;${r}\x07`),process.on("exit",()=>{process.stdout.write("\x1B]2;\x07")})}}async function Rya(t,e,r,n){let o=t;if(t.getApprovalMode()!==ii.YOLO){let s=r.merged.excludeTools||[],a=[$d.Name,M0.Name,Vf.Name],c=[...new Set([...s,...a])],u={...r.merged,excludeTools:c},d={...n};o=await TH(u,e,t.getSessionId(),d),await o.initialize()}return await Nya(r.merged.selectedAuthType,o,r)}async function Nya(t,e,r){!t&&!process.env.IFLOW_API_KEY&&!eke()&&(console.error(O.t("gemini.pleaseSetAuthMethod",{userSettingsPath:uH})),process.exit(1)),t||(eke()?t=Yt.IFLOW:t=Yt.IFLOW);let n=XP(t);return n!=null&&(console.error(n),process.exit(1)),await e.refreshAuth(t,{apiKey:r.merged.apiKey,baseUrl:r.merged.baseUrl,modelName:e.getModel()}),e}P2i().catch(t=>{console.error("An unexpected critical error occurred:"),t instanceof Error?console.error(t.stack):console.error(String(t)),process.exit(1)});
|
|
5682
5682
|
/**
|
|
5683
5683
|
* @license
|
|
5684
5684
|
* Copyright 2025 Google LLC
|