@iflow-ai/iflow-cli 0.3.29-beta.2 → 0.3.30

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
@@ -482,9 +482,9 @@ ${c}`.trim()}_serializeSingularDataPoint(e,r,n){let o="";e=w3t(e,r);let{value:s,
482
482
  ${o}
483
483
  ${s}
484
484
  `}};sDe.PrometheusSerializer=I3t});var iDr=T(aDe=>{"use strict";Object.defineProperty(aDe,"__esModule",{value:!0});aDe.PrometheusExporter=void 0;var dpe=(Zt(),vt(ur)),Uno=fi(),R3t=zS(),Qno=ye("http"),jno=D3t(),Gno=ye("url"),N3t=class t extends R3t.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:R3t.AggregationType.DEFAULT}),aggregationTemporalitySelector:o=>R3t.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,Qno.createServer)(this._requestHandler).unref(),this._serializer=new jno.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=>{dpe.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,Uno.globalErrorHandler)(r):dpe.diag.debug("Prometheus exporter was stopped"),e()})}):(dpe.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},()=>{dpe.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 Gno.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&&dpe.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()}};aDe.PrometheusExporter=N3t});var oDr=T(qK=>{"use strict";Object.defineProperty(qK,"__esModule",{value:!0});qK.PrometheusSerializer=qK.PrometheusExporter=void 0;var $no=iDr();Object.defineProperty(qK,"PrometheusExporter",{enumerable:!0,get:function(){return $no.PrometheusExporter}});var qno=D3t();Object.defineProperty(qK,"PrometheusSerializer",{enumerable:!0,get:function(){return qno.PrometheusSerializer}})});var sDr=T(cDe=>{"use strict";Object.defineProperty(cDe,"__esModule",{value:!0});cDe.VERSION=void 0;cDe.VERSION="0.206.0"});var cDr=T(lDe=>{"use strict";Object.defineProperty(lDe,"__esModule",{value:!0});lDe.OTLPTraceExporter=void 0;var Hno=(US(),vt(LS)),Vno=sDr(),Wno=XS(),aDr=(h9(),vt(eN)),O3t=class extends Hno.OTLPExporterBase{constructor(e={}){super((0,aDr.createOtlpHttpExportDelegate)((0,aDr.convertLegacyHttpOptions)(e,"TRACES","v1/traces",{"User-Agent":`OTel-OTLP-Exporter-JavaScript/${Vno.VERSION}`,"Content-Type":"application/json"}),Wno.JsonTraceSerializer))}};lDe.OTLPTraceExporter=O3t});var lDr=T(uDe=>{"use strict";Object.defineProperty(uDe,"__esModule",{value:!0});uDe.OTLPTraceExporter=void 0;var zno=cDr();Object.defineProperty(uDe,"OTLPTraceExporter",{enumerable:!0,get:function(){return zno.OTLPTraceExporter}})});var uDr=T(dDe=>{"use strict";Object.defineProperty(dDe,"__esModule",{value:!0});dDe.OTLPTraceExporter=void 0;var Yno=lDr();Object.defineProperty(dDe,"OTLPTraceExporter",{enumerable:!0,get:function(){return Yno.OTLPTraceExporter}})});var dDr=T(fDe=>{"use strict";Object.defineProperty(fDe,"__esModule",{value:!0});fDe.OTLPTraceExporter=void 0;var Kno=uDr();Object.defineProperty(fDe,"OTLPTraceExporter",{enumerable:!0,get:function(){return Kno.OTLPTraceExporter}})});var pDr=T(pDe=>{"use strict";Object.defineProperty(pDe,"__esModule",{value:!0});pDe.OTLPTraceExporter=void 0;var fDr=zIe(),Xno=XS(),Jno=(US(),vt(LS)),k3t=class extends Jno.OTLPExporterBase{constructor(e={}){super((0,fDr.createOtlpGrpcExportDelegate)((0,fDr.convertLegacyOtlpGrpcOptions)(e,"TRACES"),Xno.ProtobufTraceSerializer,"TraceExportService","/opentelemetry.proto.collector.trace.v1.TraceService/Export"))}};pDe.OTLPTraceExporter=k3t});var hDr=T(hDe=>{"use strict";Object.defineProperty(hDe,"__esModule",{value:!0});hDe.OTLPTraceExporter=void 0;var Zno=pDr();Object.defineProperty(hDe,"OTLPTraceExporter",{enumerable:!0,get:function(){return Zno.OTLPTraceExporter}})});var mDr=T(gDe=>{"use strict";Object.defineProperty(gDe,"__esModule",{value:!0});gDe.prepareSend=void 0;var B3t=(Zt(),vt(ur)),mDe=fi(),eio=ye("http"),tio=ye("https");function rio(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 B3t.diag.debug("Zipkin send with empty spans"),a({code:mDe.ExportResultCode.SUCCESS});let{request:c}=r.protocol==="http:"?eio:tio,u=c(r,n,f=>{let p="";f.on("data",h=>{p+=h}),f.on("end",()=>{let h=f.statusCode||0;return B3t.diag.debug(`Zipkin response status code: ${h}, body: ${p}`),h<400?a({code:mDe.ExportResultCode.SUCCESS}):a({code:mDe.ExportResultCode.FAILED,error:new Error(`Got unexpected status code from zipkin: ${h}`)})})});u.on("error",f=>a({code:mDe.ExportResultCode.FAILED,error:f}));let d=JSON.stringify(s);B3t.diag.debug(`Zipkin request payload: ${d}`),u.write(d,"utf8"),u.end()}}gDe.prepareSend=rio});var gDr=T(ADe=>{"use strict";Object.defineProperty(ADe,"__esModule",{value:!0});ADe.prepareSend=void 0;var nio=mDr();Object.defineProperty(ADe,"prepareSend",{enumerable:!0,get:function(){return nio.prepareSend}})});var P3t=T(yDe=>{"use strict";Object.defineProperty(yDe,"__esModule",{value:!0});yDe.prepareSend=void 0;var iio=gDr();Object.defineProperty(yDe,"prepareSend",{enumerable:!0,get:function(){return iio.prepareSend}})});var ADr=T(fpe=>{"use strict";Object.defineProperty(fpe,"__esModule",{value:!0});fpe.SpanKind=void 0;var oio;(function(t){t.CLIENT="CLIENT",t.SERVER="SERVER",t.CONSUMER="CONSUMER",t.PRODUCER="PRODUCER"})(oio=fpe.SpanKind||(fpe.SpanKind={}))});var EDr=T(J6=>{"use strict";Object.defineProperty(J6,"__esModule",{value:!0});J6._toZipkinAnnotations=J6._toZipkinTags=J6.toZipkinSpan=J6.defaultStatusErrorTagName=J6.defaultStatusCodeTagName=void 0;var bN=(Zt(),vt(ur)),M3t=fi(),_De=ADr(),sio={[bN.SpanKind.CLIENT]:_De.SpanKind.CLIENT,[bN.SpanKind.SERVER]:_De.SpanKind.SERVER,[bN.SpanKind.CONSUMER]:_De.SpanKind.CONSUMER,[bN.SpanKind.PRODUCER]:_De.SpanKind.PRODUCER,[bN.SpanKind.INTERNAL]:void 0};J6.defaultStatusCodeTagName="otel.status_code";J6.defaultStatusErrorTagName="error";function aio(t,e,r,n){return{traceId:t.spanContext().traceId,parentId:t.parentSpanContext?.spanId,name:t.name,id:t.spanContext().spanId,kind:sio[t.kind],timestamp:(0,M3t.hrTimeToMicroseconds)(t.startTime),duration:Math.round((0,M3t.hrTimeToMicroseconds)(t.duration)),localEndpoint:{serviceName:e},tags:yDr(t,r,n),annotations:t.events.length?_Dr(t.events):void 0}}J6.toZipkinSpan=aio;function yDr({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!==bN.SpanStatusCode.UNSET&&(u[a]=String(bN.SpanStatusCode[r.code])),r.code===bN.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}J6._toZipkinTags=yDr;function _Dr(t){return t.map(e=>({timestamp:Math.round((0,M3t.hrTimeToMicroseconds)(e.time)),value:e.name}))}J6._toZipkinAnnotations=_Dr});var vDr=T(EDe=>{"use strict";Object.defineProperty(EDe,"__esModule",{value:!0});EDe.prepareGetHeaders=void 0;function cio(t){return function(){return t()}}EDe.prepareGetHeaders=cio});var xDr=T(vDe=>{"use strict";Object.defineProperty(vDe,"__esModule",{value:!0});vDe.ZipkinExporter=void 0;var bDr=(Zt(),vt(ur)),CDr=fi(),SDr=P3t(),F3t=EDr(),L3t=($h(),vt(yA)),lio=vDr(),U3t=class{DEFAULT_SERVICE_NAME="OpenTelemetry Service";_statusCodeTagName;_statusDescriptionTagName;_urlStr;_send;_getHeaders;_serviceName;_isShutdown;_sendingPromises=[];constructor(e={}){this._urlStr=e.url||((0,CDr.getStringFromEnv)("OTEL_EXPORTER_ZIPKIN_ENDPOINT")??"http://localhost:9411/api/v2/spans"),this._send=(0,SDr.prepareSend)(this._urlStr,e.headers),this._serviceName=e.serviceName,this._statusCodeTagName=e.statusCodeTagName||F3t.defaultStatusCodeTagName,this._statusDescriptionTagName=e.statusDescriptionTagName||F3t.defaultStatusErrorTagName,this._isShutdown=!1,typeof e.getExportRequestHeaders=="function"?this._getHeaders=(0,lio.prepareGetHeaders)(e.getExportRequestHeaders):this._beforeSend=function(){}}export(e,r){let n=String(this._serviceName||e[0].resource.attributes[L3t.ATTR_SERVICE_NAME]||this.DEFAULT_SERVICE_NAME);if(bDr.diag.debug("Zipkin exporter export"),this._isShutdown){setTimeout(()=>r({code:CDr.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 bDr.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,SDr.prepareSend)(this._urlStr,this._getHeaders()))}_sendSpans(e,r,n){let o=e.map(s=>(0,F3t.toZipkinSpan)(s,String(s.attributes[L3t.ATTR_SERVICE_NAME]||s.resource.attributes[L3t.ATTR_SERVICE_NAME]||r),this._statusCodeTagName,this._statusDescriptionTagName));return this._beforeSend(),this._send(o,s=>{if(n)return n(s)})}};vDe.ZipkinExporter=U3t});var wDr=T(HK=>{"use strict";Object.defineProperty(HK,"__esModule",{value:!0});HK.ZipkinExporter=HK.prepareSend=void 0;var uio=P3t();Object.defineProperty(HK,"prepareSend",{enumerable:!0,get:function(){return uio.prepareSend}});var dio=xDr();Object.defineProperty(HK,"ZipkinExporter",{enumerable:!0,get:function(){return dio.ZipkinExporter}})});var Q3t=T(bDe=>{"use strict";Object.defineProperty(bDe,"__esModule",{value:!0});bDe.B3_DEBUG_FLAG_KEY=void 0;var fio=(Zt(),vt(ur));bDe.B3_DEBUG_FLAG_KEY=(0,fio.createContextKey)("OpenTelemetry Context Key B3 Debug Flag")});var ppe=T(P3=>{"use strict";Object.defineProperty(P3,"__esModule",{value:!0});P3.X_B3_FLAGS=P3.X_B3_PARENT_SPAN_ID=P3.X_B3_SAMPLED=P3.X_B3_SPAN_ID=P3.X_B3_TRACE_ID=P3.B3_CONTEXT_HEADER=void 0;P3.B3_CONTEXT_HEADER="b3";P3.X_B3_TRACE_ID="x-b3-traceid";P3.X_B3_SPAN_ID="x-b3-spanid";P3.X_B3_SAMPLED="x-b3-sampled";P3.X_B3_PARENT_SPAN_ID="x-b3-parentspanid";P3.X_B3_FLAGS="x-b3-flags"});var DDr=T(SDe=>{"use strict";Object.defineProperty(SDe,"__esModule",{value:!0});SDe.B3MultiPropagator=void 0;var lC=(Zt(),vt(ur)),pio=fi(),TDr=Q3t(),T_=ppe(),hio=new Set([!0,"true","True","1",1]),mio=new Set([!1,"false","False","0",0]);function gio(t){return t===lC.TraceFlags.SAMPLED||t===lC.TraceFlags.NONE}function Aio(t){return Array.isArray(t)?t[0]:t}function CDe(t,e,r){let n=e.get(t,r);return Aio(n)}function yio(t,e){let r=CDe(t,e,T_.X_B3_TRACE_ID);return typeof r=="string"?r.padStart(32,"0"):""}function _io(t,e){let r=CDe(t,e,T_.X_B3_SPAN_ID);return typeof r=="string"?r:""}function IDr(t,e){return CDe(t,e,T_.X_B3_FLAGS)==="1"?"1":void 0}function Eio(t,e){let r=CDe(t,e,T_.X_B3_SAMPLED);if(IDr(t,e)==="1"||hio.has(r))return lC.TraceFlags.SAMPLED;if(r===void 0||mio.has(r))return lC.TraceFlags.NONE}var j3t=class{inject(e,r,n){let o=lC.trace.getSpanContext(e);if(!o||!(0,lC.isSpanContextValid)(o)||(0,pio.isTracingSuppressed)(e))return;let s=e.getValue(TDr.B3_DEBUG_FLAG_KEY);n.set(r,T_.X_B3_TRACE_ID,o.traceId),n.set(r,T_.X_B3_SPAN_ID,o.spanId),s==="1"?n.set(r,T_.X_B3_FLAGS,s):o.traceFlags!==void 0&&n.set(r,T_.X_B3_SAMPLED,(lC.TraceFlags.SAMPLED&o.traceFlags)===lC.TraceFlags.SAMPLED?"1":"0")}extract(e,r,n){let o=yio(r,n),s=_io(r,n),a=Eio(r,n),c=IDr(r,n);return(0,lC.isValidTraceId)(o)&&(0,lC.isValidSpanId)(s)&&gio(a)?(e=e.setValue(TDr.B3_DEBUG_FLAG_KEY,c),lC.trace.setSpanContext(e,{traceId:o,spanId:s,isRemote:!0,traceFlags:a})):e}fields(){return[T_.X_B3_TRACE_ID,T_.X_B3_SPAN_ID,T_.X_B3_FLAGS,T_.X_B3_SAMPLED,T_.X_B3_PARENT_SPAN_ID]}};SDe.B3MultiPropagator=j3t});var NDr=T(xDe=>{"use strict";Object.defineProperty(xDe,"__esModule",{value:!0});xDe.B3SinglePropagator=void 0;var GL=(Zt(),vt(ur)),vio=fi(),RDr=Q3t(),G3t=ppe(),bio=/((?:[0-9a-f]{16}){1,2})-([0-9a-f]{16})(?:-([01d](?![0-9a-f])))?(?:-([0-9a-f]{16}))?/,Cio="0".repeat(16),Sio=new Set(["d","1"]),xio="d";function wio(t){return t.length===32?t:`${Cio}${t}`}function Tio(t){return t&&Sio.has(t)?GL.TraceFlags.SAMPLED:GL.TraceFlags.NONE}var $3t=class{inject(e,r,n){let o=GL.trace.getSpanContext(e);if(!o||!(0,GL.isSpanContextValid)(o)||(0,vio.isTracingSuppressed)(e))return;let s=e.getValue(RDr.B3_DEBUG_FLAG_KEY)||o.traceFlags&1,a=`${o.traceId}-${o.spanId}-${s}`;n.set(r,G3t.B3_CONTEXT_HEADER,a)}extract(e,r,n){let o=n.get(r,G3t.B3_CONTEXT_HEADER),s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let a=s.match(bio);if(!a)return e;let[,c,u,d]=a,f=wio(c);if(!(0,GL.isValidTraceId)(f)||!(0,GL.isValidSpanId)(u))return e;let p=Tio(d);return d===xio&&(e=e.setValue(RDr.B3_DEBUG_FLAG_KEY,d)),GL.trace.setSpanContext(e,{traceId:f,spanId:u,isRemote:!0,traceFlags:p})}fields(){return[G3t.B3_CONTEXT_HEADER]}};xDe.B3SinglePropagator=$3t});var q3t=T(hpe=>{"use strict";Object.defineProperty(hpe,"__esModule",{value:!0});hpe.B3InjectEncoding=void 0;var Iio;(function(t){t[t.SINGLE_HEADER=0]="SINGLE_HEADER",t[t.MULTI_HEADER=1]="MULTI_HEADER"})(Iio=hpe.B3InjectEncoding||(hpe.B3InjectEncoding={}))});var ODr=T(wDe=>{"use strict";Object.defineProperty(wDe,"__esModule",{value:!0});wDe.B3Propagator=void 0;var Dio=fi(),Rio=DDr(),Nio=NDr(),Oio=ppe(),kio=q3t(),H3t=class{_b3MultiPropagator=new Rio.B3MultiPropagator;_b3SinglePropagator=new Nio.B3SinglePropagator;_inject;_fields;constructor(e={}){e.injectEncoding===kio.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,Dio.isTracingSuppressed)(e)||this._inject(e,r,n)}extract(e,r,n){let o=n.get(r,Oio.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}};wDe.B3Propagator=H3t});var kDr=T(Ym=>{"use strict";Object.defineProperty(Ym,"__esModule",{value:!0});Ym.B3InjectEncoding=Ym.X_B3_TRACE_ID=Ym.X_B3_SPAN_ID=Ym.X_B3_SAMPLED=Ym.X_B3_PARENT_SPAN_ID=Ym.X_B3_FLAGS=Ym.B3_CONTEXT_HEADER=Ym.B3Propagator=void 0;var Bio=ODr();Object.defineProperty(Ym,"B3Propagator",{enumerable:!0,get:function(){return Bio.B3Propagator}});var VK=ppe();Object.defineProperty(Ym,"B3_CONTEXT_HEADER",{enumerable:!0,get:function(){return VK.B3_CONTEXT_HEADER}});Object.defineProperty(Ym,"X_B3_FLAGS",{enumerable:!0,get:function(){return VK.X_B3_FLAGS}});Object.defineProperty(Ym,"X_B3_PARENT_SPAN_ID",{enumerable:!0,get:function(){return VK.X_B3_PARENT_SPAN_ID}});Object.defineProperty(Ym,"X_B3_SAMPLED",{enumerable:!0,get:function(){return VK.X_B3_SAMPLED}});Object.defineProperty(Ym,"X_B3_SPAN_ID",{enumerable:!0,get:function(){return VK.X_B3_SPAN_ID}});Object.defineProperty(Ym,"X_B3_TRACE_ID",{enumerable:!0,get:function(){return VK.X_B3_TRACE_ID}});var Pio=q3t();Object.defineProperty(Ym,"B3InjectEncoding",{enumerable:!0,get:function(){return Pio.B3InjectEncoding}})});var BDr=T(uC=>{"use strict";Object.defineProperty(uC,"__esModule",{value:!0});uC.JaegerPropagator=uC.UBER_BAGGAGE_HEADER_PREFIX=uC.UBER_TRACE_ID_HEADER=void 0;var $L=(Zt(),vt(ur)),Mio=fi();uC.UBER_TRACE_ID_HEADER="uber-trace-id";uC.UBER_BAGGAGE_HEADER_PREFIX="uberctx";var V3t=class{_jaegerTraceHeader;_jaegerBaggageHeaderPrefix;constructor(e){typeof e=="string"?(this._jaegerTraceHeader=e,this._jaegerBaggageHeaderPrefix=uC.UBER_BAGGAGE_HEADER_PREFIX):(this._jaegerTraceHeader=e?.customTraceHeader||uC.UBER_TRACE_ID_HEADER,this._jaegerBaggageHeaderPrefix=e?.customBaggageHeaderPrefix||uC.UBER_BAGGAGE_HEADER_PREFIX)}inject(e,r,n){let o=$L.trace.getSpanContext(e),s=$L.propagation.getBaggage(e);if(o&&(0,Mio.isTracingSuppressed)(e)===!1){let a=`0${(o.traceFlags||$L.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=Lio(s);d&&(c=$L.trace.setSpanContext(c,d))}if(a.length===0)return c;let u=$L.propagation.getBaggage(e)??$L.propagation.createBaggage();for(let d of a)d.value!==void 0&&(u=u.setEntry(d.key,{value:decodeURIComponent(d.value)}));return c=$L.propagation.setBaggage(c,u),c}fields(){return[this._jaegerTraceHeader]}};uC.JaegerPropagator=V3t;var Fio=/^[0-9a-f]{1,2}$/i;function Lio(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=Fio.test(o)?parseInt(o,16)&1:1;return{traceId:s,spanId:a,isRemote:!0,traceFlags:c}}});var PDr=T(CN=>{"use strict";Object.defineProperty(CN,"__esModule",{value:!0});CN.UBER_TRACE_ID_HEADER=CN.UBER_BAGGAGE_HEADER_PREFIX=CN.JaegerPropagator=void 0;var W3t=BDr();Object.defineProperty(CN,"JaegerPropagator",{enumerable:!0,get:function(){return W3t.JaegerPropagator}});Object.defineProperty(CN,"UBER_BAGGAGE_HEADER_PREFIX",{enumerable:!0,get:function(){return W3t.UBER_BAGGAGE_HEADER_PREFIX}});Object.defineProperty(CN,"UBER_TRACE_ID_HEADER",{enumerable:!0,get:function(){return W3t.UBER_TRACE_ID_HEADER}})});var UDr=T(Z6=>{"use strict";Object.defineProperty(Z6,"__esModule",{value:!0});Z6.getPropagatorFromEnv=Z6.getSpanProcessorsFromEnv=Z6.getOtlpProtocolFromEnv=Z6.filterBlanksAndNulls=Z6.getResourceDetectorsFromEnv=void 0;var SN=(Zt(),vt(ur)),xN=fi(),MDr=Jht(),Uio=dDr(),Qio=hDr(),jio=wDr(),mpe=UY(),TDe=D9e(),z3t=kDr(),Gio=PDr(),$io="env",qio="host",Hio="os",Vio="process",Wio="serviceinstance";function zio(){let t=new Map([[$io,mpe.envDetector],[qio,mpe.hostDetector],[Hio,mpe.osDetector],[Wio,mpe.serviceInstanceIdDetector],[Vio,mpe.processDetector]]),e=(0,xN.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||SN.diag.warn(`Invalid resource detector "${r}" specified in the environment variable OTEL_NODE_RESOURCE_DETECTORS`),n||[]})}Z6.getResourceDetectorsFromEnv=zio;function FDr(t){return t.map(e=>e.trim()).filter(e=>e!=="null"&&e!=="")}Z6.filterBlanksAndNulls=FDr;function LDr(){return(0,xN.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")??(0,xN.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL")??"http/protobuf"}Z6.getOtlpProtocolFromEnv=LDr;function Yio(){let t=LDr();switch(t){case"grpc":return new Qio.OTLPTraceExporter;case"http/json":return new Uio.OTLPTraceExporter;case"http/protobuf":return new MDr.OTLPTraceExporter;default:return SN.diag.warn(`Unsupported OTLP traces protocol: ${t}. Using http/protobuf.`),new MDr.OTLPTraceExporter}}function Kio(){try{let{JaegerExporter:t}=ye("@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 Xio(){let t=new Map([["otlp",()=>Yio()],["zipkin",()=>new jio.ZipkinExporter],["console",()=>new TDe.ConsoleSpanExporter],["jaeger",()=>Kio()]]),e=[],r=[],n=FDr(Array.from(new Set((0,xN.getStringListFromEnv)("OTEL_TRACES_EXPORTER"))));if(n[0]==="none")return SN.diag.warn('OTEL_TRACES_EXPORTER contains "none". SDK will not be initialized.'),[];n.length===0?(SN.diag.debug("OTEL_TRACES_EXPORTER is empty. Using default otlp exporter."),n=["otlp"]):n.length>1&&n.includes("none")&&(SN.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):SN.diag.warn(`Unrecognized OTEL_TRACES_EXPORTER value: ${o}.`)}for(let o of e)o instanceof TDe.ConsoleSpanExporter?r.push(new TDe.SimpleSpanProcessor(o)):r.push(new TDe.BatchSpanProcessor(o));return e.length===0&&SN.diag.warn("Unable to set up trace exporter(s) due to invalid exporter and/or protocol values."),r}Z6.getSpanProcessorsFromEnv=Xio;function Jio(){let t=(0,xN.getStringListFromEnv)("OTEL_PROPAGATORS");if(t==null)return;let e=new Map([["tracecontext",()=>new xN.W3CTraceContextPropagator],["baggage",()=>new xN.W3CBaggagePropagator],["b3",()=>new z3t.B3Propagator],["b3multi",()=>new z3t.B3Propagator({injectEncoding:z3t.B3InjectEncoding.MULTI_HEADER})],["jaeger",()=>new Gio.JaegerPropagator]]),r=Array.from(new Set(t)),o=r.map(s=>{let a=e.get(s)?.();if(!a){SN.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 xN.CompositePropagator({propagators:o})}Z6.getPropagatorFromEnv=Jio});var GDr=T(IDe=>{"use strict";Object.defineProperty(IDe,"__esModule",{value:!0});IDe.NodeSDK=void 0;var i1=(Zt(),vt(ur)),Zio=PY(),eoo=x8r(),WK=UY(),gpe=Fmt(),too=smt(),roo=VIr(),Y3t=JIr(),noo=tDr(),QDr=imt(),ioo=a8e(),ooo=oDr(),qL=zS(),soo=D9e(),aoo=i9e(),coo=($h(),vt(yA)),wN=fi(),K3t=UDr();function jDr(t,e){return parseInt(process.env[t]||"")||e}function loo(){let t=[],e=(0,wN.getStringListFromEnv)("OTEL_METRICS_EXPORTER");return e?(e.length===0&&i1.diag.debug("OTEL_METRICS_EXPORTER is empty. Using default otlp exporter."),e.includes("none")?(i1.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=jDr("OTEL_METRIC_EXPORT_INTERVAL",6e4),s=jDr("OTEL_METRIC_EXPORT_TIMEOUT",3e4);switch(n){case"grpc":t.push(new qL.PeriodicExportingMetricReader({exporter:new noo.OTLPMetricExporter,exportIntervalMillis:o,exportTimeoutMillis:s}));break;case"http/json":t.push(new qL.PeriodicExportingMetricReader({exporter:new ioo.OTLPMetricExporter,exportIntervalMillis:o,exportTimeoutMillis:s}));break;case"http/protobuf":t.push(new qL.PeriodicExportingMetricReader({exporter:new QDr.OTLPMetricExporter,exportIntervalMillis:o,exportTimeoutMillis:s}));break;default:i1.diag.warn(`Unsupported OTLP metrics protocol: "${n}". Using http/protobuf.`),t.push(new qL.PeriodicExportingMetricReader({exporter:new QDr.OTLPMetricExporter,exportIntervalMillis:o,exportTimeoutMillis:s}))}}else r==="console"?t.push(new qL.PeriodicExportingMetricReader({exporter:new qL.ConsoleMetricExporter})):r==="prometheus"?t.push(new ooo.PrometheusExporter):i1.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${r}". Supported values are: otlp, console, prometheus, none.`)}),t)):t}var X3t=class{_tracerProviderConfig;_loggerProviderConfig;_meterProviderConfig;_instrumentations;_resource;_resourceDetectors;_autoDetectResources;_tracerProvider;_loggerProvider;_meterProvider;_serviceName;_configuration;_disabled;constructor(e={}){(0,wN.getBooleanFromEnv)("OTEL_SDK_DISABLED")&&(this._disabled=!0);let r=(0,wN.getStringFromEnv)("OTEL_LOG_LEVEL");if(r!=null&&i1.diag.setLogger(new i1.DiagConsoleLogger,{logLevel:(0,wN.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,wN.getStringFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")?this._resourceDetectors=(0,K3t.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&&i1.diag.warn("The 'spanProcessor' option is deprecated. Please use 'spanProcessors' instead.");let o=e.spanProcessor??new soo.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]},i1.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],i1.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,eoo.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)({[coo.ATTR_SERVICE_NAME]:this._serviceName}));let e=this._tracerProviderConfig?this._tracerProviderConfig.spanProcessors:(0,K3t.getSpanProcessorsFromEnv)();if(this._tracerProvider=new aoo.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,K3t.getPropagatorFromEnv)()}),this._loggerProviderConfig){let n=new gpe.LoggerProvider({resource:this._resource,processors:this._loggerProviderConfig.logRecordProcessors});this._loggerProvider=n,Zio.logs.setGlobalLoggerProvider(n)}let r=loo();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 qL.MeterProvider({resource:this._resource,views:this._meterProviderConfig?.views??[],readers:n});this._meterProvider=o,i1.metrics.setGlobalMeterProvider(o);for(let s of this._instrumentations)s.setMeterProvider(i1.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,wN.getStringListFromEnv)("OTEL_LOGS_EXPORTER")??[];if(e.length===0&&(i1.diag.debug("OTEL_LOGS_EXPORTER is empty. Using default otlp exporter."),e.push("otlp")),e.includes("none")){i1.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,wN.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL")??(0,wN.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim();switch(o){case"grpc":r.push(new roo.OTLPLogExporter);break;case"http/json":r.push(new too.OTLPLogExporter);break;case"http/protobuf":r.push(new Y3t.OTLPLogExporter);break;case void 0:case"":r.push(new Y3t.OTLPLogExporter);break;default:i1.diag.warn(`Unsupported OTLP logs protocol: "${o}". Using http/protobuf.`),r.push(new Y3t.OTLPLogExporter)}}else n==="console"?r.push(new gpe.ConsoleLogRecordExporter):i1.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 gpe.ConsoleLogRecordExporter?new gpe.SimpleLogRecordProcessor(n):new gpe.BatchLogRecordProcessor(n))})}};IDe.NodeSDK=X3t});var $Dr=T(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});sh.NodeSDK=sh.tracing=sh.resources=sh.node=sh.metrics=sh.logs=sh.core=sh.contextBase=sh.api=void 0;sh.api=(Zt(),vt(ur));sh.contextBase=(Zt(),vt(ur));sh.core=fi();sh.logs=Fmt();sh.metrics=zS();sh.node=i9e();sh.resources=UY();sh.tracing=D9e();var uoo=GDr();Object.defineProperty(sh,"NodeSDK",{enumerable:!0,get:function(){return uoo.NodeSDK}})});function doo(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 qDr,DDe,HDr=te(()=>{"use strict";qDr=Te(zS(),1);DDe=class extends qDr.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 doo(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 Ape=T(TN=>{"use strict";Object.defineProperty(TN,"__esModule",{value:!0});TN.isTracingSuppressed=TN.unsuppressTracing=TN.suppressTracing=void 0;var foo=(Zt(),vt(ur)),J3t=(0,foo.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function poo(t){return t.setValue(J3t,!0)}TN.suppressTracing=poo;function hoo(t){return t.deleteValue(J3t)}TN.unsuppressTracing=hoo;function moo(t){return t.getValue(J3t)===!0}TN.isTracingSuppressed=moo});var Z3t=T(CA=>{"use strict";Object.defineProperty(CA,"__esModule",{value:!0});CA.BAGGAGE_MAX_TOTAL_LENGTH=CA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=CA.BAGGAGE_MAX_NAME_VALUE_PAIRS=CA.BAGGAGE_HEADER=CA.BAGGAGE_ITEMS_SEPARATOR=CA.BAGGAGE_PROPERTIES_SEPARATOR=CA.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;CA.BAGGAGE_KEY_PAIR_SEPARATOR="=";CA.BAGGAGE_PROPERTIES_SEPARATOR=";";CA.BAGGAGE_ITEMS_SEPARATOR=",";CA.BAGGAGE_HEADER="baggage";CA.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;CA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;CA.BAGGAGE_MAX_TOTAL_LENGTH=8192});var eyt=T(wx=>{"use strict";Object.defineProperty(wx,"__esModule",{value:!0});wx.parseKeyPairsIntoRecord=wx.parsePairKeyValue=wx.getKeyPairs=wx.serializeKeyPairs=void 0;var goo=(Zt(),vt(ur)),HL=Z3t();function Aoo(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?HL.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>HL.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}wx.serializeKeyPairs=Aoo;function yoo(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=HL.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}wx.getKeyPairs=yoo;function VDr(t){let e=t.split(HL.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(HL.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,goo.baggageEntryMetadataFromString)(e.join(HL.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:a}}wx.parsePairKeyValue=VDr;function _oo(t){let e={};return typeof t=="string"&&t.length>0&&t.split(HL.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=VDr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}wx.parseKeyPairsIntoRecord=_oo});var WDr=T(RDe=>{"use strict";Object.defineProperty(RDe,"__esModule",{value:!0});RDe.W3CBaggagePropagator=void 0;var tyt=(Zt(),vt(ur)),Eoo=Ape(),VL=Z3t(),ryt=eyt(),nyt=class{inject(e,r,n){let o=tyt.propagation.getBaggage(e);if(!o||(0,Eoo.isTracingSuppressed)(e))return;let s=(0,ryt.getKeyPairs)(o).filter(c=>c.length<=VL.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,VL.BAGGAGE_MAX_NAME_VALUE_PAIRS),a=(0,ryt.serializeKeyPairs)(s);a.length>0&&n.set(r,VL.BAGGAGE_HEADER,a)}extract(e,r,n){let o=n.get(r,VL.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(VL.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let a={};return s.length===0||(s.split(VL.BAGGAGE_ITEMS_SEPARATOR).forEach(u=>{let d=(0,ryt.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:tyt.propagation.setBaggage(e,tyt.propagation.createBaggage(a))}fields(){return[VL.BAGGAGE_HEADER]}};RDe.W3CBaggagePropagator=nyt});var zDr=T(NDe=>{"use strict";Object.defineProperty(NDe,"__esModule",{value:!0});NDe.AnchoredClock=void 0;var iyt=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}};NDe.AnchoredClock=iyt});var ZDr=T(IN=>{"use strict";Object.defineProperty(IN,"__esModule",{value:!0});IN.isAttributeValue=IN.isAttributeKey=IN.sanitizeAttributes=void 0;var YDr=(Zt(),vt(ur));function voo(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(!KDr(r)){YDr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!XDr(n)){YDr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}IN.sanitizeAttributes=voo;function KDr(t){return typeof t=="string"&&t!==""}IN.isAttributeKey=KDr;function XDr(t){return t==null?!0:Array.isArray(t)?boo(t):JDr(typeof t)}IN.isAttributeValue=XDr;function boo(t){let e;for(let r of t){if(r==null)continue;let n=typeof r;if(n!==e){if(!e){if(JDr(n)){e=n;continue}return!1}return!1}}return!0}function JDr(t){switch(t){case"number":case"boolean":case"string":return!0}return!1}});var oyt=T(ODe=>{"use strict";Object.defineProperty(ODe,"__esModule",{value:!0});ODe.loggingErrorHandler=void 0;var Coo=(Zt(),vt(ur));function Soo(){return t=>{Coo.diag.error(xoo(t))}}ODe.loggingErrorHandler=Soo;function xoo(t){return typeof t=="string"?t:JSON.stringify(woo(t))}function woo(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 tRr=T(zK=>{"use strict";Object.defineProperty(zK,"__esModule",{value:!0});zK.globalErrorHandler=zK.setGlobalErrorHandler=void 0;var Too=oyt(),eRr=(0,Too.loggingErrorHandler)();function Ioo(t){eRr=t}zK.setGlobalErrorHandler=Ioo;function Doo(t){try{eRr(t)}catch{}}zK.globalErrorHandler=Doo});var oRr=T(Tx=>{"use strict";Object.defineProperty(Tx,"__esModule",{value:!0});Tx.getStringListFromEnv=Tx.getBooleanFromEnv=Tx.getStringFromEnv=Tx.getNumberFromEnv=void 0;var rRr=(Zt(),vt(ur)),nRr=ye("util");function Roo(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){rRr.diag.warn(`Unknown value ${(0,nRr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}Tx.getNumberFromEnv=Roo;function iRr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}Tx.getStringFromEnv=iRr;function Noo(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||rRr.diag.warn(`Unknown value ${(0,nRr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}Tx.getBooleanFromEnv=Noo;function Ooo(t){return iRr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}Tx.getStringListFromEnv=Ooo});var sRr=T(kDe=>{"use strict";Object.defineProperty(kDe,"__esModule",{value:!0});kDe._globalThis=void 0;kDe._globalThis=typeof globalThis=="object"?globalThis:global});var aRr=T(BDe=>{"use strict";Object.defineProperty(BDe,"__esModule",{value:!0});BDe.otperformance=void 0;var koo=ye("perf_hooks");BDe.otperformance=koo.performance});var cRr=T(PDe=>{"use strict";Object.defineProperty(PDe,"__esModule",{value:!0});PDe.VERSION=void 0;PDe.VERSION="2.2.0"});var lRr=T(MDe=>{"use strict";Object.defineProperty(MDe,"__esModule",{value:!0});MDe.ATTR_PROCESS_RUNTIME_NAME=void 0;MDe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var uRr=T(LDe=>{"use strict";Object.defineProperty(LDe,"__esModule",{value:!0});LDe.SDK_INFO=void 0;var Boo=cRr(),FDe=($h(),vt(yA)),Poo=lRr();LDe.SDK_INFO={[FDe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[Poo.ATTR_PROCESS_RUNTIME_NAME]:"node",[FDe.ATTR_TELEMETRY_SDK_LANGUAGE]:FDe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[FDe.ATTR_TELEMETRY_SDK_VERSION]:Boo.VERSION}});var dRr=T(SA=>{"use strict";Object.defineProperty(SA,"__esModule",{value:!0});SA.SDK_INFO=SA.otperformance=SA._globalThis=SA.getStringListFromEnv=SA.getNumberFromEnv=SA.getBooleanFromEnv=SA.getStringFromEnv=void 0;var UDe=oRr();Object.defineProperty(SA,"getStringFromEnv",{enumerable:!0,get:function(){return UDe.getStringFromEnv}});Object.defineProperty(SA,"getBooleanFromEnv",{enumerable:!0,get:function(){return UDe.getBooleanFromEnv}});Object.defineProperty(SA,"getNumberFromEnv",{enumerable:!0,get:function(){return UDe.getNumberFromEnv}});Object.defineProperty(SA,"getStringListFromEnv",{enumerable:!0,get:function(){return UDe.getStringListFromEnv}});var Moo=sRr();Object.defineProperty(SA,"_globalThis",{enumerable:!0,get:function(){return Moo._globalThis}});var Foo=aRr();Object.defineProperty(SA,"otperformance",{enumerable:!0,get:function(){return Foo.otperformance}});var Loo=uRr();Object.defineProperty(SA,"SDK_INFO",{enumerable:!0,get:function(){return Loo.SDK_INFO}})});var syt=T(xA=>{"use strict";Object.defineProperty(xA,"__esModule",{value:!0});xA.getStringListFromEnv=xA.getNumberFromEnv=xA.getStringFromEnv=xA.getBooleanFromEnv=xA.otperformance=xA._globalThis=xA.SDK_INFO=void 0;var WL=dRr();Object.defineProperty(xA,"SDK_INFO",{enumerable:!0,get:function(){return WL.SDK_INFO}});Object.defineProperty(xA,"_globalThis",{enumerable:!0,get:function(){return WL._globalThis}});Object.defineProperty(xA,"otperformance",{enumerable:!0,get:function(){return WL.otperformance}});Object.defineProperty(xA,"getBooleanFromEnv",{enumerable:!0,get:function(){return WL.getBooleanFromEnv}});Object.defineProperty(xA,"getStringFromEnv",{enumerable:!0,get:function(){return WL.getStringFromEnv}});Object.defineProperty(xA,"getNumberFromEnv",{enumerable:!0,get:function(){return WL.getNumberFromEnv}});Object.defineProperty(xA,"getStringListFromEnv",{enumerable:!0,get:function(){return WL.getStringListFromEnv}})});var mRr=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 ayt=syt(),fRr=9,Uoo=6,Qoo=Math.pow(10,Uoo),QDe=Math.pow(10,fRr);function ype(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Qoo);return[r,n]}Su.millisToHrTime=ype;function cyt(){let t=ayt.otperformance.timeOrigin;if(typeof t!="number"){let e=ayt.otperformance;t=e.timing&&e.timing.fetchStart}return t}Su.getTimeOrigin=cyt;function pRr(t){let e=ype(cyt()),r=ype(typeof t=="number"?t:ayt.otperformance.now());return hRr(e,r)}Su.hrTime=pRr;function joo(t){if(lyt(t))return t;if(typeof t=="number")return t<cyt()?pRr(t):ype(t);if(t instanceof Date)return ype(t.getTime());throw TypeError("Invalid input type")}Su.timeInputToHrTime=joo;function Goo(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=QDe),[r,n]}Su.hrTimeDuration=Goo;function $oo(t){let e=fRr,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=$oo;function qoo(t){return t[0]*QDe+t[1]}Su.hrTimeToNanoseconds=qoo;function Hoo(t){return t[0]*1e3+t[1]/1e6}Su.hrTimeToMilliseconds=Hoo;function Voo(t){return t[0]*1e6+t[1]/1e3}Su.hrTimeToMicroseconds=Voo;function lyt(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}Su.isTimeInputHrTime=lyt;function Woo(t){return lyt(t)||typeof t=="number"||t instanceof Date}Su.isTimeInput=Woo;function hRr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=QDe&&(r[1]-=QDe,r[0]+=1),r}Su.addHrTimes=hRr});var gRr=T(jDe=>{"use strict";Object.defineProperty(jDe,"__esModule",{value:!0});jDe.unrefTimer=void 0;function zoo(t){typeof t!="number"&&t.unref()}jDe.unrefTimer=zoo});var ARr=T(_pe=>{"use strict";Object.defineProperty(_pe,"__esModule",{value:!0});_pe.ExportResultCode=void 0;var Yoo;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Yoo=_pe.ExportResultCode||(_pe.ExportResultCode={}))});var _Rr=T(GDe=>{"use strict";Object.defineProperty(GDe,"__esModule",{value:!0});GDe.CompositePropagator=void 0;var yRr=(Zt(),vt(ur)),uyt=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){yRr.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){yRr.diag.warn(`Failed to extract with ${s.constructor.name}. Err: ${a.message}`)}return o},e)}fields(){return this._fields.slice()}};GDe.CompositePropagator=uyt});var ERr=T(YK=>{"use strict";Object.defineProperty(YK,"__esModule",{value:!0});YK.validateValue=YK.validateKey=void 0;var dyt="[_0-9a-z-*/]",Koo=`[a-z]${dyt}{0,255}`,Xoo=`[a-z0-9]${dyt}{0,240}@[a-z]${dyt}{0,13}`,Joo=new RegExp(`^(?:${Koo}|${Xoo})$`),Zoo=/^[ -~]{0,255}[!-~]$/,eso=/,|=/;function tso(t){return Joo.test(t)}YK.validateKey=tso;function rso(t){return Zoo.test(t)&&!eso.test(t)}YK.validateValue=rso});var pyt=T($De=>{"use strict";Object.defineProperty($De,"__esModule",{value:!0});$De.TraceState=void 0;var vRr=ERr(),bRr=32,nso=512,CRr=",",SRr="=",fyt=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+SRr+this.get(r)),e),[]).join(CRr)}_parse(e){e.length>nso||(this._internalState=e.split(CRr).reverse().reduce((r,n)=>{let o=n.trim(),s=o.indexOf(SRr);if(s!==-1){let a=o.slice(0,s),c=o.slice(s+1,n.length);(0,vRr.validateKey)(a)&&(0,vRr.validateValue)(c)&&r.set(a,c)}return r},new Map),this._internalState.size>bRr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,bRr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};$De.TraceState=fyt});var wRr=T(wA=>{"use strict";Object.defineProperty(wA,"__esModule",{value:!0});wA.W3CTraceContextPropagator=wA.parseTraceParent=wA.TRACE_STATE_HEADER=wA.TRACE_PARENT_HEADER=void 0;var qDe=(Zt(),vt(ur)),iso=Ape(),oso=pyt();wA.TRACE_PARENT_HEADER="traceparent";wA.TRACE_STATE_HEADER="tracestate";var sso="00",aso="(?!ff)[\\da-f]{2}",cso="(?![0]{32})[\\da-f]{32}",lso="(?![0]{16})[\\da-f]{16}",uso="[\\da-f]{2}",dso=new RegExp(`^\\s?(${aso})-(${cso})-(${lso})-(${uso})(-.*)?\\s?$`);function xRr(t){let e=dso.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}wA.parseTraceParent=xRr;var hyt=class{inject(e,r,n){let o=qDe.trace.getSpanContext(e);if(!o||(0,iso.isTracingSuppressed)(e)||!(0,qDe.isSpanContextValid)(o))return;let s=`${sso}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||qDe.TraceFlags.NONE).toString(16)}`;n.set(r,wA.TRACE_PARENT_HEADER,s),o.traceState&&n.set(r,wA.TRACE_STATE_HEADER,o.traceState.serialize())}extract(e,r,n){let o=n.get(r,wA.TRACE_PARENT_HEADER);if(!o)return e;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let a=xRr(s);if(!a)return e;a.isRemote=!0;let c=n.get(r,wA.TRACE_STATE_HEADER);if(c){let u=Array.isArray(c)?c.join(","):c;a.traceState=new oso.TraceState(typeof u=="string"?u:void 0)}return qDe.trace.setSpanContext(e,a)}fields(){return[wA.TRACE_PARENT_HEADER,wA.TRACE_STATE_HEADER]}};wA.W3CTraceContextPropagator=hyt});var TRr=T(dC=>{"use strict";Object.defineProperty(dC,"__esModule",{value:!0});dC.getRPCMetadata=dC.deleteRPCMetadata=dC.setRPCMetadata=dC.RPCType=void 0;var fso=(Zt(),vt(ur)),myt=(0,fso.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),pso;(function(t){t.HTTP="http"})(pso=dC.RPCType||(dC.RPCType={}));function hso(t,e){return t.setValue(myt,e)}dC.setRPCMetadata=hso;function mso(t){return t.deleteValue(myt)}dC.deleteRPCMetadata=mso;function gso(t){return t.getValue(myt)}dC.getRPCMetadata=gso});var ORr=T(HDe=>{"use strict";Object.defineProperty(HDe,"__esModule",{value:!0});HDe.isPlainObject=void 0;var Aso="[object Object]",yso="[object Null]",_so="[object Undefined]",Eso=Function.prototype,IRr=Eso.toString,vso=IRr.call(Object),bso=Object.getPrototypeOf,DRr=Object.prototype,RRr=DRr.hasOwnProperty,zL=Symbol?Symbol.toStringTag:void 0,NRr=DRr.toString;function Cso(t){if(!Sso(t)||xso(t)!==Aso)return!1;let e=bso(t);if(e===null)return!0;let r=RRr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&IRr.call(r)===vso}HDe.isPlainObject=Cso;function Sso(t){return t!=null&&typeof t=="object"}function xso(t){return t==null?t===void 0?_so:yso:zL&&zL in Object(t)?wso(t):Tso(t)}function wso(t){let e=RRr.call(t,zL),r=t[zL],n=!1;try{t[zL]=void 0,n=!0}catch{}let o=NRr.call(t);return n&&(e?t[zL]=r:delete t[zL]),o}function Tso(t){return NRr.call(t)}});var FRr=T(zDe=>{"use strict";Object.defineProperty(zDe,"__esModule",{value:!0});zDe.merge=void 0;var kRr=ORr(),Iso=20;function Dso(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=PRr(e,t.shift(),0,r);return e}zDe.merge=Dso;function gyt(t){return WDe(t)?t.slice():t}function PRr(t,e,r=0,n){let o;if(!(r>Iso)){if(r++,VDe(t)||VDe(e)||MRr(e))o=gyt(e);else if(WDe(t)){if(o=t.slice(),WDe(e))for(let s=0,a=e.length;s<a;s++)o.push(gyt(e[s]));else if(Epe(e)){let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a];o[u]=gyt(e[u])}}}else if(Epe(t))if(Epe(e)){if(!Rso(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(VDe(d))typeof d>"u"?delete o[u]:o[u]=d;else{let f=o[u],p=d;if(BRr(t,u,n)||BRr(e,u,n))delete o[u];else{if(Epe(f)&&Epe(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]=PRr(o[u],d,r,n)}}}}else o=e;return o}}function BRr(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 WDe(t){return Array.isArray(t)}function MRr(t){return typeof t=="function"}function Epe(t){return!VDe(t)&&!WDe(t)&&!MRr(t)&&typeof t=="object"}function VDe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function Rso(t,e){return!(!(0,kRr.isPlainObject)(t)||!(0,kRr.isPlainObject)(e))}});var LRr=T(KK=>{"use strict";Object.defineProperty(KK,"__esModule",{value:!0});KK.callWithTimeout=KK.TimeoutError=void 0;var YDe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};KK.TimeoutError=YDe;function Nso(t,e){let r,n=new Promise(function(s,a){r=setTimeout(function(){a(new YDe("Operation timed out."))},e)});return Promise.race([t,n]).then(o=>(clearTimeout(r),o),o=>{throw clearTimeout(r),o})}KK.callWithTimeout=Nso});var QRr=T(XK=>{"use strict";Object.defineProperty(XK,"__esModule",{value:!0});XK.isUrlIgnored=XK.urlMatches=void 0;function URr(t,e){return typeof e=="string"?t===e:!!t.match(e)}XK.urlMatches=URr;function Oso(t,e){if(!e)return!1;for(let r of e)if(URr(t,r))return!0;return!1}XK.isUrlIgnored=Oso});var jRr=T(KDe=>{"use strict";Object.defineProperty(KDe,"__esModule",{value:!0});KDe.Deferred=void 0;var Ayt=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)}};KDe.Deferred=Ayt});var GRr=T(XDe=>{"use strict";Object.defineProperty(XDe,"__esModule",{value:!0});XDe.BindOnceFuture=void 0;var kso=jRr(),yyt=class{_callback;_that;_isCalled=!1;_deferred=new kso.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}};XDe.BindOnceFuture=yyt});var qRr=T(JDe=>{"use strict";Object.defineProperty(JDe,"__esModule",{value:!0});JDe.diagLogLevelFromString=void 0;var D9=(Zt(),vt(ur)),$Rr={ALL:D9.DiagLogLevel.ALL,VERBOSE:D9.DiagLogLevel.VERBOSE,DEBUG:D9.DiagLogLevel.DEBUG,INFO:D9.DiagLogLevel.INFO,WARN:D9.DiagLogLevel.WARN,ERROR:D9.DiagLogLevel.ERROR,NONE:D9.DiagLogLevel.NONE};function Bso(t){if(t==null)return;let e=$Rr[t.toUpperCase()];return e??(D9.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys($Rr)}, using default`),D9.DiagLogLevel.INFO)}JDe.diagLogLevelFromString=Bso});var VRr=T(ZDe=>{"use strict";Object.defineProperty(ZDe,"__esModule",{value:!0});ZDe._export=void 0;var HRr=(Zt(),vt(ur)),Pso=Ape();function Mso(t,e){return new Promise(r=>{HRr.context.with((0,Pso.suppressTracing)(HRr.context.active()),()=>{t.export(e,n=>{r(n)})})})}ZDe._export=Mso});var Eyt=T(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.internal=Qr.diagLogLevelFromString=Qr.BindOnceFuture=Qr.urlMatches=Qr.isUrlIgnored=Qr.callWithTimeout=Qr.TimeoutError=Qr.merge=Qr.TraceState=Qr.unsuppressTracing=Qr.suppressTracing=Qr.isTracingSuppressed=Qr.setRPCMetadata=Qr.getRPCMetadata=Qr.deleteRPCMetadata=Qr.RPCType=Qr.parseTraceParent=Qr.W3CTraceContextPropagator=Qr.TRACE_STATE_HEADER=Qr.TRACE_PARENT_HEADER=Qr.CompositePropagator=Qr.otperformance=Qr.getStringListFromEnv=Qr.getNumberFromEnv=Qr.getBooleanFromEnv=Qr.getStringFromEnv=Qr._globalThis=Qr.SDK_INFO=Qr.parseKeyPairsIntoRecord=Qr.ExportResultCode=Qr.unrefTimer=Qr.timeInputToHrTime=Qr.millisToHrTime=Qr.isTimeInputHrTime=Qr.isTimeInput=Qr.hrTimeToTimeStamp=Qr.hrTimeToNanoseconds=Qr.hrTimeToMilliseconds=Qr.hrTimeToMicroseconds=Qr.hrTimeDuration=Qr.hrTime=Qr.getTimeOrigin=Qr.addHrTimes=Qr.loggingErrorHandler=Qr.setGlobalErrorHandler=Qr.globalErrorHandler=Qr.sanitizeAttributes=Qr.isAttributeValue=Qr.AnchoredClock=Qr.W3CBaggagePropagator=void 0;var Fso=WDr();Object.defineProperty(Qr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return Fso.W3CBaggagePropagator}});var Lso=zDr();Object.defineProperty(Qr,"AnchoredClock",{enumerable:!0,get:function(){return Lso.AnchoredClock}});var WRr=ZDr();Object.defineProperty(Qr,"isAttributeValue",{enumerable:!0,get:function(){return WRr.isAttributeValue}});Object.defineProperty(Qr,"sanitizeAttributes",{enumerable:!0,get:function(){return WRr.sanitizeAttributes}});var zRr=tRr();Object.defineProperty(Qr,"globalErrorHandler",{enumerable:!0,get:function(){return zRr.globalErrorHandler}});Object.defineProperty(Qr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return zRr.setGlobalErrorHandler}});var Uso=oyt();Object.defineProperty(Qr,"loggingErrorHandler",{enumerable:!0,get:function(){return Uso.loggingErrorHandler}});var ev=mRr();Object.defineProperty(Qr,"addHrTimes",{enumerable:!0,get:function(){return ev.addHrTimes}});Object.defineProperty(Qr,"getTimeOrigin",{enumerable:!0,get:function(){return ev.getTimeOrigin}});Object.defineProperty(Qr,"hrTime",{enumerable:!0,get:function(){return ev.hrTime}});Object.defineProperty(Qr,"hrTimeDuration",{enumerable:!0,get:function(){return ev.hrTimeDuration}});Object.defineProperty(Qr,"hrTimeToMicroseconds",{enumerable:!0,get:function(){return ev.hrTimeToMicroseconds}});Object.defineProperty(Qr,"hrTimeToMilliseconds",{enumerable:!0,get:function(){return ev.hrTimeToMilliseconds}});Object.defineProperty(Qr,"hrTimeToNanoseconds",{enumerable:!0,get:function(){return ev.hrTimeToNanoseconds}});Object.defineProperty(Qr,"hrTimeToTimeStamp",{enumerable:!0,get:function(){return ev.hrTimeToTimeStamp}});Object.defineProperty(Qr,"isTimeInput",{enumerable:!0,get:function(){return ev.isTimeInput}});Object.defineProperty(Qr,"isTimeInputHrTime",{enumerable:!0,get:function(){return ev.isTimeInputHrTime}});Object.defineProperty(Qr,"millisToHrTime",{enumerable:!0,get:function(){return ev.millisToHrTime}});Object.defineProperty(Qr,"timeInputToHrTime",{enumerable:!0,get:function(){return ev.timeInputToHrTime}});var Qso=gRr();Object.defineProperty(Qr,"unrefTimer",{enumerable:!0,get:function(){return Qso.unrefTimer}});var jso=ARr();Object.defineProperty(Qr,"ExportResultCode",{enumerable:!0,get:function(){return jso.ExportResultCode}});var Gso=eyt();Object.defineProperty(Qr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return Gso.parseKeyPairsIntoRecord}});var YL=syt();Object.defineProperty(Qr,"SDK_INFO",{enumerable:!0,get:function(){return YL.SDK_INFO}});Object.defineProperty(Qr,"_globalThis",{enumerable:!0,get:function(){return YL._globalThis}});Object.defineProperty(Qr,"getStringFromEnv",{enumerable:!0,get:function(){return YL.getStringFromEnv}});Object.defineProperty(Qr,"getBooleanFromEnv",{enumerable:!0,get:function(){return YL.getBooleanFromEnv}});Object.defineProperty(Qr,"getNumberFromEnv",{enumerable:!0,get:function(){return YL.getNumberFromEnv}});Object.defineProperty(Qr,"getStringListFromEnv",{enumerable:!0,get:function(){return YL.getStringListFromEnv}});Object.defineProperty(Qr,"otperformance",{enumerable:!0,get:function(){return YL.otperformance}});var $so=_Rr();Object.defineProperty(Qr,"CompositePropagator",{enumerable:!0,get:function(){return $so.CompositePropagator}});var eRe=wRr();Object.defineProperty(Qr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return eRe.TRACE_PARENT_HEADER}});Object.defineProperty(Qr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return eRe.TRACE_STATE_HEADER}});Object.defineProperty(Qr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return eRe.W3CTraceContextPropagator}});Object.defineProperty(Qr,"parseTraceParent",{enumerable:!0,get:function(){return eRe.parseTraceParent}});var tRe=TRr();Object.defineProperty(Qr,"RPCType",{enumerable:!0,get:function(){return tRe.RPCType}});Object.defineProperty(Qr,"deleteRPCMetadata",{enumerable:!0,get:function(){return tRe.deleteRPCMetadata}});Object.defineProperty(Qr,"getRPCMetadata",{enumerable:!0,get:function(){return tRe.getRPCMetadata}});Object.defineProperty(Qr,"setRPCMetadata",{enumerable:!0,get:function(){return tRe.setRPCMetadata}});var _yt=Ape();Object.defineProperty(Qr,"isTracingSuppressed",{enumerable:!0,get:function(){return _yt.isTracingSuppressed}});Object.defineProperty(Qr,"suppressTracing",{enumerable:!0,get:function(){return _yt.suppressTracing}});Object.defineProperty(Qr,"unsuppressTracing",{enumerable:!0,get:function(){return _yt.unsuppressTracing}});var qso=pyt();Object.defineProperty(Qr,"TraceState",{enumerable:!0,get:function(){return qso.TraceState}});var Hso=FRr();Object.defineProperty(Qr,"merge",{enumerable:!0,get:function(){return Hso.merge}});var YRr=LRr();Object.defineProperty(Qr,"TimeoutError",{enumerable:!0,get:function(){return YRr.TimeoutError}});Object.defineProperty(Qr,"callWithTimeout",{enumerable:!0,get:function(){return YRr.callWithTimeout}});var KRr=QRr();Object.defineProperty(Qr,"isUrlIgnored",{enumerable:!0,get:function(){return KRr.isUrlIgnored}});Object.defineProperty(Qr,"urlMatches",{enumerable:!0,get:function(){return KRr.urlMatches}});var Vso=GRr();Object.defineProperty(Qr,"BindOnceFuture",{enumerable:!0,get:function(){return Vso.BindOnceFuture}});var Wso=qRr();Object.defineProperty(Qr,"diagLogLevelFromString",{enumerable:!0,get:function(){return Wso.diagLogLevelFromString}});var zso=VRr();Qr.internal={_export:zso._export}});var XRr=T(rRe=>{"use strict";Object.defineProperty(rRe,"__esModule",{value:!0});rRe.defaultServiceName=void 0;function Yso(){return`unknown_service:${process.argv0}`}rRe.defaultServiceName=Yso});var JRr=T(nRe=>{"use strict";Object.defineProperty(nRe,"__esModule",{value:!0});nRe.defaultServiceName=void 0;var Kso=XRr();Object.defineProperty(nRe,"defaultServiceName",{enumerable:!0,get:function(){return Kso.defaultServiceName}})});var vyt=T(iRe=>{"use strict";Object.defineProperty(iRe,"__esModule",{value:!0});iRe.defaultServiceName=void 0;var Xso=JRr();Object.defineProperty(iRe,"defaultServiceName",{enumerable:!0,get:function(){return Xso.defaultServiceName}})});var ZRr=T(JK=>{"use strict";Object.defineProperty(JK,"__esModule",{value:!0});JK.identity=JK.isPromiseLike=void 0;var Jso=t=>t!==null&&typeof t=="object"&&typeof t.then=="function";JK.isPromiseLike=Jso;function Zso(t){return t}JK.identity=Zso});var Syt=T(Ix=>{"use strict";Object.defineProperty(Ix,"__esModule",{value:!0});Ix.defaultResource=Ix.emptyResource=Ix.resourceFromDetectedResource=Ix.resourceFromAttributes=void 0;var bpe=(Zt(),vt(ur)),byt=Eyt(),KL=($h(),vt(yA)),eao=vyt(),vpe=ZRr(),oRe=class t{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(e,r){let n=new t({},r);return n._rawAttributes=eNr(e),n._asyncAttributesPending=e.filter(([o,s])=>(0,vpe.isPromiseLike)(s)).length>0,n}constructor(e,r){let n=e.attributes??{};this._rawAttributes=Object.entries(n).map(([o,s])=>((0,vpe.isPromiseLike)(s)&&(this._asyncAttributesPending=!0),[o,s])),this._rawAttributes=eNr(this._rawAttributes),this._schemaUrl=iao(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,vpe.isPromiseLike)(n)?await n:n]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&bpe.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,vpe.isPromiseLike)(n)){bpe.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=oao(this,e),n=r?{schemaUrl:r}:void 0;return t.FromAttributeList([...e.getRawAttributes(),...this.getRawAttributes()],n)}};function Cyt(t,e){return oRe.FromAttributeList(Object.entries(t),e)}Ix.resourceFromAttributes=Cyt;function tao(t,e){return new oRe(t,e)}Ix.resourceFromDetectedResource=tao;function rao(){return Cyt({})}Ix.emptyResource=rao;function nao(){return Cyt({[KL.ATTR_SERVICE_NAME]:(0,eao.defaultServiceName)(),[KL.ATTR_TELEMETRY_SDK_LANGUAGE]:byt.SDK_INFO[KL.ATTR_TELEMETRY_SDK_LANGUAGE],[KL.ATTR_TELEMETRY_SDK_NAME]:byt.SDK_INFO[KL.ATTR_TELEMETRY_SDK_NAME],[KL.ATTR_TELEMETRY_SDK_VERSION]:byt.SDK_INFO[KL.ATTR_TELEMETRY_SDK_VERSION]})}Ix.defaultResource=nao;function eNr(t){return t.map(([e,r])=>(0,vpe.isPromiseLike)(r)?[e,r.catch(n=>{bpe.diag.debug("promise rejection for resource attribute: %s - %s",e,n)})]:[e,r])}function iao(t){if(typeof t=="string"||t===void 0)return t;bpe.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t)}function oao(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;bpe.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',r,n)}});var rNr=T(sRe=>{"use strict";Object.defineProperty(sRe,"__esModule",{value:!0});sRe.detectResources=void 0;var tNr=(Zt(),vt(ur)),xyt=Syt(),sao=(t={})=>(t.detectors||[]).map(r=>{try{let n=(0,xyt.resourceFromDetectedResource)(r.detect(t));return tNr.diag.debug(`${r.constructor.name} found resource.`,n),n}catch(n){return tNr.diag.debug(`${r.constructor.name} failed: ${n.message}`),(0,xyt.emptyResource)()}}).reduce((r,n)=>r.merge(n),(0,xyt.emptyResource)());sRe.detectResources=sao});var iNr=T(aRe=>{"use strict";Object.defineProperty(aRe,"__esModule",{value:!0});aRe.envDetector=void 0;var aao=(Zt(),vt(ur)),cao=($h(),vt(yA)),nNr=Eyt(),wyt=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,nNr.getStringFromEnv)("OTEL_RESOURCE_ATTRIBUTES"),o=(0,nNr.getStringFromEnv)("OTEL_SERVICE_NAME");if(n)try{let s=this._parseResourceAttributes(n);Object.assign(r,s)}catch(s){aao.diag.debug(`EnvDetector failed: ${s.message}`)}return o&&(r[cao.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)}};aRe.envDetector=new wyt});var Cpe=T(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.ATTR_WEBENGINE_VERSION=Pn.ATTR_WEBENGINE_NAME=Pn.ATTR_WEBENGINE_DESCRIPTION=Pn.ATTR_SERVICE_NAMESPACE=Pn.ATTR_SERVICE_INSTANCE_ID=Pn.ATTR_PROCESS_RUNTIME_VERSION=Pn.ATTR_PROCESS_RUNTIME_NAME=Pn.ATTR_PROCESS_RUNTIME_DESCRIPTION=Pn.ATTR_PROCESS_PID=Pn.ATTR_PROCESS_OWNER=Pn.ATTR_PROCESS_EXECUTABLE_PATH=Pn.ATTR_PROCESS_EXECUTABLE_NAME=Pn.ATTR_PROCESS_COMMAND_ARGS=Pn.ATTR_PROCESS_COMMAND=Pn.ATTR_OS_VERSION=Pn.ATTR_OS_TYPE=Pn.ATTR_K8S_POD_NAME=Pn.ATTR_K8S_NAMESPACE_NAME=Pn.ATTR_K8S_DEPLOYMENT_NAME=Pn.ATTR_K8S_CLUSTER_NAME=Pn.ATTR_HOST_TYPE=Pn.ATTR_HOST_NAME=Pn.ATTR_HOST_IMAGE_VERSION=Pn.ATTR_HOST_IMAGE_NAME=Pn.ATTR_HOST_IMAGE_ID=Pn.ATTR_HOST_ID=Pn.ATTR_HOST_ARCH=Pn.ATTR_CONTAINER_NAME=Pn.ATTR_CONTAINER_IMAGE_TAGS=Pn.ATTR_CONTAINER_IMAGE_NAME=Pn.ATTR_CONTAINER_ID=Pn.ATTR_CLOUD_REGION=Pn.ATTR_CLOUD_PROVIDER=Pn.ATTR_CLOUD_AVAILABILITY_ZONE=Pn.ATTR_CLOUD_ACCOUNT_ID=void 0;Pn.ATTR_CLOUD_ACCOUNT_ID="cloud.account.id";Pn.ATTR_CLOUD_AVAILABILITY_ZONE="cloud.availability_zone";Pn.ATTR_CLOUD_PROVIDER="cloud.provider";Pn.ATTR_CLOUD_REGION="cloud.region";Pn.ATTR_CONTAINER_ID="container.id";Pn.ATTR_CONTAINER_IMAGE_NAME="container.image.name";Pn.ATTR_CONTAINER_IMAGE_TAGS="container.image.tags";Pn.ATTR_CONTAINER_NAME="container.name";Pn.ATTR_HOST_ARCH="host.arch";Pn.ATTR_HOST_ID="host.id";Pn.ATTR_HOST_IMAGE_ID="host.image.id";Pn.ATTR_HOST_IMAGE_NAME="host.image.name";Pn.ATTR_HOST_IMAGE_VERSION="host.image.version";Pn.ATTR_HOST_NAME="host.name";Pn.ATTR_HOST_TYPE="host.type";Pn.ATTR_K8S_CLUSTER_NAME="k8s.cluster.name";Pn.ATTR_K8S_DEPLOYMENT_NAME="k8s.deployment.name";Pn.ATTR_K8S_NAMESPACE_NAME="k8s.namespace.name";Pn.ATTR_K8S_POD_NAME="k8s.pod.name";Pn.ATTR_OS_TYPE="os.type";Pn.ATTR_OS_VERSION="os.version";Pn.ATTR_PROCESS_COMMAND="process.command";Pn.ATTR_PROCESS_COMMAND_ARGS="process.command_args";Pn.ATTR_PROCESS_EXECUTABLE_NAME="process.executable.name";Pn.ATTR_PROCESS_EXECUTABLE_PATH="process.executable.path";Pn.ATTR_PROCESS_OWNER="process.owner";Pn.ATTR_PROCESS_PID="process.pid";Pn.ATTR_PROCESS_RUNTIME_DESCRIPTION="process.runtime.description";Pn.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name";Pn.ATTR_PROCESS_RUNTIME_VERSION="process.runtime.version";Pn.ATTR_SERVICE_INSTANCE_ID="service.instance.id";Pn.ATTR_SERVICE_NAMESPACE="service.namespace";Pn.ATTR_WEBENGINE_DESCRIPTION="webengine.description";Pn.ATTR_WEBENGINE_NAME="webengine.name";Pn.ATTR_WEBENGINE_VERSION="webengine.version"});var lRe=T(cRe=>{"use strict";Object.defineProperty(cRe,"__esModule",{value:!0});cRe.execAsync=void 0;var lao=ye("child_process"),uao=ye("util");cRe.execAsync=uao.promisify(lao.exec)});var oNr=T(uRe=>{"use strict";Object.defineProperty(uRe,"__esModule",{value:!0});uRe.getMachineId=void 0;var dao=lRe(),fao=(Zt(),vt(ur));async function pao(){try{let e=(await(0,dao.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split(`
485
- `).find(n=>n.includes("IOPlatformUUID"));if(!e)return;let r=e.split('" = "');if(r.length===2)return r[1].slice(0,-1)}catch(t){fao.diag.debug(`error reading machine id: ${t}`)}}uRe.getMachineId=pao});var sNr=T(dRe=>{"use strict";Object.defineProperty(dRe,"__esModule",{value:!0});dRe.getMachineId=void 0;var hao=ye("fs"),mao=(Zt(),vt(ur));async function gao(){let t=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let e of t)try{return(await hao.promises.readFile(e,{encoding:"utf8"})).trim()}catch(r){mao.diag.debug(`error reading machine id: ${r}`)}}dRe.getMachineId=gao});var cNr=T(fRe=>{"use strict";Object.defineProperty(fRe,"__esModule",{value:!0});fRe.getMachineId=void 0;var Aao=ye("fs"),yao=lRe(),aNr=(Zt(),vt(ur));async function _ao(){try{return(await Aao.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(t){aNr.diag.debug(`error reading machine id: ${t}`)}try{return(await(0,yao.execAsync)("kenv -q smbios.system.uuid")).stdout.trim()}catch(t){aNr.diag.debug(`error reading machine id: ${t}`)}}fRe.getMachineId=_ao});var uNr=T(pRe=>{"use strict";Object.defineProperty(pRe,"__esModule",{value:!0});pRe.getMachineId=void 0;var lNr=ye("process"),Eao=lRe(),vao=(Zt(),vt(ur));async function bao(){let t="QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",e="%windir%\\System32\\REG.exe";lNr.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in lNr.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{let n=(await(0,Eao.execAsync)(`${e} ${t}`)).stdout.split("REG_SZ");if(n.length===2)return n[1].trim()}catch(r){vao.diag.debug(`error reading machine id: ${r}`)}}pRe.getMachineId=bao});var dNr=T(hRe=>{"use strict";Object.defineProperty(hRe,"__esModule",{value:!0});hRe.getMachineId=void 0;var Cao=(Zt(),vt(ur));async function Sao(){Cao.diag.debug("could not read machine-id: unsupported platform")}hRe.getMachineId=Sao});var fNr=T(mRe=>{"use strict";Object.defineProperty(mRe,"__esModule",{value:!0});mRe.getMachineId=void 0;var xao=ye("process"),XL;async function wao(){if(!XL)switch(xao.platform){case"darwin":XL=(await Promise.resolve().then(()=>Te(oNr()))).getMachineId;break;case"linux":XL=(await Promise.resolve().then(()=>Te(sNr()))).getMachineId;break;case"freebsd":XL=(await Promise.resolve().then(()=>Te(cNr()))).getMachineId;break;case"win32":XL=(await Promise.resolve().then(()=>Te(uNr()))).getMachineId;break;default:XL=(await Promise.resolve().then(()=>Te(dNr()))).getMachineId;break}return XL()}mRe.getMachineId=wao});var Tyt=T(ZK=>{"use strict";Object.defineProperty(ZK,"__esModule",{value:!0});ZK.normalizeType=ZK.normalizeArch=void 0;var Tao=t=>{switch(t){case"arm":return"arm32";case"ppc":return"ppc32";case"x64":return"amd64";default:return t}};ZK.normalizeArch=Tao;var Iao=t=>{switch(t){case"sunos":return"solaris";case"win32":return"windows";default:return t}};ZK.normalizeType=Iao});var hNr=T(gRe=>{"use strict";Object.defineProperty(gRe,"__esModule",{value:!0});gRe.hostDetector=void 0;var Iyt=Cpe(),pNr=ye("os"),Dao=fNr(),Rao=Tyt(),Dyt=class{detect(e){return{attributes:{[Iyt.ATTR_HOST_NAME]:(0,pNr.hostname)(),[Iyt.ATTR_HOST_ARCH]:(0,Rao.normalizeArch)((0,pNr.arch)()),[Iyt.ATTR_HOST_ID]:(0,Dao.getMachineId)()}}}};gRe.hostDetector=new Dyt});var ANr=T(ARe=>{"use strict";Object.defineProperty(ARe,"__esModule",{value:!0});ARe.osDetector=void 0;var mNr=Cpe(),gNr=ye("os"),Nao=Tyt(),Ryt=class{detect(e){return{attributes:{[mNr.ATTR_OS_TYPE]:(0,Nao.normalizeType)((0,gNr.platform)()),[mNr.ATTR_OS_VERSION]:(0,gNr.release)()}}}};ARe.osDetector=new Ryt});var yNr=T(yRe=>{"use strict";Object.defineProperty(yRe,"__esModule",{value:!0});yRe.processDetector=void 0;var Oao=(Zt(),vt(ur)),R9=Cpe(),kao=ye("os"),Nyt=class{detect(e){let r={[R9.ATTR_PROCESS_PID]:process.pid,[R9.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[R9.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[R9.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[R9.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[R9.ATTR_PROCESS_RUNTIME_NAME]:"nodejs",[R9.ATTR_PROCESS_RUNTIME_DESCRIPTION]:"Node.js"};process.argv.length>1&&(r[R9.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let n=kao.userInfo();r[R9.ATTR_PROCESS_OWNER]=n.username}catch(n){Oao.diag.debug(`error obtaining process owner: ${n}`)}return{attributes:r}}};yRe.processDetector=new Nyt});var _Nr=T(_Re=>{"use strict";Object.defineProperty(_Re,"__esModule",{value:!0});_Re.serviceInstanceIdDetector=void 0;var Bao=Cpe(),Pao=ye("crypto"),Oyt=class{detect(e){return{attributes:{[Bao.ATTR_SERVICE_INSTANCE_ID]:(0,Pao.randomUUID)()}}}};_Re.serviceInstanceIdDetector=new Oyt});var ENr=T(Dx=>{"use strict";Object.defineProperty(Dx,"__esModule",{value:!0});Dx.serviceInstanceIdDetector=Dx.processDetector=Dx.osDetector=Dx.hostDetector=void 0;var Mao=hNr();Object.defineProperty(Dx,"hostDetector",{enumerable:!0,get:function(){return Mao.hostDetector}});var Fao=ANr();Object.defineProperty(Dx,"osDetector",{enumerable:!0,get:function(){return Fao.osDetector}});var Lao=yNr();Object.defineProperty(Dx,"processDetector",{enumerable:!0,get:function(){return Lao.processDetector}});var Uao=_Nr();Object.defineProperty(Dx,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return Uao.serviceInstanceIdDetector}})});var vNr=T(Rx=>{"use strict";Object.defineProperty(Rx,"__esModule",{value:!0});Rx.serviceInstanceIdDetector=Rx.processDetector=Rx.osDetector=Rx.hostDetector=void 0;var ERe=ENr();Object.defineProperty(Rx,"hostDetector",{enumerable:!0,get:function(){return ERe.hostDetector}});Object.defineProperty(Rx,"osDetector",{enumerable:!0,get:function(){return ERe.osDetector}});Object.defineProperty(Rx,"processDetector",{enumerable:!0,get:function(){return ERe.processDetector}});Object.defineProperty(Rx,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return ERe.serviceInstanceIdDetector}})});var bNr=T(eX=>{"use strict";Object.defineProperty(eX,"__esModule",{value:!0});eX.noopDetector=eX.NoopDetector=void 0;var vRe=class{detect(){return{attributes:{}}}};eX.NoopDetector=vRe;eX.noopDetector=new vRe});var CNr=T(M3=>{"use strict";Object.defineProperty(M3,"__esModule",{value:!0});M3.noopDetector=M3.serviceInstanceIdDetector=M3.processDetector=M3.osDetector=M3.hostDetector=M3.envDetector=void 0;var Qao=iNr();Object.defineProperty(M3,"envDetector",{enumerable:!0,get:function(){return Qao.envDetector}});var bRe=vNr();Object.defineProperty(M3,"hostDetector",{enumerable:!0,get:function(){return bRe.hostDetector}});Object.defineProperty(M3,"osDetector",{enumerable:!0,get:function(){return bRe.osDetector}});Object.defineProperty(M3,"processDetector",{enumerable:!0,get:function(){return bRe.processDetector}});Object.defineProperty(M3,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return bRe.serviceInstanceIdDetector}});var jao=bNr();Object.defineProperty(M3,"noopDetector",{enumerable:!0,get:function(){return jao.noopDetector}})});var Byt=T(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});Uf.defaultServiceName=Uf.emptyResource=Uf.defaultResource=Uf.resourceFromAttributes=Uf.serviceInstanceIdDetector=Uf.processDetector=Uf.osDetector=Uf.hostDetector=Uf.envDetector=Uf.detectResources=void 0;var Gao=rNr();Object.defineProperty(Uf,"detectResources",{enumerable:!0,get:function(){return Gao.detectResources}});var Spe=CNr();Object.defineProperty(Uf,"envDetector",{enumerable:!0,get:function(){return Spe.envDetector}});Object.defineProperty(Uf,"hostDetector",{enumerable:!0,get:function(){return Spe.hostDetector}});Object.defineProperty(Uf,"osDetector",{enumerable:!0,get:function(){return Spe.osDetector}});Object.defineProperty(Uf,"processDetector",{enumerable:!0,get:function(){return Spe.processDetector}});Object.defineProperty(Uf,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return Spe.serviceInstanceIdDetector}});var kyt=Syt();Object.defineProperty(Uf,"resourceFromAttributes",{enumerable:!0,get:function(){return kyt.resourceFromAttributes}});Object.defineProperty(Uf,"defaultResource",{enumerable:!0,get:function(){return kyt.defaultResource}});Object.defineProperty(Uf,"emptyResource",{enumerable:!0,get:function(){return kyt.emptyResource}});var $ao=vyt();Object.defineProperty(Uf,"defaultServiceName",{enumerable:!0,get:function(){return $ao.defaultServiceName}})});var SNr=T(xpe=>{"use strict";Object.defineProperty(xpe,"__esModule",{value:!0});xpe.SeverityNumber=void 0;var qao;(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"})(qao=xpe.SeverityNumber||(xpe.SeverityNumber={}))});var SRe=T(tX=>{"use strict";Object.defineProperty(tX,"__esModule",{value:!0});tX.NOOP_LOGGER=tX.NoopLogger=void 0;var CRe=class{emit(e){}};tX.NoopLogger=CRe;tX.NOOP_LOGGER=new CRe});var wRe=T(rX=>{"use strict";Object.defineProperty(rX,"__esModule",{value:!0});rX.NOOP_LOGGER_PROVIDER=rX.NoopLoggerProvider=void 0;var Hao=SRe(),xRe=class{getLogger(e,r,n){return new Hao.NoopLogger}};rX.NoopLoggerProvider=xRe;rX.NOOP_LOGGER_PROVIDER=new xRe});var Myt=T(TRe=>{"use strict";Object.defineProperty(TRe,"__esModule",{value:!0});TRe.ProxyLogger=void 0;var Vao=SRe(),Pyt=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):Vao.NOOP_LOGGER}};TRe.ProxyLogger=Pyt});var Lyt=T(IRe=>{"use strict";Object.defineProperty(IRe,"__esModule",{value:!0});IRe.ProxyLoggerProvider=void 0;var Wao=wRe(),zao=Myt(),Fyt=class{getLogger(e,r,n){var o;return(o=this._getDelegateLogger(e,r,n))!==null&&o!==void 0?o:new zao.ProxyLogger(this,e,r,n)}_getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Wao.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)}};IRe.ProxyLoggerProvider=Fyt});var xNr=T(DRe=>{"use strict";Object.defineProperty(DRe,"__esModule",{value:!0});DRe._globalThis=void 0;DRe._globalThis=typeof globalThis=="object"?globalThis:global});var wNr=T(RRe=>{"use strict";Object.defineProperty(RRe,"__esModule",{value:!0});RRe._globalThis=void 0;var Yao=xNr();Object.defineProperty(RRe,"_globalThis",{enumerable:!0,get:function(){return Yao._globalThis}})});var TNr=T(NRe=>{"use strict";Object.defineProperty(NRe,"__esModule",{value:!0});NRe._globalThis=void 0;var Kao=wNr();Object.defineProperty(NRe,"_globalThis",{enumerable:!0,get:function(){return Kao._globalThis}})});var INr=T(Nx=>{"use strict";Object.defineProperty(Nx,"__esModule",{value:!0});Nx.API_BACKWARDS_COMPATIBILITY_VERSION=Nx.makeGetter=Nx._global=Nx.GLOBAL_LOGS_API_KEY=void 0;var Xao=TNr();Nx.GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs");Nx._global=Xao._globalThis;function Jao(t,e,r){return n=>n===t?e:r}Nx.makeGetter=Jao;Nx.API_BACKWARDS_COMPATIBILITY_VERSION=1});var RNr=T(ORe=>{"use strict";Object.defineProperty(ORe,"__esModule",{value:!0});ORe.LogsAPI=void 0;var tv=INr(),Zao=wRe(),DNr=Lyt(),Uyt=class t{constructor(){this._proxyLoggerProvider=new DNr.ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalLoggerProvider(e){return tv._global[tv.GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(tv._global[tv.GLOBAL_LOGS_API_KEY]=(0,tv.makeGetter)(tv.API_BACKWARDS_COMPATIBILITY_VERSION,e,Zao.NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider._setDelegate(e),e)}getLoggerProvider(){var e,r;return(r=(e=tv._global[tv.GLOBAL_LOGS_API_KEY])===null||e===void 0?void 0:e.call(tv._global,tv.API_BACKWARDS_COMPATIBILITY_VERSION))!==null&&r!==void 0?r:this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){delete tv._global[tv.GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new DNr.ProxyLoggerProvider}};ORe.LogsAPI=Uyt});var kNr=T(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});Km.logs=Km.ProxyLoggerProvider=Km.ProxyLogger=Km.NoopLoggerProvider=Km.NOOP_LOGGER_PROVIDER=Km.NoopLogger=Km.NOOP_LOGGER=Km.SeverityNumber=void 0;var eco=SNr();Object.defineProperty(Km,"SeverityNumber",{enumerable:!0,get:function(){return eco.SeverityNumber}});var NNr=SRe();Object.defineProperty(Km,"NOOP_LOGGER",{enumerable:!0,get:function(){return NNr.NOOP_LOGGER}});Object.defineProperty(Km,"NoopLogger",{enumerable:!0,get:function(){return NNr.NoopLogger}});var ONr=wRe();Object.defineProperty(Km,"NOOP_LOGGER_PROVIDER",{enumerable:!0,get:function(){return ONr.NOOP_LOGGER_PROVIDER}});Object.defineProperty(Km,"NoopLoggerProvider",{enumerable:!0,get:function(){return ONr.NoopLoggerProvider}});var tco=Myt();Object.defineProperty(Km,"ProxyLogger",{enumerable:!0,get:function(){return tco.ProxyLogger}});var rco=Lyt();Object.defineProperty(Km,"ProxyLoggerProvider",{enumerable:!0,get:function(){return rco.ProxyLoggerProvider}});var nco=RNr();Km.logs=nco.LogsAPI.getInstance()});var wpe=T(DN=>{"use strict";Object.defineProperty(DN,"__esModule",{value:!0});DN.isTracingSuppressed=DN.unsuppressTracing=DN.suppressTracing=void 0;var ico=(Zt(),vt(ur)),Qyt=(0,ico.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function oco(t){return t.setValue(Qyt,!0)}DN.suppressTracing=oco;function sco(t){return t.deleteValue(Qyt)}DN.unsuppressTracing=sco;function aco(t){return t.getValue(Qyt)===!0}DN.isTracingSuppressed=aco});var jyt=T(TA=>{"use strict";Object.defineProperty(TA,"__esModule",{value:!0});TA.BAGGAGE_MAX_TOTAL_LENGTH=TA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=TA.BAGGAGE_MAX_NAME_VALUE_PAIRS=TA.BAGGAGE_HEADER=TA.BAGGAGE_ITEMS_SEPARATOR=TA.BAGGAGE_PROPERTIES_SEPARATOR=TA.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;TA.BAGGAGE_KEY_PAIR_SEPARATOR="=";TA.BAGGAGE_PROPERTIES_SEPARATOR=";";TA.BAGGAGE_ITEMS_SEPARATOR=",";TA.BAGGAGE_HEADER="baggage";TA.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;TA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;TA.BAGGAGE_MAX_TOTAL_LENGTH=8192});var Gyt=T(Ox=>{"use strict";Object.defineProperty(Ox,"__esModule",{value:!0});Ox.parseKeyPairsIntoRecord=Ox.parsePairKeyValue=Ox.getKeyPairs=Ox.serializeKeyPairs=void 0;var cco=(Zt(),vt(ur)),JL=jyt();function lco(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?JL.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>JL.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}Ox.serializeKeyPairs=lco;function uco(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=JL.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}Ox.getKeyPairs=uco;function BNr(t){let e=t.split(JL.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(JL.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,cco.baggageEntryMetadataFromString)(e.join(JL.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:a}}Ox.parsePairKeyValue=BNr;function dco(t){let e={};return typeof t=="string"&&t.length>0&&t.split(JL.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=BNr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}Ox.parseKeyPairsIntoRecord=dco});var PNr=T(kRe=>{"use strict";Object.defineProperty(kRe,"__esModule",{value:!0});kRe.W3CBaggagePropagator=void 0;var $yt=(Zt(),vt(ur)),fco=wpe(),ZL=jyt(),qyt=Gyt(),Hyt=class{inject(e,r,n){let o=$yt.propagation.getBaggage(e);if(!o||(0,fco.isTracingSuppressed)(e))return;let s=(0,qyt.getKeyPairs)(o).filter(c=>c.length<=ZL.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,ZL.BAGGAGE_MAX_NAME_VALUE_PAIRS),a=(0,qyt.serializeKeyPairs)(s);a.length>0&&n.set(r,ZL.BAGGAGE_HEADER,a)}extract(e,r,n){let o=n.get(r,ZL.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(ZL.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let a={};return s.length===0||(s.split(ZL.BAGGAGE_ITEMS_SEPARATOR).forEach(u=>{let d=(0,qyt.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:$yt.propagation.setBaggage(e,$yt.propagation.createBaggage(a))}fields(){return[ZL.BAGGAGE_HEADER]}};kRe.W3CBaggagePropagator=Hyt});var MNr=T(BRe=>{"use strict";Object.defineProperty(BRe,"__esModule",{value:!0});BRe.AnchoredClock=void 0;var Vyt=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}};BRe.AnchoredClock=Vyt});var jNr=T(RN=>{"use strict";Object.defineProperty(RN,"__esModule",{value:!0});RN.isAttributeValue=RN.isAttributeKey=RN.sanitizeAttributes=void 0;var FNr=(Zt(),vt(ur));function pco(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(!LNr(r)){FNr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!UNr(n)){FNr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}RN.sanitizeAttributes=pco;function LNr(t){return typeof t=="string"&&t!==""}RN.isAttributeKey=LNr;function UNr(t){return t==null?!0:Array.isArray(t)?hco(t):QNr(typeof t)}RN.isAttributeValue=UNr;function hco(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 Wyt=T(PRe=>{"use strict";Object.defineProperty(PRe,"__esModule",{value:!0});PRe.loggingErrorHandler=void 0;var mco=(Zt(),vt(ur));function gco(){return t=>{mco.diag.error(Aco(t))}}PRe.loggingErrorHandler=gco;function Aco(t){return typeof t=="string"?t:JSON.stringify(yco(t))}function yco(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 $Nr=T(nX=>{"use strict";Object.defineProperty(nX,"__esModule",{value:!0});nX.globalErrorHandler=nX.setGlobalErrorHandler=void 0;var _co=Wyt(),GNr=(0,_co.loggingErrorHandler)();function Eco(t){GNr=t}nX.setGlobalErrorHandler=Eco;function vco(t){try{GNr(t)}catch{}}nX.globalErrorHandler=vco});var WNr=T(kx=>{"use strict";Object.defineProperty(kx,"__esModule",{value:!0});kx.getStringListFromEnv=kx.getBooleanFromEnv=kx.getStringFromEnv=kx.getNumberFromEnv=void 0;var qNr=(Zt(),vt(ur)),HNr=ye("util");function bco(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){qNr.diag.warn(`Unknown value ${(0,HNr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}kx.getNumberFromEnv=bco;function VNr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}kx.getStringFromEnv=VNr;function Cco(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||qNr.diag.warn(`Unknown value ${(0,HNr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}kx.getBooleanFromEnv=Cco;function Sco(t){return VNr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}kx.getStringListFromEnv=Sco});var zNr=T(MRe=>{"use strict";Object.defineProperty(MRe,"__esModule",{value:!0});MRe._globalThis=void 0;MRe._globalThis=typeof globalThis=="object"?globalThis:global});var YNr=T(FRe=>{"use strict";Object.defineProperty(FRe,"__esModule",{value:!0});FRe.otperformance=void 0;var xco=ye("perf_hooks");FRe.otperformance=xco.performance});var KNr=T(LRe=>{"use strict";Object.defineProperty(LRe,"__esModule",{value:!0});LRe.VERSION=void 0;LRe.VERSION="2.2.0"});var XNr=T(URe=>{"use strict";Object.defineProperty(URe,"__esModule",{value:!0});URe.ATTR_PROCESS_RUNTIME_NAME=void 0;URe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var JNr=T(jRe=>{"use strict";Object.defineProperty(jRe,"__esModule",{value:!0});jRe.SDK_INFO=void 0;var wco=KNr(),QRe=($h(),vt(yA)),Tco=XNr();jRe.SDK_INFO={[QRe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[Tco.ATTR_PROCESS_RUNTIME_NAME]:"node",[QRe.ATTR_TELEMETRY_SDK_LANGUAGE]:QRe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[QRe.ATTR_TELEMETRY_SDK_VERSION]:wco.VERSION}});var ZNr=T(IA=>{"use strict";Object.defineProperty(IA,"__esModule",{value:!0});IA.SDK_INFO=IA.otperformance=IA._globalThis=IA.getStringListFromEnv=IA.getNumberFromEnv=IA.getBooleanFromEnv=IA.getStringFromEnv=void 0;var GRe=WNr();Object.defineProperty(IA,"getStringFromEnv",{enumerable:!0,get:function(){return GRe.getStringFromEnv}});Object.defineProperty(IA,"getBooleanFromEnv",{enumerable:!0,get:function(){return GRe.getBooleanFromEnv}});Object.defineProperty(IA,"getNumberFromEnv",{enumerable:!0,get:function(){return GRe.getNumberFromEnv}});Object.defineProperty(IA,"getStringListFromEnv",{enumerable:!0,get:function(){return GRe.getStringListFromEnv}});var Ico=zNr();Object.defineProperty(IA,"_globalThis",{enumerable:!0,get:function(){return Ico._globalThis}});var Dco=YNr();Object.defineProperty(IA,"otperformance",{enumerable:!0,get:function(){return Dco.otperformance}});var Rco=JNr();Object.defineProperty(IA,"SDK_INFO",{enumerable:!0,get:function(){return Rco.SDK_INFO}})});var zyt=T(DA=>{"use strict";Object.defineProperty(DA,"__esModule",{value:!0});DA.getStringListFromEnv=DA.getNumberFromEnv=DA.getStringFromEnv=DA.getBooleanFromEnv=DA.otperformance=DA._globalThis=DA.SDK_INFO=void 0;var eU=ZNr();Object.defineProperty(DA,"SDK_INFO",{enumerable:!0,get:function(){return eU.SDK_INFO}});Object.defineProperty(DA,"_globalThis",{enumerable:!0,get:function(){return eU._globalThis}});Object.defineProperty(DA,"otperformance",{enumerable:!0,get:function(){return eU.otperformance}});Object.defineProperty(DA,"getBooleanFromEnv",{enumerable:!0,get:function(){return eU.getBooleanFromEnv}});Object.defineProperty(DA,"getStringFromEnv",{enumerable:!0,get:function(){return eU.getStringFromEnv}});Object.defineProperty(DA,"getNumberFromEnv",{enumerable:!0,get:function(){return eU.getNumberFromEnv}});Object.defineProperty(DA,"getStringListFromEnv",{enumerable:!0,get:function(){return eU.getStringListFromEnv}})});var nOr=T(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});xu.addHrTimes=xu.isTimeInput=xu.isTimeInputHrTime=xu.hrTimeToMicroseconds=xu.hrTimeToMilliseconds=xu.hrTimeToNanoseconds=xu.hrTimeToTimeStamp=xu.hrTimeDuration=xu.timeInputToHrTime=xu.hrTime=xu.getTimeOrigin=xu.millisToHrTime=void 0;var Yyt=zyt(),eOr=9,Nco=6,Oco=Math.pow(10,Nco),$Re=Math.pow(10,eOr);function Tpe(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Oco);return[r,n]}xu.millisToHrTime=Tpe;function Kyt(){let t=Yyt.otperformance.timeOrigin;if(typeof t!="number"){let e=Yyt.otperformance;t=e.timing&&e.timing.fetchStart}return t}xu.getTimeOrigin=Kyt;function tOr(t){let e=Tpe(Kyt()),r=Tpe(typeof t=="number"?t:Yyt.otperformance.now());return rOr(e,r)}xu.hrTime=tOr;function kco(t){if(Xyt(t))return t;if(typeof t=="number")return t<Kyt()?tOr(t):Tpe(t);if(t instanceof Date)return Tpe(t.getTime());throw TypeError("Invalid input type")}xu.timeInputToHrTime=kco;function Bco(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=$Re),[r,n]}xu.hrTimeDuration=Bco;function Pco(t){let e=eOr,r=`${"0".repeat(e)}${t[1]}Z`,n=r.substring(r.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",n)}xu.hrTimeToTimeStamp=Pco;function Mco(t){return t[0]*$Re+t[1]}xu.hrTimeToNanoseconds=Mco;function Fco(t){return t[0]*1e3+t[1]/1e6}xu.hrTimeToMilliseconds=Fco;function Lco(t){return t[0]*1e6+t[1]/1e3}xu.hrTimeToMicroseconds=Lco;function Xyt(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}xu.isTimeInputHrTime=Xyt;function Uco(t){return Xyt(t)||typeof t=="number"||t instanceof Date}xu.isTimeInput=Uco;function rOr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=$Re&&(r[1]-=$Re,r[0]+=1),r}xu.addHrTimes=rOr});var iOr=T(qRe=>{"use strict";Object.defineProperty(qRe,"__esModule",{value:!0});qRe.unrefTimer=void 0;function Qco(t){typeof t!="number"&&t.unref()}qRe.unrefTimer=Qco});var oOr=T(Ipe=>{"use strict";Object.defineProperty(Ipe,"__esModule",{value:!0});Ipe.ExportResultCode=void 0;var jco;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(jco=Ipe.ExportResultCode||(Ipe.ExportResultCode={}))});var aOr=T(HRe=>{"use strict";Object.defineProperty(HRe,"__esModule",{value:!0});HRe.CompositePropagator=void 0;var sOr=(Zt(),vt(ur)),Jyt=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){sOr.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){sOr.diag.warn(`Failed to extract with ${s.constructor.name}. Err: ${a.message}`)}return o},e)}fields(){return this._fields.slice()}};HRe.CompositePropagator=Jyt});var cOr=T(iX=>{"use strict";Object.defineProperty(iX,"__esModule",{value:!0});iX.validateValue=iX.validateKey=void 0;var Zyt="[_0-9a-z-*/]",Gco=`[a-z]${Zyt}{0,255}`,$co=`[a-z0-9]${Zyt}{0,240}@[a-z]${Zyt}{0,13}`,qco=new RegExp(`^(?:${Gco}|${$co})$`),Hco=/^[ -~]{0,255}[!-~]$/,Vco=/,|=/;function Wco(t){return qco.test(t)}iX.validateKey=Wco;function zco(t){return Hco.test(t)&&!Vco.test(t)}iX.validateValue=zco});var t_t=T(VRe=>{"use strict";Object.defineProperty(VRe,"__esModule",{value:!0});VRe.TraceState=void 0;var lOr=cOr(),uOr=32,Yco=512,dOr=",",fOr="=",e_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+fOr+this.get(r)),e),[]).join(dOr)}_parse(e){e.length>Yco||(this._internalState=e.split(dOr).reverse().reduce((r,n)=>{let o=n.trim(),s=o.indexOf(fOr);if(s!==-1){let a=o.slice(0,s),c=o.slice(s+1,n.length);(0,lOr.validateKey)(a)&&(0,lOr.validateValue)(c)&&r.set(a,c)}return r},new Map),this._internalState.size>uOr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,uOr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};VRe.TraceState=e_t});var hOr=T(RA=>{"use strict";Object.defineProperty(RA,"__esModule",{value:!0});RA.W3CTraceContextPropagator=RA.parseTraceParent=RA.TRACE_STATE_HEADER=RA.TRACE_PARENT_HEADER=void 0;var WRe=(Zt(),vt(ur)),Kco=wpe(),Xco=t_t();RA.TRACE_PARENT_HEADER="traceparent";RA.TRACE_STATE_HEADER="tracestate";var Jco="00",Zco="(?!ff)[\\da-f]{2}",elo="(?![0]{32})[\\da-f]{32}",tlo="(?![0]{16})[\\da-f]{16}",rlo="[\\da-f]{2}",nlo=new RegExp(`^\\s?(${Zco})-(${elo})-(${tlo})-(${rlo})(-.*)?\\s?$`);function pOr(t){let e=nlo.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}RA.parseTraceParent=pOr;var r_t=class{inject(e,r,n){let o=WRe.trace.getSpanContext(e);if(!o||(0,Kco.isTracingSuppressed)(e)||!(0,WRe.isSpanContextValid)(o))return;let s=`${Jco}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||WRe.TraceFlags.NONE).toString(16)}`;n.set(r,RA.TRACE_PARENT_HEADER,s),o.traceState&&n.set(r,RA.TRACE_STATE_HEADER,o.traceState.serialize())}extract(e,r,n){let o=n.get(r,RA.TRACE_PARENT_HEADER);if(!o)return e;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let a=pOr(s);if(!a)return e;a.isRemote=!0;let c=n.get(r,RA.TRACE_STATE_HEADER);if(c){let u=Array.isArray(c)?c.join(","):c;a.traceState=new Xco.TraceState(typeof u=="string"?u:void 0)}return WRe.trace.setSpanContext(e,a)}fields(){return[RA.TRACE_PARENT_HEADER,RA.TRACE_STATE_HEADER]}};RA.W3CTraceContextPropagator=r_t});var mOr=T(fC=>{"use strict";Object.defineProperty(fC,"__esModule",{value:!0});fC.getRPCMetadata=fC.deleteRPCMetadata=fC.setRPCMetadata=fC.RPCType=void 0;var ilo=(Zt(),vt(ur)),n_t=(0,ilo.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),olo;(function(t){t.HTTP="http"})(olo=fC.RPCType||(fC.RPCType={}));function slo(t,e){return t.setValue(n_t,e)}fC.setRPCMetadata=slo;function alo(t){return t.deleteValue(n_t)}fC.deleteRPCMetadata=alo;function clo(t){return t.getValue(n_t)}fC.getRPCMetadata=clo});var EOr=T(zRe=>{"use strict";Object.defineProperty(zRe,"__esModule",{value:!0});zRe.isPlainObject=void 0;var llo="[object Object]",ulo="[object Null]",dlo="[object Undefined]",flo=Function.prototype,gOr=flo.toString,plo=gOr.call(Object),hlo=Object.getPrototypeOf,AOr=Object.prototype,yOr=AOr.hasOwnProperty,tU=Symbol?Symbol.toStringTag:void 0,_Or=AOr.toString;function mlo(t){if(!glo(t)||Alo(t)!==llo)return!1;let e=hlo(t);if(e===null)return!0;let r=yOr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&gOr.call(r)===plo}zRe.isPlainObject=mlo;function glo(t){return t!=null&&typeof t=="object"}function Alo(t){return t==null?t===void 0?dlo:ulo:tU&&tU in Object(t)?ylo(t):_lo(t)}function ylo(t){let e=yOr.call(t,tU),r=t[tU],n=!1;try{t[tU]=void 0,n=!0}catch{}let o=_Or.call(t);return n&&(e?t[tU]=r:delete t[tU]),o}function _lo(t){return _Or.call(t)}});var xOr=T(XRe=>{"use strict";Object.defineProperty(XRe,"__esModule",{value:!0});XRe.merge=void 0;var vOr=EOr(),Elo=20;function vlo(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=COr(e,t.shift(),0,r);return e}XRe.merge=vlo;function i_t(t){return KRe(t)?t.slice():t}function COr(t,e,r=0,n){let o;if(!(r>Elo)){if(r++,YRe(t)||YRe(e)||SOr(e))o=i_t(e);else if(KRe(t)){if(o=t.slice(),KRe(e))for(let s=0,a=e.length;s<a;s++)o.push(i_t(e[s]));else if(Dpe(e)){let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a];o[u]=i_t(e[u])}}}else if(Dpe(t))if(Dpe(e)){if(!blo(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(YRe(d))typeof d>"u"?delete o[u]:o[u]=d;else{let f=o[u],p=d;if(bOr(t,u,n)||bOr(e,u,n))delete o[u];else{if(Dpe(f)&&Dpe(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]=COr(o[u],d,r,n)}}}}else o=e;return o}}function bOr(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 KRe(t){return Array.isArray(t)}function SOr(t){return typeof t=="function"}function Dpe(t){return!YRe(t)&&!KRe(t)&&!SOr(t)&&typeof t=="object"}function YRe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function blo(t,e){return!(!(0,vOr.isPlainObject)(t)||!(0,vOr.isPlainObject)(e))}});var wOr=T(oX=>{"use strict";Object.defineProperty(oX,"__esModule",{value:!0});oX.callWithTimeout=oX.TimeoutError=void 0;var JRe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};oX.TimeoutError=JRe;function Clo(t,e){let r,n=new Promise(function(s,a){r=setTimeout(function(){a(new JRe("Operation timed out."))},e)});return Promise.race([t,n]).then(o=>(clearTimeout(r),o),o=>{throw clearTimeout(r),o})}oX.callWithTimeout=Clo});var IOr=T(sX=>{"use strict";Object.defineProperty(sX,"__esModule",{value:!0});sX.isUrlIgnored=sX.urlMatches=void 0;function TOr(t,e){return typeof e=="string"?t===e:!!t.match(e)}sX.urlMatches=TOr;function Slo(t,e){if(!e)return!1;for(let r of e)if(TOr(t,r))return!0;return!1}sX.isUrlIgnored=Slo});var DOr=T(ZRe=>{"use strict";Object.defineProperty(ZRe,"__esModule",{value:!0});ZRe.Deferred=void 0;var o_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)}};ZRe.Deferred=o_t});var ROr=T(eNe=>{"use strict";Object.defineProperty(eNe,"__esModule",{value:!0});eNe.BindOnceFuture=void 0;var xlo=DOr(),s_t=class{_callback;_that;_isCalled=!1;_deferred=new xlo.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}};eNe.BindOnceFuture=s_t});var OOr=T(tNe=>{"use strict";Object.defineProperty(tNe,"__esModule",{value:!0});tNe.diagLogLevelFromString=void 0;var N9=(Zt(),vt(ur)),NOr={ALL:N9.DiagLogLevel.ALL,VERBOSE:N9.DiagLogLevel.VERBOSE,DEBUG:N9.DiagLogLevel.DEBUG,INFO:N9.DiagLogLevel.INFO,WARN:N9.DiagLogLevel.WARN,ERROR:N9.DiagLogLevel.ERROR,NONE:N9.DiagLogLevel.NONE};function wlo(t){if(t==null)return;let e=NOr[t.toUpperCase()];return e??(N9.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys(NOr)}, using default`),N9.DiagLogLevel.INFO)}tNe.diagLogLevelFromString=wlo});var BOr=T(rNe=>{"use strict";Object.defineProperty(rNe,"__esModule",{value:!0});rNe._export=void 0;var kOr=(Zt(),vt(ur)),Tlo=wpe();function Ilo(t,e){return new Promise(r=>{kOr.context.with((0,Tlo.suppressTracing)(kOr.context.active()),()=>{t.export(e,n=>{r(n)})})})}rNe._export=Ilo});var O9=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 Dlo=PNr();Object.defineProperty(jr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return Dlo.W3CBaggagePropagator}});var Rlo=MNr();Object.defineProperty(jr,"AnchoredClock",{enumerable:!0,get:function(){return Rlo.AnchoredClock}});var POr=jNr();Object.defineProperty(jr,"isAttributeValue",{enumerable:!0,get:function(){return POr.isAttributeValue}});Object.defineProperty(jr,"sanitizeAttributes",{enumerable:!0,get:function(){return POr.sanitizeAttributes}});var MOr=$Nr();Object.defineProperty(jr,"globalErrorHandler",{enumerable:!0,get:function(){return MOr.globalErrorHandler}});Object.defineProperty(jr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return MOr.setGlobalErrorHandler}});var Nlo=Wyt();Object.defineProperty(jr,"loggingErrorHandler",{enumerable:!0,get:function(){return Nlo.loggingErrorHandler}});var rv=nOr();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 Olo=iOr();Object.defineProperty(jr,"unrefTimer",{enumerable:!0,get:function(){return Olo.unrefTimer}});var klo=oOr();Object.defineProperty(jr,"ExportResultCode",{enumerable:!0,get:function(){return klo.ExportResultCode}});var Blo=Gyt();Object.defineProperty(jr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return Blo.parseKeyPairsIntoRecord}});var rU=zyt();Object.defineProperty(jr,"SDK_INFO",{enumerable:!0,get:function(){return rU.SDK_INFO}});Object.defineProperty(jr,"_globalThis",{enumerable:!0,get:function(){return rU._globalThis}});Object.defineProperty(jr,"getStringFromEnv",{enumerable:!0,get:function(){return rU.getStringFromEnv}});Object.defineProperty(jr,"getBooleanFromEnv",{enumerable:!0,get:function(){return rU.getBooleanFromEnv}});Object.defineProperty(jr,"getNumberFromEnv",{enumerable:!0,get:function(){return rU.getNumberFromEnv}});Object.defineProperty(jr,"getStringListFromEnv",{enumerable:!0,get:function(){return rU.getStringListFromEnv}});Object.defineProperty(jr,"otperformance",{enumerable:!0,get:function(){return rU.otperformance}});var Plo=aOr();Object.defineProperty(jr,"CompositePropagator",{enumerable:!0,get:function(){return Plo.CompositePropagator}});var nNe=hOr();Object.defineProperty(jr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return nNe.TRACE_PARENT_HEADER}});Object.defineProperty(jr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return nNe.TRACE_STATE_HEADER}});Object.defineProperty(jr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return nNe.W3CTraceContextPropagator}});Object.defineProperty(jr,"parseTraceParent",{enumerable:!0,get:function(){return nNe.parseTraceParent}});var iNe=mOr();Object.defineProperty(jr,"RPCType",{enumerable:!0,get:function(){return iNe.RPCType}});Object.defineProperty(jr,"deleteRPCMetadata",{enumerable:!0,get:function(){return iNe.deleteRPCMetadata}});Object.defineProperty(jr,"getRPCMetadata",{enumerable:!0,get:function(){return iNe.getRPCMetadata}});Object.defineProperty(jr,"setRPCMetadata",{enumerable:!0,get:function(){return iNe.setRPCMetadata}});var a_t=wpe();Object.defineProperty(jr,"isTracingSuppressed",{enumerable:!0,get:function(){return a_t.isTracingSuppressed}});Object.defineProperty(jr,"suppressTracing",{enumerable:!0,get:function(){return a_t.suppressTracing}});Object.defineProperty(jr,"unsuppressTracing",{enumerable:!0,get:function(){return a_t.unsuppressTracing}});var Mlo=t_t();Object.defineProperty(jr,"TraceState",{enumerable:!0,get:function(){return Mlo.TraceState}});var Flo=xOr();Object.defineProperty(jr,"merge",{enumerable:!0,get:function(){return Flo.merge}});var FOr=wOr();Object.defineProperty(jr,"TimeoutError",{enumerable:!0,get:function(){return FOr.TimeoutError}});Object.defineProperty(jr,"callWithTimeout",{enumerable:!0,get:function(){return FOr.callWithTimeout}});var LOr=IOr();Object.defineProperty(jr,"isUrlIgnored",{enumerable:!0,get:function(){return LOr.isUrlIgnored}});Object.defineProperty(jr,"urlMatches",{enumerable:!0,get:function(){return LOr.urlMatches}});var Llo=ROr();Object.defineProperty(jr,"BindOnceFuture",{enumerable:!0,get:function(){return Llo.BindOnceFuture}});var Ulo=OOr();Object.defineProperty(jr,"diagLogLevelFromString",{enumerable:!0,get:function(){return Ulo.diagLogLevelFromString}});var Qlo=BOr();jr.internal={_export:Qlo._export}});var UOr=T(sNe=>{"use strict";Object.defineProperty(sNe,"__esModule",{value:!0});sNe.LogRecordImpl=void 0;var nU=(Zt(),vt(ur)),oNe=O9(),c_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,oNe.timeInputToHrTime)(o??h),this.hrTimeObserved=(0,oNe.timeInputToHrTime)(s??h),p){let m=nU.trace.getSpanContext(p);m&&nU.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?(nU.diag.warn(`Invalid attribute key: ${e}`),this):!(0,oNe.isAttributeValue)(r)&&!(typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length>0)?(nU.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&&nU.diag.warn("Dropping extra attributes."),this):((0,oNe.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?(nU.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&&nU.diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}};sNe.LogRecordImpl=c_t});var QOr=T(aNe=>{"use strict";Object.defineProperty(aNe,"__esModule",{value:!0});aNe.Logger=void 0;var jlo=(Zt(),vt(ur)),Glo=UOr(),l_t=class{instrumentationScope;_sharedState;constructor(e,r){this.instrumentationScope=e,this._sharedState=r}emit(e){let r=e.context||jlo.context.active(),n=new Glo.LogRecordImpl(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(n,r),n._makeReadonly()}};aNe.Logger=l_t});var jOr=T(cX=>{"use strict";Object.defineProperty(cX,"__esModule",{value:!0});cX.reconfigureLimits=cX.loadDefaultConfig=void 0;var aX=O9();function $lo(){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=$lo;function qlo(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=qlo});var d_t=T(cNe=>{"use strict";Object.defineProperty(cNe,"__esModule",{value:!0});cNe.NoopLogRecordProcessor=void 0;var u_t=class{forceFlush(){return Promise.resolve()}onEmit(e,r){}shutdown(){return Promise.resolve()}};cNe.NoopLogRecordProcessor=u_t});var GOr=T(lNe=>{"use strict";Object.defineProperty(lNe,"__esModule",{value:!0});lNe.MultiLogRecordProcessor=void 0;var Hlo=O9(),f_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,Hlo.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()))}};lNe.MultiLogRecordProcessor=f_t});var $Or=T(uNe=>{"use strict";Object.defineProperty(uNe,"__esModule",{value:!0});uNe.LoggerProviderSharedState=void 0;var Vlo=d_t(),Wlo=GOr(),p_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 Wlo.MultiLogRecordProcessor(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new Vlo.NoopLogRecordProcessor}};uNe.LoggerProviderSharedState=p_t});var VOr=T(iU=>{"use strict";Object.defineProperty(iU,"__esModule",{value:!0});iU.LoggerProvider=iU.DEFAULT_LOGGER_NAME=void 0;var dNe=(Zt(),vt(ur)),zlo=kNr(),Ylo=Byt(),qOr=O9(),Klo=QOr(),HOr=jOr(),Xlo=$Or();iU.DEFAULT_LOGGER_NAME="unknown";var h_t=class{_shutdownOnce;_sharedState;constructor(e={}){let r=(0,qOr.merge)({},(0,HOr.loadDefaultConfig)(),e),n=e.resource??(0,Ylo.defaultResource)();this._sharedState=new Xlo.LoggerProviderSharedState(n,r.forceFlushTimeoutMillis,(0,HOr.reconfigureLimits)(r.logRecordLimits),e?.processors??[]),this._shutdownOnce=new qOr.BindOnceFuture(this._shutdown,this)}getLogger(e,r,n){if(this._shutdownOnce.isCalled)return dNe.diag.warn("A shutdown LoggerProvider cannot provide a Logger"),zlo.NOOP_LOGGER;e||dNe.diag.warn("Logger requested without instrumentation scope name.");let o=e||iU.DEFAULT_LOGGER_NAME,s=`${o}@${r||""}:${n?.schemaUrl||""}`;return this._sharedState.loggers.has(s)||this._sharedState.loggers.set(s,new Klo.Logger({name:o,version:r,schemaUrl:n?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(s)}forceFlush(){return this._shutdownOnce.isCalled?(dNe.diag.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(dNe.diag.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}};iU.LoggerProvider=h_t});var zOr=T(fNe=>{"use strict";Object.defineProperty(fNe,"__esModule",{value:!0});fNe.ConsoleLogRecordExporter=void 0;var WOr=O9(),m_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,WOr.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:WOr.ExportResultCode.SUCCESS})}};fNe.ConsoleLogRecordExporter=m_t});var YOr=T(pNe=>{"use strict";Object.defineProperty(pNe,"__esModule",{value:!0});pNe.SimpleLogRecordProcessor=void 0;var lX=O9(),g_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()}};pNe.SimpleLogRecordProcessor=g_t});var XOr=T(hNe=>{"use strict";Object.defineProperty(hNe,"__esModule",{value:!0});hNe.InMemoryLogRecordExporter=void 0;var KOr=O9(),A_t=class{_finishedLogRecords=[];_stopped=!1;export(e,r){if(this._stopped)return r({code:KOr.ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),r({code:KOr.ExportResultCode.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}};hNe.InMemoryLogRecordExporter=A_t});var JOr=T(mNe=>{"use strict";Object.defineProperty(mNe,"__esModule",{value:!0});mNe.BatchLogRecordProcessorBase=void 0;var Jlo=(Zt(),vt(ur)),nv=O9(),y_t=class{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,r){this._exporter=e,this._maxExportBatchSize=r?.maxExportBatchSize??(0,nv.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=r?.maxQueueSize??(0,nv.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=r?.scheduledDelayMillis??(0,nv.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY")??5e3,this._exportTimeoutMillis=r?.exportTimeoutMillis??(0,nv.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT")??3e4,this._shutdownOnce=new nv.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(Jlo.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,nv.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,nv.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=()=>nv.internal._export(this._exporter,e).then(o=>{o.code!==nv.ExportResultCode.SUCCESS&&(0,nv.globalErrorHandler)(o.error??new Error(`BatchLogRecordProcessor: log record export failed (status ${o})`))}).catch(nv.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,nv.globalErrorHandler)}};mNe.BatchLogRecordProcessorBase=y_t});var ZOr=T(gNe=>{"use strict";Object.defineProperty(gNe,"__esModule",{value:!0});gNe.BatchLogRecordProcessor=void 0;var Zlo=JOr(),__t=class extends Zlo.BatchLogRecordProcessorBase{onShutdown(){}};gNe.BatchLogRecordProcessor=__t});var ekr=T(ANe=>{"use strict";Object.defineProperty(ANe,"__esModule",{value:!0});ANe.BatchLogRecordProcessor=void 0;var euo=ZOr();Object.defineProperty(ANe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return euo.BatchLogRecordProcessor}})});var tkr=T(yNe=>{"use strict";Object.defineProperty(yNe,"__esModule",{value:!0});yNe.BatchLogRecordProcessor=void 0;var tuo=ekr();Object.defineProperty(yNe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return tuo.BatchLogRecordProcessor}})});var rkr=T(F3=>{"use strict";Object.defineProperty(F3,"__esModule",{value:!0});F3.BatchLogRecordProcessor=F3.InMemoryLogRecordExporter=F3.SimpleLogRecordProcessor=F3.ConsoleLogRecordExporter=F3.NoopLogRecordProcessor=F3.LoggerProvider=void 0;var ruo=VOr();Object.defineProperty(F3,"LoggerProvider",{enumerable:!0,get:function(){return ruo.LoggerProvider}});var nuo=d_t();Object.defineProperty(F3,"NoopLogRecordProcessor",{enumerable:!0,get:function(){return nuo.NoopLogRecordProcessor}});var iuo=zOr();Object.defineProperty(F3,"ConsoleLogRecordExporter",{enumerable:!0,get:function(){return iuo.ConsoleLogRecordExporter}});var ouo=YOr();Object.defineProperty(F3,"SimpleLogRecordProcessor",{enumerable:!0,get:function(){return ouo.SimpleLogRecordProcessor}});var suo=XOr();Object.defineProperty(F3,"InMemoryLogRecordExporter",{enumerable:!0,get:function(){return suo.InMemoryLogRecordExporter}});var auo=tkr();Object.defineProperty(F3,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return auo.BatchLogRecordProcessor}})});var Vh,nkr,Rpe,ikr,Npe,Ope,okr,skr,akr,ckr,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,kpe=te(()=>{"use strict";Vh="iflow-cli",nkr="iflow_cli.user_prompt",Rpe="iflow_cli.tool_call",ikr="iflow_cli.api_request",Npe="iflow_cli.api_error",Ope="iflow_cli.api_response",okr="iflow_cli.config",skr="iflow_cli.flash_fallback",akr="iflow_cli.next_speaker_check",ckr="iflow_cli.slash_command",lkr="iflow_cli.cli_response",ukr="iflow_cli.tool.call.count",dkr="iflow_cli.tool.call.latency",fkr="iflow_cli.mcp.tool.call.count",pkr="iflow_cli.mcp.tool.call.latency",hkr="iflow_cli.builtin.tool.call.count",mkr="iflow_cli.builtin.tool.call.latency",gkr="gen_ai.client.operation",Akr="gen_ai.client.operation.duration",ykr="gen_ai.client.token.usage",_kr="iflow_cli.session.count",Ekr="iflow_cli.file.operation.count",vkr="iflow_cli.user_request.count",bkr="iflow_cli.user_request.latency",Ckr="iflow_cli.user_experience.success",Skr="iflow_cli.user.identity",xkr="iflow_cli.scheduler.lock.error",wkr="iflow_cli.mcp.connect.count",Tkr="iflow_cli.loop.detection.count",Ikr="iflow_cli.paste.operation.count",Dkr="iflow_cli.paste.operation.latency",Rkr="iflow_cli.xinliu.web.search.count",Nkr="iflow_cli.xinliu.web.search.latency",Okr="iflow_cli.web.fetch.count",kkr="iflow_cli.web.fetch.latency"});import cuo from"os";function Bkr(){try{let t=cuo.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 Pkr=te(()=>{"use strict"});var uX,dX,fX,pX,hX,mX,gX,AX,yX,_X,pC,hC,Mkr=te(()=>{"use strict";uX="iflow_cli.cpu.usage_percentage",dX="iflow_cli.cpu.user_percentage",fX="iflow_cli.cpu.system_percentage",pX="iflow_cli.cpu.cores",hX="iflow_cli.memory.heap_used",mX="iflow_cli.memory.heap_total",gX="iflow_cli.memory.rss",AX="iflow_cli.memory.external",yX="iflow_cli.memory.system_usage_percentage",_X="iflow_cli.memory.process_usage_percentage",pC={[uX]:"CPU usage percentage",[dX]:"CPU user time percentage",[fX]:"CPU system time percentage",[pX]:"Number of CPU cores",[hX]:"Heap memory used in bytes",[mX]:"Heap memory total in bytes",[gX]:"Resident Set Size in bytes",[AX]:"External memory in bytes",[yX]:"System memory usage percentage",[_X]:"Process memory usage percentage relative to Node.js limits"},hC={[uX]:"percent",[dX]:"percent",[fX]:"percent",[pX]:"cores",[hX]:"bytes",[mX]:"bytes",[gX]:"bytes",[AX]:"bytes",[yX]:"percent",[_X]:"percent"}});import*as mC from"os";var _Ne,Fkr=te(()=>{"use strict";Mkr();_Ne=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=mC.cpus().length,this.totalSystemMemory=mC.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=mC.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=mC.platform(),r=mC.arch(),n=process.version;this.options.enableCpuMetrics&&(this.cpuUsageGauge=this.meter.createObservableGauge(uX,{description:pC[uX],unit:hC[uX]}),this.cpuUserGauge=this.meter.createObservableGauge(dX,{description:pC[dX],unit:hC[dX]}),this.cpuSystemGauge=this.meter.createObservableGauge(fX,{description:pC[fX],unit:hC[fX]}),this.cpuCoresGauge=this.meter.createObservableGauge(pX,{description:pC[pX],unit:hC[pX]}),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(hX,{description:pC[hX],unit:hC[hX]}),this.memoryHeapTotalGauge=this.meter.createObservableGauge(mX,{description:pC[mX],unit:hC[mX]}),this.memoryRssGauge=this.meter.createObservableGauge(gX,{description:pC[gX],unit:hC[gX]}),this.memoryExternalGauge=this.meter.createObservableGauge(AX,{description:pC[AX],unit:hC[AX]}),this.memorySystemUsageGauge=this.meter.createObservableGauge(yX,{description:pC[yX],unit:hC[yX]}),this.memoryProcessUsageGauge=this.meter.createObservableGauge(_X,{description:pC[_X],unit:hC[_X]}),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=mC.arch();return n==="x64"||n==="arm64"?1400*1024*1024:700*1024*1024}}});function Lkr(t,e={}){if(ENe)return ENe;let r={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...e};return ENe=new _Ne(t,r),ENe}var ENe,Ukr=te(()=>{"use strict";Fkr();ENe=null});import*as EX from"os";import*as vNe from"fs";function Fd(t){let e="0.3.29-beta.2",r=process.env.IFLOW_ENV||"normal",n={darwin:"macOS",win32:"Windows",linux:"Linux",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",aix:"AIX"},o=EX.platform(),s=n[o]||o,a="unknown";try{if(o==="darwin")a=EX.release();else if(o==="linux")try{if(vNe.existsSync("/etc/os-release")){let m=vNe.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="(.+)"/m);m&&(a=m[1])}}catch{a=EX.release()}else o==="win32"&&(a=EX.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:Vh,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:Bkr(),iflow_env:r,usage_mode:d}}function Qkr(){return E_t||(E_t=hde.getMeter(Vh)),E_t}function jkr(){if(Wh)return;let t=Qkr();if(t){try{Lkr(t,{enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0})}catch{}v_t=t.createHistogram(ukr,{description:"Counts tool calls, tagged by function name and success.",unit:"count",valueType:xc.INT}),b_t=t.createHistogram(dkr,{description:"Latency of tool calls in milliseconds.",unit:"ms",valueType:xc.INT}),C_t=t.createHistogram(fkr,{description:"Counts MCP tool calls, tagged by function name and success.",unit:"count",valueType:xc.INT}),S_t=t.createHistogram(pkr,{description:"Latency of MCP tool calls in milliseconds.",unit:"ms",valueType:xc.INT}),x_t=t.createHistogram(hkr,{description:"Counts built-in tool calls, tagged by function name and success.",unit:"count",valueType:xc.INT}),w_t=t.createHistogram(mkr,{description:"Latency of built-in tool calls in milliseconds.",unit:"ms",valueType:xc.INT}),Bpe=t.createHistogram(gkr,{description:"Counts API requests, tagged by model and status.",unit:"count",valueType:xc.INT}),Ppe=t.createHistogram(Akr,{description:"Latency of API requests in milliseconds.",unit:"ms",valueType:xc.INT}),T_t=t.createHistogram(ykr,{description:"Counts the total number of tokens used.",unit:"tokens",valueType:xc.INT}),I_t=t.createHistogram(Ekr,{description:"Counts file operations (create, read, update).",unit:"count",valueType:xc.INT}),D_t=t.createHistogram(vkr,{description:"Counts user requests from prompt to completion.",unit:"count",valueType:xc.INT}),R_t=t.createHistogram(bkr,{description:"End-to-end latency of user requests in milliseconds.",unit:"ms",valueType:xc.INT}),N_t=t.createHistogram(Ckr,{description:"User experience success rate - counts successful user experiences including retries and fixes.",unit:"count",valueType:xc.INT}),O_t=t.createHistogram(Skr,{description:"User identity for tracking unique installations.",unit:"count",valueType:xc.INT}),k_t=t.createHistogram(xkr,{description:"Counts tool scheduler lock errors when new calls are blocked by running calls.",unit:"count",valueType:xc.INT}),B_t=t.createHistogram(wkr,{description:"Counts MCP connection attempts and their success/failure status.",unit:"count",valueType:xc.INT}),P_t=t.createHistogram(Tkr,{description:"Counts loop detection events by loop type.",unit:"count",valueType:xc.INT}),M_t=t.createHistogram(Ikr,{description:"Counts paste operations, tagged by type and success.",unit:"count",valueType:xc.INT}),F_t=t.createHistogram(Dkr,{description:"Latency of paste operations in milliseconds.",unit:"ms",valueType:xc.INT}),L_t=t.createHistogram(Rkr,{description:"Counts xinliu web search operations, tagged by success and error type.",unit:"count",valueType:xc.INT}),U_t=t.createHistogram(Nkr,{description:"Latency of xinliu web search operations in milliseconds.",unit:"ms",valueType:xc.INT}),Q_t=t.createHistogram(Okr,{description:"Counts web fetch operations, tagged by success and error type.",unit:"count",valueType:xc.INT}),j_t=t.createHistogram(kkr,{description:"Latency of web fetch operations in milliseconds.",unit:"ms",valueType:xc.INT}),Wh=!0}}function bNe(t){let e=Qkr();if(!e||!Wh)return;e.createHistogram(_kr,{description:"Count of CLI sessions started.",unit:"count",valueType:xc.INT}).record(1,Fd(t))}function Gkr(t,e,r,n,o,s){if(!v_t||!b_t||!Wh)return;let a={...Fd(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};v_t.record(1,a),b_t.record(r,{...Fd(t),function_name:e??"unknown",tool_type:s??"unknown"})}function $kr(t,e,r,n,o,s){if(!C_t||!S_t||!Wh)return;let a={...Fd(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};s&&(a.execution_context=s),C_t.record(1,a),S_t.record(r,{...Fd(t),function_name:e??"unknown",execution_context:s??"unknown"})}function qkr(t,e,r,n,o,s){if(!x_t||!w_t||!Wh)return;let a={...Fd(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};s&&(a.execution_context=s),x_t.record(1,a),w_t.record(r,{...Fd(t),function_name:e??"unknown",execution_context:s??"unknown"})}function vX(t,e,r,n){!T_t||!Wh||T_t.record(r,{...Fd(t),model:e??"unknown",type:n??"unknown"})}function Hkr(t,e,r,n,o,s,a,c){if(!Bpe||!Ppe||!Wh)return;let u={...Fd(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),Bpe.record(1,u);let d={...Fd(t),model:e??"unknown",http_status_code:String(a??200),finish_reason:s??"unknown"};c!=null&&(d.business_code=String(c)),Ppe.record(r,d)}function Vkr(t,e,r,n,o,s,a){if(!Bpe||!Ppe||!Wh)return;let c={...Fd(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)),Bpe.record(1,c);let u={...Fd(t),model:e??"unknown",http_status_code:String(s??0),error:o??"unknown"};a!=null&&(u.business_code=String(a)),Ppe.record(r,u)}function oU(t,e,r,n,o){if(!I_t||!Wh)return;let s={...Fd(t),operation:e};r!==void 0&&(s.lines=String(r)),n!==void 0&&(s.mimetype=n),o!==void 0&&(s.extension=o),I_t.record(1,s)}function Wkr(t,e,r,n,o){if(!D_t||!R_t||!Wh)return;let s={...Fd(t),prompt_id:e,success:String(n)};o&&(s.error=o),D_t.record(1,s),R_t.record(r,s)}function G_t(t,e,r=!1,n=!1,o){if(!N_t||!Wh)return;let s={...Fd(t),success:String(e),had_retries:String(r),had_fixes:String(n)};o&&(s.final_error=o),N_t.record(1,s)}function zkr(t,e){if(!O_t||!Wh)return;let r={...Fd(t),user_id:e};O_t.record(1,r)}function Ykr(t,e,r){if(!k_t||!Wh)return;let n={...Fd(t),running_calls_count:String(e)};r.forEach((o,s)=>{n[`call_${s}_name`]=o.name,n[`call_${s}_status`]=o.status}),k_t.record(1,n)}function $_t(t,e,r,n,o){if(!B_t||!Wh)return;let s={...Fd(t),server_name:e,success:String(r)};n&&(s.error_type=n),o&&(s.transport_type=o),B_t.record(1,s)}function Kkr(t,e,r){if(!P_t||!Wh)return;let n={...Fd(t),loop_type:e,prompt_id:r};P_t.record(1,n)}function CNe(t,e,r,n,o="text",s,a){if(!M_t||!F_t||!Wh)return;let c={};try{c=Fd(t)}catch{c={app_name:Vh,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),M_t.record(1,u);let d={...c,paste_type:o,text_length_range:String(r),performance_ratio:luo(e,r)};F_t.record(e,d)}function luo(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 SNe(t,e,r,n,o,s){if(!L_t||!U_t||!Wh)return;let a={...Fd(t),success:String(r)};n&&(a.error_type=n),o!==void 0&&(a.results_count=String(o)),s&&(a.query_length=String(s.length)),L_t.record(1,a),U_t.record(e,{...Fd(t),error_type:n??"none"})}function sU(t,e,r,n,o,s){if(!Q_t||!j_t||!Wh)return;let a={...Fd(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)),Q_t.record(1,a),j_t.record(e,{...Fd(t),error_type:n??"none"})}var k9,E_t,v_t,b_t,C_t,S_t,x_t,w_t,Bpe,Ppe,T_t,I_t,D_t,R_t,N_t,O_t,k_t,B_t,P_t,M_t,F_t,L_t,U_t,Q_t,j_t,Wh,L3=te(()=>{"use strict";Zt();Pkr();kpe();g_();Ukr();(function(t){t.CREATE="create",t.READ="read",t.UPDATE="update"})(k9||(k9={}));Wh=!1});var Oo,vn,ko,Bo,Ld=te(()=>{"use strict";Oo=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"})(vn||(vn={}));(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"})(ko||(ko={}));(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"})(Bo||(Bo={}))});function uuo(t){switch(t){case vn.ProceedOnce:case vn.ProceedAlways:case vn.ProceedAlwaysServer:case vn.ProceedAlwaysTool:return iv.ACCEPT;case vn.ModifyWithEditor:return iv.MODIFY;case vn.Cancel:default:return iv.REJECT}}var iv,bX,CX,SX,xX,wX,NA,TX,IX,ov,DX,xNe,RX,wNe,NN=te(()=>{"use strict";Ld();g_();(function(t){t.ACCEPT="accept",t.REJECT="reject",t.MODIFY="modify"})(iv||(iv={}));bX=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()}},CX=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()}},SX=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}},xX=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?uuo(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)}},wX=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}},NA=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}},TX=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}},IX=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"})(ov||(ov={}));DX=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}},xNe=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}},RX=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}},wNe=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,Xkr=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 aU(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 TNe=te(()=>{"use strict";});import Bx,{dirname as duo,join as q_t}from"node:path";import INe from"os";import*as Jkr from"crypto";import{fileURLToPath as fuo}from"node:url";import puo from"node:fs";import{execSync as huo}from"node:child_process";function Px(t){let e=INe.homedir();return t.startsWith(e)?t.replace(e,"~"):t}function wc(t,e=35){if(t.length<=e)return t;let n=Bx.parse(t).root,o=Bx.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 Ud(t,e){let r=Bx.resolve(t),n=Bx.resolve(e);return Bx.relative(n,r)||"."}function NX(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 B9(t){return process.platform==="win32"?t.replace(/\\([ ,;!?()[\]{}])/g,"$1"):t.replace(/\\(.)/g,"$1")}function DNe(t){return Jkr.createHash("sha256").update(t).digest("hex")}function o1(t){let e=DNe(t);return Bx.join(INe.homedir(),Xm,muo,e)}function RNe(){return Bx.join(INe.homedir(),Xm,Zkr)}function NNe(t){return Bx.join(t,Xm,Zkr)}function ONe(){if(process.env.USE_BUILTIN_RIPGREP==="0")return"rg";let t=duo(fuo(import.meta.url)),e=[q_t(t,"..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),q_t(t,"..","..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),q_t(t,"..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`)];for(let r of e)try{if(puo.existsSync(r))return process.platform==="darwin"&&eBr(r),r}catch{}return e[0]}function eBr(t){if(process.platform==="darwin")try{let e=["com.apple.quarantine","CachedFileMimeType","CachedFileType","FileXRayCachedResultInEA"];for(let r of e)try{huo(`xattr -d "${r}" "${t}" 2>/dev/null`,{stdio:"ignore"})}catch{}}catch{}}function Mpe(t,e){let n=INe.platform()==="win32"?Bx.win32:Bx,o=n.relative(t,e);return!o.startsWith(`..${n.sep}`)&&o!==".."&&!n.isAbsolute(o)}var Xm,H_t,muo,Zkr,Qd=te(()=>{"use strict";Xm=".iflow",H_t="google_accounts.json",muo="tmp",Zkr="commands"});import guo from"node:path";import{promises as jLa,existsSync as tBr,readFileSync as rBr}from"node:fs";import*as nBr from"os";function iBr(){return guo.join(nBr.homedir(),Xm,H_t)}function oBr(){try{let t=iBr();if(tBr(t)){let e=rBr(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 sBr(){try{let t=iBr();if(!tBr(t))return 0;let e=rBr(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 aBr=te(()=>{"use strict";Qd();});import*as cBr from"os";import*as P9 from"fs";import*as z_t from"path";import{randomUUID as Auo}from"crypto";function _uo(){P9.existsSync(V_t)||P9.mkdirSync(V_t,{recursive:!0})}function Euo(){return P9.existsSync(W_t)&&P9.readFileSync(W_t,"utf-8").trim()||null}function vuo(t){P9.writeFileSync(W_t,t,"utf-8")}function kNe(){try{_uo();let t=Euo();return t||(t=Auo(),vuo(t)),t}catch(t){return console.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}var yuo,V_t,W_t,Y_t=te(()=>{"use strict";Qd();yuo=cBr.homedir()??"",V_t=z_t.join(yuo,Xm),W_t=z_t.join(V_t,"installation_id")});var lBr,buo,Cuo,Suo,xuo,wuo,Tuo,Iuo,Duo,Ruo,Nuo,Ouo,kuo,Buo,zh,Fpe=te(()=>{"use strict";lBr=Te(Clt(),1);NN();Xkr();TNe();aBr();Y_t();buo="start_session",Cuo="new_prompt",Suo="tool_call",xuo="api_request",wuo="api_response",Tuo="api_error",Iuo="end_session",Duo="flash_fallback",Ruo="loop_detected",Nuo="next_speaker_check",Ouo="slash_command",kuo="malformed_json_response",Buo="cli_response",zh=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:aU(e)}])}createLogEvent(e,r){let n=oBr(),o=sBr();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=kNe(),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(buo,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(Cuo,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(Suo,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(xuo,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(wuo,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(Tuo,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(Duo,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(Ruo,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(Nuo,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(Ouo,r)}logMalformedJsonResponseEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.handleLogEvent(kuo,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(Buo,r)}logEndSessionEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:e?.session_id?.toString()??""}];this.handleLogEvent(Iuo,r,!0)}getProxyAgent(){let e=this.config?.getProxy();if(e){if(e.startsWith("http"))return new lBr.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}shutdown(){let e=new CX(this.config);this.logEndSessionEvent(e)}}});import*as uBr from"node:fs";var cU,dBr,Lpe,BNe,PNe,MNe,fBr=te(()=>{"use strict";cU=Te(fi(),1),dBr=Te(zS(),1);Lpe=class{writeStream;constructor(e){this.writeStream=uBr.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
+ `).find(n=>n.includes("IOPlatformUUID"));if(!e)return;let r=e.split('" = "');if(r.length===2)return r[1].slice(0,-1)}catch(t){fao.diag.debug(`error reading machine id: ${t}`)}}uRe.getMachineId=pao});var sNr=T(dRe=>{"use strict";Object.defineProperty(dRe,"__esModule",{value:!0});dRe.getMachineId=void 0;var hao=ye("fs"),mao=(Zt(),vt(ur));async function gao(){let t=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let e of t)try{return(await hao.promises.readFile(e,{encoding:"utf8"})).trim()}catch(r){mao.diag.debug(`error reading machine id: ${r}`)}}dRe.getMachineId=gao});var cNr=T(fRe=>{"use strict";Object.defineProperty(fRe,"__esModule",{value:!0});fRe.getMachineId=void 0;var Aao=ye("fs"),yao=lRe(),aNr=(Zt(),vt(ur));async function _ao(){try{return(await Aao.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(t){aNr.diag.debug(`error reading machine id: ${t}`)}try{return(await(0,yao.execAsync)("kenv -q smbios.system.uuid")).stdout.trim()}catch(t){aNr.diag.debug(`error reading machine id: ${t}`)}}fRe.getMachineId=_ao});var uNr=T(pRe=>{"use strict";Object.defineProperty(pRe,"__esModule",{value:!0});pRe.getMachineId=void 0;var lNr=ye("process"),Eao=lRe(),vao=(Zt(),vt(ur));async function bao(){let t="QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",e="%windir%\\System32\\REG.exe";lNr.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in lNr.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{let n=(await(0,Eao.execAsync)(`${e} ${t}`)).stdout.split("REG_SZ");if(n.length===2)return n[1].trim()}catch(r){vao.diag.debug(`error reading machine id: ${r}`)}}pRe.getMachineId=bao});var dNr=T(hRe=>{"use strict";Object.defineProperty(hRe,"__esModule",{value:!0});hRe.getMachineId=void 0;var Cao=(Zt(),vt(ur));async function Sao(){Cao.diag.debug("could not read machine-id: unsupported platform")}hRe.getMachineId=Sao});var fNr=T(mRe=>{"use strict";Object.defineProperty(mRe,"__esModule",{value:!0});mRe.getMachineId=void 0;var xao=ye("process"),XL;async function wao(){if(!XL)switch(xao.platform){case"darwin":XL=(await Promise.resolve().then(()=>Te(oNr()))).getMachineId;break;case"linux":XL=(await Promise.resolve().then(()=>Te(sNr()))).getMachineId;break;case"freebsd":XL=(await Promise.resolve().then(()=>Te(cNr()))).getMachineId;break;case"win32":XL=(await Promise.resolve().then(()=>Te(uNr()))).getMachineId;break;default:XL=(await Promise.resolve().then(()=>Te(dNr()))).getMachineId;break}return XL()}mRe.getMachineId=wao});var Tyt=T(ZK=>{"use strict";Object.defineProperty(ZK,"__esModule",{value:!0});ZK.normalizeType=ZK.normalizeArch=void 0;var Tao=t=>{switch(t){case"arm":return"arm32";case"ppc":return"ppc32";case"x64":return"amd64";default:return t}};ZK.normalizeArch=Tao;var Iao=t=>{switch(t){case"sunos":return"solaris";case"win32":return"windows";default:return t}};ZK.normalizeType=Iao});var hNr=T(gRe=>{"use strict";Object.defineProperty(gRe,"__esModule",{value:!0});gRe.hostDetector=void 0;var Iyt=Cpe(),pNr=ye("os"),Dao=fNr(),Rao=Tyt(),Dyt=class{detect(e){return{attributes:{[Iyt.ATTR_HOST_NAME]:(0,pNr.hostname)(),[Iyt.ATTR_HOST_ARCH]:(0,Rao.normalizeArch)((0,pNr.arch)()),[Iyt.ATTR_HOST_ID]:(0,Dao.getMachineId)()}}}};gRe.hostDetector=new Dyt});var ANr=T(ARe=>{"use strict";Object.defineProperty(ARe,"__esModule",{value:!0});ARe.osDetector=void 0;var mNr=Cpe(),gNr=ye("os"),Nao=Tyt(),Ryt=class{detect(e){return{attributes:{[mNr.ATTR_OS_TYPE]:(0,Nao.normalizeType)((0,gNr.platform)()),[mNr.ATTR_OS_VERSION]:(0,gNr.release)()}}}};ARe.osDetector=new Ryt});var yNr=T(yRe=>{"use strict";Object.defineProperty(yRe,"__esModule",{value:!0});yRe.processDetector=void 0;var Oao=(Zt(),vt(ur)),R9=Cpe(),kao=ye("os"),Nyt=class{detect(e){let r={[R9.ATTR_PROCESS_PID]:process.pid,[R9.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[R9.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[R9.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[R9.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[R9.ATTR_PROCESS_RUNTIME_NAME]:"nodejs",[R9.ATTR_PROCESS_RUNTIME_DESCRIPTION]:"Node.js"};process.argv.length>1&&(r[R9.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let n=kao.userInfo();r[R9.ATTR_PROCESS_OWNER]=n.username}catch(n){Oao.diag.debug(`error obtaining process owner: ${n}`)}return{attributes:r}}};yRe.processDetector=new Nyt});var _Nr=T(_Re=>{"use strict";Object.defineProperty(_Re,"__esModule",{value:!0});_Re.serviceInstanceIdDetector=void 0;var Bao=Cpe(),Pao=ye("crypto"),Oyt=class{detect(e){return{attributes:{[Bao.ATTR_SERVICE_INSTANCE_ID]:(0,Pao.randomUUID)()}}}};_Re.serviceInstanceIdDetector=new Oyt});var ENr=T(Dx=>{"use strict";Object.defineProperty(Dx,"__esModule",{value:!0});Dx.serviceInstanceIdDetector=Dx.processDetector=Dx.osDetector=Dx.hostDetector=void 0;var Mao=hNr();Object.defineProperty(Dx,"hostDetector",{enumerable:!0,get:function(){return Mao.hostDetector}});var Fao=ANr();Object.defineProperty(Dx,"osDetector",{enumerable:!0,get:function(){return Fao.osDetector}});var Lao=yNr();Object.defineProperty(Dx,"processDetector",{enumerable:!0,get:function(){return Lao.processDetector}});var Uao=_Nr();Object.defineProperty(Dx,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return Uao.serviceInstanceIdDetector}})});var vNr=T(Rx=>{"use strict";Object.defineProperty(Rx,"__esModule",{value:!0});Rx.serviceInstanceIdDetector=Rx.processDetector=Rx.osDetector=Rx.hostDetector=void 0;var ERe=ENr();Object.defineProperty(Rx,"hostDetector",{enumerable:!0,get:function(){return ERe.hostDetector}});Object.defineProperty(Rx,"osDetector",{enumerable:!0,get:function(){return ERe.osDetector}});Object.defineProperty(Rx,"processDetector",{enumerable:!0,get:function(){return ERe.processDetector}});Object.defineProperty(Rx,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return ERe.serviceInstanceIdDetector}})});var bNr=T(eX=>{"use strict";Object.defineProperty(eX,"__esModule",{value:!0});eX.noopDetector=eX.NoopDetector=void 0;var vRe=class{detect(){return{attributes:{}}}};eX.NoopDetector=vRe;eX.noopDetector=new vRe});var CNr=T(M3=>{"use strict";Object.defineProperty(M3,"__esModule",{value:!0});M3.noopDetector=M3.serviceInstanceIdDetector=M3.processDetector=M3.osDetector=M3.hostDetector=M3.envDetector=void 0;var Qao=iNr();Object.defineProperty(M3,"envDetector",{enumerable:!0,get:function(){return Qao.envDetector}});var bRe=vNr();Object.defineProperty(M3,"hostDetector",{enumerable:!0,get:function(){return bRe.hostDetector}});Object.defineProperty(M3,"osDetector",{enumerable:!0,get:function(){return bRe.osDetector}});Object.defineProperty(M3,"processDetector",{enumerable:!0,get:function(){return bRe.processDetector}});Object.defineProperty(M3,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return bRe.serviceInstanceIdDetector}});var jao=bNr();Object.defineProperty(M3,"noopDetector",{enumerable:!0,get:function(){return jao.noopDetector}})});var Byt=T(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});Uf.defaultServiceName=Uf.emptyResource=Uf.defaultResource=Uf.resourceFromAttributes=Uf.serviceInstanceIdDetector=Uf.processDetector=Uf.osDetector=Uf.hostDetector=Uf.envDetector=Uf.detectResources=void 0;var Gao=rNr();Object.defineProperty(Uf,"detectResources",{enumerable:!0,get:function(){return Gao.detectResources}});var Spe=CNr();Object.defineProperty(Uf,"envDetector",{enumerable:!0,get:function(){return Spe.envDetector}});Object.defineProperty(Uf,"hostDetector",{enumerable:!0,get:function(){return Spe.hostDetector}});Object.defineProperty(Uf,"osDetector",{enumerable:!0,get:function(){return Spe.osDetector}});Object.defineProperty(Uf,"processDetector",{enumerable:!0,get:function(){return Spe.processDetector}});Object.defineProperty(Uf,"serviceInstanceIdDetector",{enumerable:!0,get:function(){return Spe.serviceInstanceIdDetector}});var kyt=Syt();Object.defineProperty(Uf,"resourceFromAttributes",{enumerable:!0,get:function(){return kyt.resourceFromAttributes}});Object.defineProperty(Uf,"defaultResource",{enumerable:!0,get:function(){return kyt.defaultResource}});Object.defineProperty(Uf,"emptyResource",{enumerable:!0,get:function(){return kyt.emptyResource}});var $ao=vyt();Object.defineProperty(Uf,"defaultServiceName",{enumerable:!0,get:function(){return $ao.defaultServiceName}})});var SNr=T(xpe=>{"use strict";Object.defineProperty(xpe,"__esModule",{value:!0});xpe.SeverityNumber=void 0;var qao;(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"})(qao=xpe.SeverityNumber||(xpe.SeverityNumber={}))});var SRe=T(tX=>{"use strict";Object.defineProperty(tX,"__esModule",{value:!0});tX.NOOP_LOGGER=tX.NoopLogger=void 0;var CRe=class{emit(e){}};tX.NoopLogger=CRe;tX.NOOP_LOGGER=new CRe});var wRe=T(rX=>{"use strict";Object.defineProperty(rX,"__esModule",{value:!0});rX.NOOP_LOGGER_PROVIDER=rX.NoopLoggerProvider=void 0;var Hao=SRe(),xRe=class{getLogger(e,r,n){return new Hao.NoopLogger}};rX.NoopLoggerProvider=xRe;rX.NOOP_LOGGER_PROVIDER=new xRe});var Myt=T(TRe=>{"use strict";Object.defineProperty(TRe,"__esModule",{value:!0});TRe.ProxyLogger=void 0;var Vao=SRe(),Pyt=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):Vao.NOOP_LOGGER}};TRe.ProxyLogger=Pyt});var Lyt=T(IRe=>{"use strict";Object.defineProperty(IRe,"__esModule",{value:!0});IRe.ProxyLoggerProvider=void 0;var Wao=wRe(),zao=Myt(),Fyt=class{getLogger(e,r,n){var o;return(o=this._getDelegateLogger(e,r,n))!==null&&o!==void 0?o:new zao.ProxyLogger(this,e,r,n)}_getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Wao.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)}};IRe.ProxyLoggerProvider=Fyt});var xNr=T(DRe=>{"use strict";Object.defineProperty(DRe,"__esModule",{value:!0});DRe._globalThis=void 0;DRe._globalThis=typeof globalThis=="object"?globalThis:global});var wNr=T(RRe=>{"use strict";Object.defineProperty(RRe,"__esModule",{value:!0});RRe._globalThis=void 0;var Yao=xNr();Object.defineProperty(RRe,"_globalThis",{enumerable:!0,get:function(){return Yao._globalThis}})});var TNr=T(NRe=>{"use strict";Object.defineProperty(NRe,"__esModule",{value:!0});NRe._globalThis=void 0;var Kao=wNr();Object.defineProperty(NRe,"_globalThis",{enumerable:!0,get:function(){return Kao._globalThis}})});var INr=T(Nx=>{"use strict";Object.defineProperty(Nx,"__esModule",{value:!0});Nx.API_BACKWARDS_COMPATIBILITY_VERSION=Nx.makeGetter=Nx._global=Nx.GLOBAL_LOGS_API_KEY=void 0;var Xao=TNr();Nx.GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs");Nx._global=Xao._globalThis;function Jao(t,e,r){return n=>n===t?e:r}Nx.makeGetter=Jao;Nx.API_BACKWARDS_COMPATIBILITY_VERSION=1});var RNr=T(ORe=>{"use strict";Object.defineProperty(ORe,"__esModule",{value:!0});ORe.LogsAPI=void 0;var tv=INr(),Zao=wRe(),DNr=Lyt(),Uyt=class t{constructor(){this._proxyLoggerProvider=new DNr.ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalLoggerProvider(e){return tv._global[tv.GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(tv._global[tv.GLOBAL_LOGS_API_KEY]=(0,tv.makeGetter)(tv.API_BACKWARDS_COMPATIBILITY_VERSION,e,Zao.NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider._setDelegate(e),e)}getLoggerProvider(){var e,r;return(r=(e=tv._global[tv.GLOBAL_LOGS_API_KEY])===null||e===void 0?void 0:e.call(tv._global,tv.API_BACKWARDS_COMPATIBILITY_VERSION))!==null&&r!==void 0?r:this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){delete tv._global[tv.GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new DNr.ProxyLoggerProvider}};ORe.LogsAPI=Uyt});var kNr=T(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});Km.logs=Km.ProxyLoggerProvider=Km.ProxyLogger=Km.NoopLoggerProvider=Km.NOOP_LOGGER_PROVIDER=Km.NoopLogger=Km.NOOP_LOGGER=Km.SeverityNumber=void 0;var eco=SNr();Object.defineProperty(Km,"SeverityNumber",{enumerable:!0,get:function(){return eco.SeverityNumber}});var NNr=SRe();Object.defineProperty(Km,"NOOP_LOGGER",{enumerable:!0,get:function(){return NNr.NOOP_LOGGER}});Object.defineProperty(Km,"NoopLogger",{enumerable:!0,get:function(){return NNr.NoopLogger}});var ONr=wRe();Object.defineProperty(Km,"NOOP_LOGGER_PROVIDER",{enumerable:!0,get:function(){return ONr.NOOP_LOGGER_PROVIDER}});Object.defineProperty(Km,"NoopLoggerProvider",{enumerable:!0,get:function(){return ONr.NoopLoggerProvider}});var tco=Myt();Object.defineProperty(Km,"ProxyLogger",{enumerable:!0,get:function(){return tco.ProxyLogger}});var rco=Lyt();Object.defineProperty(Km,"ProxyLoggerProvider",{enumerable:!0,get:function(){return rco.ProxyLoggerProvider}});var nco=RNr();Km.logs=nco.LogsAPI.getInstance()});var wpe=T(DN=>{"use strict";Object.defineProperty(DN,"__esModule",{value:!0});DN.isTracingSuppressed=DN.unsuppressTracing=DN.suppressTracing=void 0;var ico=(Zt(),vt(ur)),Qyt=(0,ico.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function oco(t){return t.setValue(Qyt,!0)}DN.suppressTracing=oco;function sco(t){return t.deleteValue(Qyt)}DN.unsuppressTracing=sco;function aco(t){return t.getValue(Qyt)===!0}DN.isTracingSuppressed=aco});var jyt=T(TA=>{"use strict";Object.defineProperty(TA,"__esModule",{value:!0});TA.BAGGAGE_MAX_TOTAL_LENGTH=TA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=TA.BAGGAGE_MAX_NAME_VALUE_PAIRS=TA.BAGGAGE_HEADER=TA.BAGGAGE_ITEMS_SEPARATOR=TA.BAGGAGE_PROPERTIES_SEPARATOR=TA.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;TA.BAGGAGE_KEY_PAIR_SEPARATOR="=";TA.BAGGAGE_PROPERTIES_SEPARATOR=";";TA.BAGGAGE_ITEMS_SEPARATOR=",";TA.BAGGAGE_HEADER="baggage";TA.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;TA.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;TA.BAGGAGE_MAX_TOTAL_LENGTH=8192});var Gyt=T(Ox=>{"use strict";Object.defineProperty(Ox,"__esModule",{value:!0});Ox.parseKeyPairsIntoRecord=Ox.parsePairKeyValue=Ox.getKeyPairs=Ox.serializeKeyPairs=void 0;var cco=(Zt(),vt(ur)),JL=jyt();function lco(t){return t.reduce((e,r)=>{let n=`${e}${e!==""?JL.BAGGAGE_ITEMS_SEPARATOR:""}${r}`;return n.length>JL.BAGGAGE_MAX_TOTAL_LENGTH?e:n},"")}Ox.serializeKeyPairs=lco;function uco(t){return t.getAllEntries().map(([e,r])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(r.value)}`;return r.metadata!==void 0&&(n+=JL.BAGGAGE_PROPERTIES_SEPARATOR+r.metadata.toString()),n})}Ox.getKeyPairs=uco;function BNr(t){let e=t.split(JL.BAGGAGE_PROPERTIES_SEPARATOR);if(e.length<=0)return;let r=e.shift();if(!r)return;let n=r.indexOf(JL.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,cco.baggageEntryMetadataFromString)(e.join(JL.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:a}}Ox.parsePairKeyValue=BNr;function dco(t){let e={};return typeof t=="string"&&t.length>0&&t.split(JL.BAGGAGE_ITEMS_SEPARATOR).forEach(r=>{let n=BNr(r);n!==void 0&&n.value.length>0&&(e[n.key]=n.value)}),e}Ox.parseKeyPairsIntoRecord=dco});var PNr=T(kRe=>{"use strict";Object.defineProperty(kRe,"__esModule",{value:!0});kRe.W3CBaggagePropagator=void 0;var $yt=(Zt(),vt(ur)),fco=wpe(),ZL=jyt(),qyt=Gyt(),Hyt=class{inject(e,r,n){let o=$yt.propagation.getBaggage(e);if(!o||(0,fco.isTracingSuppressed)(e))return;let s=(0,qyt.getKeyPairs)(o).filter(c=>c.length<=ZL.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,ZL.BAGGAGE_MAX_NAME_VALUE_PAIRS),a=(0,qyt.serializeKeyPairs)(s);a.length>0&&n.set(r,ZL.BAGGAGE_HEADER,a)}extract(e,r,n){let o=n.get(r,ZL.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(ZL.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let a={};return s.length===0||(s.split(ZL.BAGGAGE_ITEMS_SEPARATOR).forEach(u=>{let d=(0,qyt.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:$yt.propagation.setBaggage(e,$yt.propagation.createBaggage(a))}fields(){return[ZL.BAGGAGE_HEADER]}};kRe.W3CBaggagePropagator=Hyt});var MNr=T(BRe=>{"use strict";Object.defineProperty(BRe,"__esModule",{value:!0});BRe.AnchoredClock=void 0;var Vyt=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}};BRe.AnchoredClock=Vyt});var jNr=T(RN=>{"use strict";Object.defineProperty(RN,"__esModule",{value:!0});RN.isAttributeValue=RN.isAttributeKey=RN.sanitizeAttributes=void 0;var FNr=(Zt(),vt(ur));function pco(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(!LNr(r)){FNr.diag.warn(`Invalid attribute key: ${r}`);continue}let n=t[r];if(!UNr(n)){FNr.diag.warn(`Invalid attribute value set for key: ${r}`);continue}Array.isArray(n)?e[r]=n.slice():e[r]=n}return e}RN.sanitizeAttributes=pco;function LNr(t){return typeof t=="string"&&t!==""}RN.isAttributeKey=LNr;function UNr(t){return t==null?!0:Array.isArray(t)?hco(t):QNr(typeof t)}RN.isAttributeValue=UNr;function hco(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 Wyt=T(PRe=>{"use strict";Object.defineProperty(PRe,"__esModule",{value:!0});PRe.loggingErrorHandler=void 0;var mco=(Zt(),vt(ur));function gco(){return t=>{mco.diag.error(Aco(t))}}PRe.loggingErrorHandler=gco;function Aco(t){return typeof t=="string"?t:JSON.stringify(yco(t))}function yco(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 $Nr=T(nX=>{"use strict";Object.defineProperty(nX,"__esModule",{value:!0});nX.globalErrorHandler=nX.setGlobalErrorHandler=void 0;var _co=Wyt(),GNr=(0,_co.loggingErrorHandler)();function Eco(t){GNr=t}nX.setGlobalErrorHandler=Eco;function vco(t){try{GNr(t)}catch{}}nX.globalErrorHandler=vco});var WNr=T(kx=>{"use strict";Object.defineProperty(kx,"__esModule",{value:!0});kx.getStringListFromEnv=kx.getBooleanFromEnv=kx.getStringFromEnv=kx.getNumberFromEnv=void 0;var qNr=(Zt(),vt(ur)),HNr=ye("util");function bco(t){let e=process.env[t];if(e==null||e.trim()==="")return;let r=Number(e);if(isNaN(r)){qNr.diag.warn(`Unknown value ${(0,HNr.inspect)(e)} for ${t}, expected a number, using defaults`);return}return r}kx.getNumberFromEnv=bco;function VNr(t){let e=process.env[t];if(!(e==null||e.trim()===""))return e}kx.getStringFromEnv=VNr;function Cco(t){let e=process.env[t]?.trim().toLowerCase();return e==null||e===""?!1:e==="true"?!0:(e==="false"||qNr.diag.warn(`Unknown value ${(0,HNr.inspect)(e)} for ${t}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}kx.getBooleanFromEnv=Cco;function Sco(t){return VNr(t)?.split(",").map(e=>e.trim()).filter(e=>e!=="")}kx.getStringListFromEnv=Sco});var zNr=T(MRe=>{"use strict";Object.defineProperty(MRe,"__esModule",{value:!0});MRe._globalThis=void 0;MRe._globalThis=typeof globalThis=="object"?globalThis:global});var YNr=T(FRe=>{"use strict";Object.defineProperty(FRe,"__esModule",{value:!0});FRe.otperformance=void 0;var xco=ye("perf_hooks");FRe.otperformance=xco.performance});var KNr=T(LRe=>{"use strict";Object.defineProperty(LRe,"__esModule",{value:!0});LRe.VERSION=void 0;LRe.VERSION="2.2.0"});var XNr=T(URe=>{"use strict";Object.defineProperty(URe,"__esModule",{value:!0});URe.ATTR_PROCESS_RUNTIME_NAME=void 0;URe.ATTR_PROCESS_RUNTIME_NAME="process.runtime.name"});var JNr=T(jRe=>{"use strict";Object.defineProperty(jRe,"__esModule",{value:!0});jRe.SDK_INFO=void 0;var wco=KNr(),QRe=($h(),vt(yA)),Tco=XNr();jRe.SDK_INFO={[QRe.ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[Tco.ATTR_PROCESS_RUNTIME_NAME]:"node",[QRe.ATTR_TELEMETRY_SDK_LANGUAGE]:QRe.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[QRe.ATTR_TELEMETRY_SDK_VERSION]:wco.VERSION}});var ZNr=T(IA=>{"use strict";Object.defineProperty(IA,"__esModule",{value:!0});IA.SDK_INFO=IA.otperformance=IA._globalThis=IA.getStringListFromEnv=IA.getNumberFromEnv=IA.getBooleanFromEnv=IA.getStringFromEnv=void 0;var GRe=WNr();Object.defineProperty(IA,"getStringFromEnv",{enumerable:!0,get:function(){return GRe.getStringFromEnv}});Object.defineProperty(IA,"getBooleanFromEnv",{enumerable:!0,get:function(){return GRe.getBooleanFromEnv}});Object.defineProperty(IA,"getNumberFromEnv",{enumerable:!0,get:function(){return GRe.getNumberFromEnv}});Object.defineProperty(IA,"getStringListFromEnv",{enumerable:!0,get:function(){return GRe.getStringListFromEnv}});var Ico=zNr();Object.defineProperty(IA,"_globalThis",{enumerable:!0,get:function(){return Ico._globalThis}});var Dco=YNr();Object.defineProperty(IA,"otperformance",{enumerable:!0,get:function(){return Dco.otperformance}});var Rco=JNr();Object.defineProperty(IA,"SDK_INFO",{enumerable:!0,get:function(){return Rco.SDK_INFO}})});var zyt=T(DA=>{"use strict";Object.defineProperty(DA,"__esModule",{value:!0});DA.getStringListFromEnv=DA.getNumberFromEnv=DA.getStringFromEnv=DA.getBooleanFromEnv=DA.otperformance=DA._globalThis=DA.SDK_INFO=void 0;var eU=ZNr();Object.defineProperty(DA,"SDK_INFO",{enumerable:!0,get:function(){return eU.SDK_INFO}});Object.defineProperty(DA,"_globalThis",{enumerable:!0,get:function(){return eU._globalThis}});Object.defineProperty(DA,"otperformance",{enumerable:!0,get:function(){return eU.otperformance}});Object.defineProperty(DA,"getBooleanFromEnv",{enumerable:!0,get:function(){return eU.getBooleanFromEnv}});Object.defineProperty(DA,"getStringFromEnv",{enumerable:!0,get:function(){return eU.getStringFromEnv}});Object.defineProperty(DA,"getNumberFromEnv",{enumerable:!0,get:function(){return eU.getNumberFromEnv}});Object.defineProperty(DA,"getStringListFromEnv",{enumerable:!0,get:function(){return eU.getStringListFromEnv}})});var nOr=T(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});xu.addHrTimes=xu.isTimeInput=xu.isTimeInputHrTime=xu.hrTimeToMicroseconds=xu.hrTimeToMilliseconds=xu.hrTimeToNanoseconds=xu.hrTimeToTimeStamp=xu.hrTimeDuration=xu.timeInputToHrTime=xu.hrTime=xu.getTimeOrigin=xu.millisToHrTime=void 0;var Yyt=zyt(),eOr=9,Nco=6,Oco=Math.pow(10,Nco),$Re=Math.pow(10,eOr);function Tpe(t){let e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*Oco);return[r,n]}xu.millisToHrTime=Tpe;function Kyt(){let t=Yyt.otperformance.timeOrigin;if(typeof t!="number"){let e=Yyt.otperformance;t=e.timing&&e.timing.fetchStart}return t}xu.getTimeOrigin=Kyt;function tOr(t){let e=Tpe(Kyt()),r=Tpe(typeof t=="number"?t:Yyt.otperformance.now());return rOr(e,r)}xu.hrTime=tOr;function kco(t){if(Xyt(t))return t;if(typeof t=="number")return t<Kyt()?tOr(t):Tpe(t);if(t instanceof Date)return Tpe(t.getTime());throw TypeError("Invalid input type")}xu.timeInputToHrTime=kco;function Bco(t,e){let r=e[0]-t[0],n=e[1]-t[1];return n<0&&(r-=1,n+=$Re),[r,n]}xu.hrTimeDuration=Bco;function Pco(t){let e=eOr,r=`${"0".repeat(e)}${t[1]}Z`,n=r.substring(r.length-e-1);return new Date(t[0]*1e3).toISOString().replace("000Z",n)}xu.hrTimeToTimeStamp=Pco;function Mco(t){return t[0]*$Re+t[1]}xu.hrTimeToNanoseconds=Mco;function Fco(t){return t[0]*1e3+t[1]/1e6}xu.hrTimeToMilliseconds=Fco;function Lco(t){return t[0]*1e6+t[1]/1e3}xu.hrTimeToMicroseconds=Lco;function Xyt(t){return Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number"}xu.isTimeInputHrTime=Xyt;function Uco(t){return Xyt(t)||typeof t=="number"||t instanceof Date}xu.isTimeInput=Uco;function rOr(t,e){let r=[t[0]+e[0],t[1]+e[1]];return r[1]>=$Re&&(r[1]-=$Re,r[0]+=1),r}xu.addHrTimes=rOr});var iOr=T(qRe=>{"use strict";Object.defineProperty(qRe,"__esModule",{value:!0});qRe.unrefTimer=void 0;function Qco(t){typeof t!="number"&&t.unref()}qRe.unrefTimer=Qco});var oOr=T(Ipe=>{"use strict";Object.defineProperty(Ipe,"__esModule",{value:!0});Ipe.ExportResultCode=void 0;var jco;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(jco=Ipe.ExportResultCode||(Ipe.ExportResultCode={}))});var aOr=T(HRe=>{"use strict";Object.defineProperty(HRe,"__esModule",{value:!0});HRe.CompositePropagator=void 0;var sOr=(Zt(),vt(ur)),Jyt=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){sOr.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){sOr.diag.warn(`Failed to extract with ${s.constructor.name}. Err: ${a.message}`)}return o},e)}fields(){return this._fields.slice()}};HRe.CompositePropagator=Jyt});var cOr=T(iX=>{"use strict";Object.defineProperty(iX,"__esModule",{value:!0});iX.validateValue=iX.validateKey=void 0;var Zyt="[_0-9a-z-*/]",Gco=`[a-z]${Zyt}{0,255}`,$co=`[a-z0-9]${Zyt}{0,240}@[a-z]${Zyt}{0,13}`,qco=new RegExp(`^(?:${Gco}|${$co})$`),Hco=/^[ -~]{0,255}[!-~]$/,Vco=/,|=/;function Wco(t){return qco.test(t)}iX.validateKey=Wco;function zco(t){return Hco.test(t)&&!Vco.test(t)}iX.validateValue=zco});var t_t=T(VRe=>{"use strict";Object.defineProperty(VRe,"__esModule",{value:!0});VRe.TraceState=void 0;var lOr=cOr(),uOr=32,Yco=512,dOr=",",fOr="=",e_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+fOr+this.get(r)),e),[]).join(dOr)}_parse(e){e.length>Yco||(this._internalState=e.split(dOr).reverse().reduce((r,n)=>{let o=n.trim(),s=o.indexOf(fOr);if(s!==-1){let a=o.slice(0,s),c=o.slice(s+1,n.length);(0,lOr.validateKey)(a)&&(0,lOr.validateValue)(c)&&r.set(a,c)}return r},new Map),this._internalState.size>uOr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,uOr))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}};VRe.TraceState=e_t});var hOr=T(RA=>{"use strict";Object.defineProperty(RA,"__esModule",{value:!0});RA.W3CTraceContextPropagator=RA.parseTraceParent=RA.TRACE_STATE_HEADER=RA.TRACE_PARENT_HEADER=void 0;var WRe=(Zt(),vt(ur)),Kco=wpe(),Xco=t_t();RA.TRACE_PARENT_HEADER="traceparent";RA.TRACE_STATE_HEADER="tracestate";var Jco="00",Zco="(?!ff)[\\da-f]{2}",elo="(?![0]{32})[\\da-f]{32}",tlo="(?![0]{16})[\\da-f]{16}",rlo="[\\da-f]{2}",nlo=new RegExp(`^\\s?(${Zco})-(${elo})-(${tlo})-(${rlo})(-.*)?\\s?$`);function pOr(t){let e=nlo.exec(t);return!e||e[1]==="00"&&e[5]?null:{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}RA.parseTraceParent=pOr;var r_t=class{inject(e,r,n){let o=WRe.trace.getSpanContext(e);if(!o||(0,Kco.isTracingSuppressed)(e)||!(0,WRe.isSpanContextValid)(o))return;let s=`${Jco}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||WRe.TraceFlags.NONE).toString(16)}`;n.set(r,RA.TRACE_PARENT_HEADER,s),o.traceState&&n.set(r,RA.TRACE_STATE_HEADER,o.traceState.serialize())}extract(e,r,n){let o=n.get(r,RA.TRACE_PARENT_HEADER);if(!o)return e;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return e;let a=pOr(s);if(!a)return e;a.isRemote=!0;let c=n.get(r,RA.TRACE_STATE_HEADER);if(c){let u=Array.isArray(c)?c.join(","):c;a.traceState=new Xco.TraceState(typeof u=="string"?u:void 0)}return WRe.trace.setSpanContext(e,a)}fields(){return[RA.TRACE_PARENT_HEADER,RA.TRACE_STATE_HEADER]}};RA.W3CTraceContextPropagator=r_t});var mOr=T(fC=>{"use strict";Object.defineProperty(fC,"__esModule",{value:!0});fC.getRPCMetadata=fC.deleteRPCMetadata=fC.setRPCMetadata=fC.RPCType=void 0;var ilo=(Zt(),vt(ur)),n_t=(0,ilo.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"),olo;(function(t){t.HTTP="http"})(olo=fC.RPCType||(fC.RPCType={}));function slo(t,e){return t.setValue(n_t,e)}fC.setRPCMetadata=slo;function alo(t){return t.deleteValue(n_t)}fC.deleteRPCMetadata=alo;function clo(t){return t.getValue(n_t)}fC.getRPCMetadata=clo});var EOr=T(zRe=>{"use strict";Object.defineProperty(zRe,"__esModule",{value:!0});zRe.isPlainObject=void 0;var llo="[object Object]",ulo="[object Null]",dlo="[object Undefined]",flo=Function.prototype,gOr=flo.toString,plo=gOr.call(Object),hlo=Object.getPrototypeOf,AOr=Object.prototype,yOr=AOr.hasOwnProperty,tU=Symbol?Symbol.toStringTag:void 0,_Or=AOr.toString;function mlo(t){if(!glo(t)||Alo(t)!==llo)return!1;let e=hlo(t);if(e===null)return!0;let r=yOr.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&gOr.call(r)===plo}zRe.isPlainObject=mlo;function glo(t){return t!=null&&typeof t=="object"}function Alo(t){return t==null?t===void 0?dlo:ulo:tU&&tU in Object(t)?ylo(t):_lo(t)}function ylo(t){let e=yOr.call(t,tU),r=t[tU],n=!1;try{t[tU]=void 0,n=!0}catch{}let o=_Or.call(t);return n&&(e?t[tU]=r:delete t[tU]),o}function _lo(t){return _Or.call(t)}});var xOr=T(XRe=>{"use strict";Object.defineProperty(XRe,"__esModule",{value:!0});XRe.merge=void 0;var vOr=EOr(),Elo=20;function vlo(...t){let e=t.shift(),r=new WeakMap;for(;t.length>0;)e=COr(e,t.shift(),0,r);return e}XRe.merge=vlo;function i_t(t){return KRe(t)?t.slice():t}function COr(t,e,r=0,n){let o;if(!(r>Elo)){if(r++,YRe(t)||YRe(e)||SOr(e))o=i_t(e);else if(KRe(t)){if(o=t.slice(),KRe(e))for(let s=0,a=e.length;s<a;s++)o.push(i_t(e[s]));else if(Dpe(e)){let s=Object.keys(e);for(let a=0,c=s.length;a<c;a++){let u=s[a];o[u]=i_t(e[u])}}}else if(Dpe(t))if(Dpe(e)){if(!blo(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(YRe(d))typeof d>"u"?delete o[u]:o[u]=d;else{let f=o[u],p=d;if(bOr(t,u,n)||bOr(e,u,n))delete o[u];else{if(Dpe(f)&&Dpe(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]=COr(o[u],d,r,n)}}}}else o=e;return o}}function bOr(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 KRe(t){return Array.isArray(t)}function SOr(t){return typeof t=="function"}function Dpe(t){return!YRe(t)&&!KRe(t)&&!SOr(t)&&typeof t=="object"}function YRe(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t>"u"||t instanceof Date||t instanceof RegExp||t===null}function blo(t,e){return!(!(0,vOr.isPlainObject)(t)||!(0,vOr.isPlainObject)(e))}});var wOr=T(oX=>{"use strict";Object.defineProperty(oX,"__esModule",{value:!0});oX.callWithTimeout=oX.TimeoutError=void 0;var JRe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};oX.TimeoutError=JRe;function Clo(t,e){let r,n=new Promise(function(s,a){r=setTimeout(function(){a(new JRe("Operation timed out."))},e)});return Promise.race([t,n]).then(o=>(clearTimeout(r),o),o=>{throw clearTimeout(r),o})}oX.callWithTimeout=Clo});var IOr=T(sX=>{"use strict";Object.defineProperty(sX,"__esModule",{value:!0});sX.isUrlIgnored=sX.urlMatches=void 0;function TOr(t,e){return typeof e=="string"?t===e:!!t.match(e)}sX.urlMatches=TOr;function Slo(t,e){if(!e)return!1;for(let r of e)if(TOr(t,r))return!0;return!1}sX.isUrlIgnored=Slo});var DOr=T(ZRe=>{"use strict";Object.defineProperty(ZRe,"__esModule",{value:!0});ZRe.Deferred=void 0;var o_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)}};ZRe.Deferred=o_t});var ROr=T(eNe=>{"use strict";Object.defineProperty(eNe,"__esModule",{value:!0});eNe.BindOnceFuture=void 0;var xlo=DOr(),s_t=class{_callback;_that;_isCalled=!1;_deferred=new xlo.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}};eNe.BindOnceFuture=s_t});var OOr=T(tNe=>{"use strict";Object.defineProperty(tNe,"__esModule",{value:!0});tNe.diagLogLevelFromString=void 0;var N9=(Zt(),vt(ur)),NOr={ALL:N9.DiagLogLevel.ALL,VERBOSE:N9.DiagLogLevel.VERBOSE,DEBUG:N9.DiagLogLevel.DEBUG,INFO:N9.DiagLogLevel.INFO,WARN:N9.DiagLogLevel.WARN,ERROR:N9.DiagLogLevel.ERROR,NONE:N9.DiagLogLevel.NONE};function wlo(t){if(t==null)return;let e=NOr[t.toUpperCase()];return e??(N9.diag.warn(`Unknown log level "${t}", expected one of ${Object.keys(NOr)}, using default`),N9.DiagLogLevel.INFO)}tNe.diagLogLevelFromString=wlo});var BOr=T(rNe=>{"use strict";Object.defineProperty(rNe,"__esModule",{value:!0});rNe._export=void 0;var kOr=(Zt(),vt(ur)),Tlo=wpe();function Ilo(t,e){return new Promise(r=>{kOr.context.with((0,Tlo.suppressTracing)(kOr.context.active()),()=>{t.export(e,n=>{r(n)})})})}rNe._export=Ilo});var O9=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 Dlo=PNr();Object.defineProperty(jr,"W3CBaggagePropagator",{enumerable:!0,get:function(){return Dlo.W3CBaggagePropagator}});var Rlo=MNr();Object.defineProperty(jr,"AnchoredClock",{enumerable:!0,get:function(){return Rlo.AnchoredClock}});var POr=jNr();Object.defineProperty(jr,"isAttributeValue",{enumerable:!0,get:function(){return POr.isAttributeValue}});Object.defineProperty(jr,"sanitizeAttributes",{enumerable:!0,get:function(){return POr.sanitizeAttributes}});var MOr=$Nr();Object.defineProperty(jr,"globalErrorHandler",{enumerable:!0,get:function(){return MOr.globalErrorHandler}});Object.defineProperty(jr,"setGlobalErrorHandler",{enumerable:!0,get:function(){return MOr.setGlobalErrorHandler}});var Nlo=Wyt();Object.defineProperty(jr,"loggingErrorHandler",{enumerable:!0,get:function(){return Nlo.loggingErrorHandler}});var rv=nOr();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 Olo=iOr();Object.defineProperty(jr,"unrefTimer",{enumerable:!0,get:function(){return Olo.unrefTimer}});var klo=oOr();Object.defineProperty(jr,"ExportResultCode",{enumerable:!0,get:function(){return klo.ExportResultCode}});var Blo=Gyt();Object.defineProperty(jr,"parseKeyPairsIntoRecord",{enumerable:!0,get:function(){return Blo.parseKeyPairsIntoRecord}});var rU=zyt();Object.defineProperty(jr,"SDK_INFO",{enumerable:!0,get:function(){return rU.SDK_INFO}});Object.defineProperty(jr,"_globalThis",{enumerable:!0,get:function(){return rU._globalThis}});Object.defineProperty(jr,"getStringFromEnv",{enumerable:!0,get:function(){return rU.getStringFromEnv}});Object.defineProperty(jr,"getBooleanFromEnv",{enumerable:!0,get:function(){return rU.getBooleanFromEnv}});Object.defineProperty(jr,"getNumberFromEnv",{enumerable:!0,get:function(){return rU.getNumberFromEnv}});Object.defineProperty(jr,"getStringListFromEnv",{enumerable:!0,get:function(){return rU.getStringListFromEnv}});Object.defineProperty(jr,"otperformance",{enumerable:!0,get:function(){return rU.otperformance}});var Plo=aOr();Object.defineProperty(jr,"CompositePropagator",{enumerable:!0,get:function(){return Plo.CompositePropagator}});var nNe=hOr();Object.defineProperty(jr,"TRACE_PARENT_HEADER",{enumerable:!0,get:function(){return nNe.TRACE_PARENT_HEADER}});Object.defineProperty(jr,"TRACE_STATE_HEADER",{enumerable:!0,get:function(){return nNe.TRACE_STATE_HEADER}});Object.defineProperty(jr,"W3CTraceContextPropagator",{enumerable:!0,get:function(){return nNe.W3CTraceContextPropagator}});Object.defineProperty(jr,"parseTraceParent",{enumerable:!0,get:function(){return nNe.parseTraceParent}});var iNe=mOr();Object.defineProperty(jr,"RPCType",{enumerable:!0,get:function(){return iNe.RPCType}});Object.defineProperty(jr,"deleteRPCMetadata",{enumerable:!0,get:function(){return iNe.deleteRPCMetadata}});Object.defineProperty(jr,"getRPCMetadata",{enumerable:!0,get:function(){return iNe.getRPCMetadata}});Object.defineProperty(jr,"setRPCMetadata",{enumerable:!0,get:function(){return iNe.setRPCMetadata}});var a_t=wpe();Object.defineProperty(jr,"isTracingSuppressed",{enumerable:!0,get:function(){return a_t.isTracingSuppressed}});Object.defineProperty(jr,"suppressTracing",{enumerable:!0,get:function(){return a_t.suppressTracing}});Object.defineProperty(jr,"unsuppressTracing",{enumerable:!0,get:function(){return a_t.unsuppressTracing}});var Mlo=t_t();Object.defineProperty(jr,"TraceState",{enumerable:!0,get:function(){return Mlo.TraceState}});var Flo=xOr();Object.defineProperty(jr,"merge",{enumerable:!0,get:function(){return Flo.merge}});var FOr=wOr();Object.defineProperty(jr,"TimeoutError",{enumerable:!0,get:function(){return FOr.TimeoutError}});Object.defineProperty(jr,"callWithTimeout",{enumerable:!0,get:function(){return FOr.callWithTimeout}});var LOr=IOr();Object.defineProperty(jr,"isUrlIgnored",{enumerable:!0,get:function(){return LOr.isUrlIgnored}});Object.defineProperty(jr,"urlMatches",{enumerable:!0,get:function(){return LOr.urlMatches}});var Llo=ROr();Object.defineProperty(jr,"BindOnceFuture",{enumerable:!0,get:function(){return Llo.BindOnceFuture}});var Ulo=OOr();Object.defineProperty(jr,"diagLogLevelFromString",{enumerable:!0,get:function(){return Ulo.diagLogLevelFromString}});var Qlo=BOr();jr.internal={_export:Qlo._export}});var UOr=T(sNe=>{"use strict";Object.defineProperty(sNe,"__esModule",{value:!0});sNe.LogRecordImpl=void 0;var nU=(Zt(),vt(ur)),oNe=O9(),c_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,oNe.timeInputToHrTime)(o??h),this.hrTimeObserved=(0,oNe.timeInputToHrTime)(s??h),p){let m=nU.trace.getSpanContext(p);m&&nU.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?(nU.diag.warn(`Invalid attribute key: ${e}`),this):!(0,oNe.isAttributeValue)(r)&&!(typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length>0)?(nU.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&&nU.diag.warn("Dropping extra attributes."),this):((0,oNe.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?(nU.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&&nU.diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}};sNe.LogRecordImpl=c_t});var QOr=T(aNe=>{"use strict";Object.defineProperty(aNe,"__esModule",{value:!0});aNe.Logger=void 0;var jlo=(Zt(),vt(ur)),Glo=UOr(),l_t=class{instrumentationScope;_sharedState;constructor(e,r){this.instrumentationScope=e,this._sharedState=r}emit(e){let r=e.context||jlo.context.active(),n=new Glo.LogRecordImpl(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(n,r),n._makeReadonly()}};aNe.Logger=l_t});var jOr=T(cX=>{"use strict";Object.defineProperty(cX,"__esModule",{value:!0});cX.reconfigureLimits=cX.loadDefaultConfig=void 0;var aX=O9();function $lo(){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=$lo;function qlo(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=qlo});var d_t=T(cNe=>{"use strict";Object.defineProperty(cNe,"__esModule",{value:!0});cNe.NoopLogRecordProcessor=void 0;var u_t=class{forceFlush(){return Promise.resolve()}onEmit(e,r){}shutdown(){return Promise.resolve()}};cNe.NoopLogRecordProcessor=u_t});var GOr=T(lNe=>{"use strict";Object.defineProperty(lNe,"__esModule",{value:!0});lNe.MultiLogRecordProcessor=void 0;var Hlo=O9(),f_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,Hlo.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()))}};lNe.MultiLogRecordProcessor=f_t});var $Or=T(uNe=>{"use strict";Object.defineProperty(uNe,"__esModule",{value:!0});uNe.LoggerProviderSharedState=void 0;var Vlo=d_t(),Wlo=GOr(),p_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 Wlo.MultiLogRecordProcessor(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new Vlo.NoopLogRecordProcessor}};uNe.LoggerProviderSharedState=p_t});var VOr=T(iU=>{"use strict";Object.defineProperty(iU,"__esModule",{value:!0});iU.LoggerProvider=iU.DEFAULT_LOGGER_NAME=void 0;var dNe=(Zt(),vt(ur)),zlo=kNr(),Ylo=Byt(),qOr=O9(),Klo=QOr(),HOr=jOr(),Xlo=$Or();iU.DEFAULT_LOGGER_NAME="unknown";var h_t=class{_shutdownOnce;_sharedState;constructor(e={}){let r=(0,qOr.merge)({},(0,HOr.loadDefaultConfig)(),e),n=e.resource??(0,Ylo.defaultResource)();this._sharedState=new Xlo.LoggerProviderSharedState(n,r.forceFlushTimeoutMillis,(0,HOr.reconfigureLimits)(r.logRecordLimits),e?.processors??[]),this._shutdownOnce=new qOr.BindOnceFuture(this._shutdown,this)}getLogger(e,r,n){if(this._shutdownOnce.isCalled)return dNe.diag.warn("A shutdown LoggerProvider cannot provide a Logger"),zlo.NOOP_LOGGER;e||dNe.diag.warn("Logger requested without instrumentation scope name.");let o=e||iU.DEFAULT_LOGGER_NAME,s=`${o}@${r||""}:${n?.schemaUrl||""}`;return this._sharedState.loggers.has(s)||this._sharedState.loggers.set(s,new Klo.Logger({name:o,version:r,schemaUrl:n?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(s)}forceFlush(){return this._shutdownOnce.isCalled?(dNe.diag.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(dNe.diag.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}};iU.LoggerProvider=h_t});var zOr=T(fNe=>{"use strict";Object.defineProperty(fNe,"__esModule",{value:!0});fNe.ConsoleLogRecordExporter=void 0;var WOr=O9(),m_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,WOr.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:WOr.ExportResultCode.SUCCESS})}};fNe.ConsoleLogRecordExporter=m_t});var YOr=T(pNe=>{"use strict";Object.defineProperty(pNe,"__esModule",{value:!0});pNe.SimpleLogRecordProcessor=void 0;var lX=O9(),g_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()}};pNe.SimpleLogRecordProcessor=g_t});var XOr=T(hNe=>{"use strict";Object.defineProperty(hNe,"__esModule",{value:!0});hNe.InMemoryLogRecordExporter=void 0;var KOr=O9(),A_t=class{_finishedLogRecords=[];_stopped=!1;export(e,r){if(this._stopped)return r({code:KOr.ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),r({code:KOr.ExportResultCode.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}};hNe.InMemoryLogRecordExporter=A_t});var JOr=T(mNe=>{"use strict";Object.defineProperty(mNe,"__esModule",{value:!0});mNe.BatchLogRecordProcessorBase=void 0;var Jlo=(Zt(),vt(ur)),nv=O9(),y_t=class{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,r){this._exporter=e,this._maxExportBatchSize=r?.maxExportBatchSize??(0,nv.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=r?.maxQueueSize??(0,nv.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=r?.scheduledDelayMillis??(0,nv.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY")??5e3,this._exportTimeoutMillis=r?.exportTimeoutMillis??(0,nv.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT")??3e4,this._shutdownOnce=new nv.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(Jlo.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,nv.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,nv.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=()=>nv.internal._export(this._exporter,e).then(o=>{o.code!==nv.ExportResultCode.SUCCESS&&(0,nv.globalErrorHandler)(o.error??new Error(`BatchLogRecordProcessor: log record export failed (status ${o})`))}).catch(nv.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,nv.globalErrorHandler)}};mNe.BatchLogRecordProcessorBase=y_t});var ZOr=T(gNe=>{"use strict";Object.defineProperty(gNe,"__esModule",{value:!0});gNe.BatchLogRecordProcessor=void 0;var Zlo=JOr(),__t=class extends Zlo.BatchLogRecordProcessorBase{onShutdown(){}};gNe.BatchLogRecordProcessor=__t});var ekr=T(ANe=>{"use strict";Object.defineProperty(ANe,"__esModule",{value:!0});ANe.BatchLogRecordProcessor=void 0;var euo=ZOr();Object.defineProperty(ANe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return euo.BatchLogRecordProcessor}})});var tkr=T(yNe=>{"use strict";Object.defineProperty(yNe,"__esModule",{value:!0});yNe.BatchLogRecordProcessor=void 0;var tuo=ekr();Object.defineProperty(yNe,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return tuo.BatchLogRecordProcessor}})});var rkr=T(F3=>{"use strict";Object.defineProperty(F3,"__esModule",{value:!0});F3.BatchLogRecordProcessor=F3.InMemoryLogRecordExporter=F3.SimpleLogRecordProcessor=F3.ConsoleLogRecordExporter=F3.NoopLogRecordProcessor=F3.LoggerProvider=void 0;var ruo=VOr();Object.defineProperty(F3,"LoggerProvider",{enumerable:!0,get:function(){return ruo.LoggerProvider}});var nuo=d_t();Object.defineProperty(F3,"NoopLogRecordProcessor",{enumerable:!0,get:function(){return nuo.NoopLogRecordProcessor}});var iuo=zOr();Object.defineProperty(F3,"ConsoleLogRecordExporter",{enumerable:!0,get:function(){return iuo.ConsoleLogRecordExporter}});var ouo=YOr();Object.defineProperty(F3,"SimpleLogRecordProcessor",{enumerable:!0,get:function(){return ouo.SimpleLogRecordProcessor}});var suo=XOr();Object.defineProperty(F3,"InMemoryLogRecordExporter",{enumerable:!0,get:function(){return suo.InMemoryLogRecordExporter}});var auo=tkr();Object.defineProperty(F3,"BatchLogRecordProcessor",{enumerable:!0,get:function(){return auo.BatchLogRecordProcessor}})});var Vh,nkr,Rpe,ikr,Npe,Ope,okr,skr,akr,ckr,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,kpe=te(()=>{"use strict";Vh="iflow-cli",nkr="iflow_cli.user_prompt",Rpe="iflow_cli.tool_call",ikr="iflow_cli.api_request",Npe="iflow_cli.api_error",Ope="iflow_cli.api_response",okr="iflow_cli.config",skr="iflow_cli.flash_fallback",akr="iflow_cli.next_speaker_check",ckr="iflow_cli.slash_command",lkr="iflow_cli.cli_response",ukr="iflow_cli.tool.call.count",dkr="iflow_cli.tool.call.latency",fkr="iflow_cli.mcp.tool.call.count",pkr="iflow_cli.mcp.tool.call.latency",hkr="iflow_cli.builtin.tool.call.count",mkr="iflow_cli.builtin.tool.call.latency",gkr="gen_ai.client.operation",Akr="gen_ai.client.operation.duration",ykr="gen_ai.client.token.usage",_kr="iflow_cli.session.count",Ekr="iflow_cli.file.operation.count",vkr="iflow_cli.user_request.count",bkr="iflow_cli.user_request.latency",Ckr="iflow_cli.user_experience.success",Skr="iflow_cli.user.identity",xkr="iflow_cli.scheduler.lock.error",wkr="iflow_cli.mcp.connect.count",Tkr="iflow_cli.loop.detection.count",Ikr="iflow_cli.paste.operation.count",Dkr="iflow_cli.paste.operation.latency",Rkr="iflow_cli.xinliu.web.search.count",Nkr="iflow_cli.xinliu.web.search.latency",Okr="iflow_cli.web.fetch.count",kkr="iflow_cli.web.fetch.latency"});import cuo from"os";function Bkr(){try{let t=cuo.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 Pkr=te(()=>{"use strict"});var uX,dX,fX,pX,hX,mX,gX,AX,yX,_X,pC,hC,Mkr=te(()=>{"use strict";uX="iflow_cli.cpu.usage_percentage",dX="iflow_cli.cpu.user_percentage",fX="iflow_cli.cpu.system_percentage",pX="iflow_cli.cpu.cores",hX="iflow_cli.memory.heap_used",mX="iflow_cli.memory.heap_total",gX="iflow_cli.memory.rss",AX="iflow_cli.memory.external",yX="iflow_cli.memory.system_usage_percentage",_X="iflow_cli.memory.process_usage_percentage",pC={[uX]:"CPU usage percentage",[dX]:"CPU user time percentage",[fX]:"CPU system time percentage",[pX]:"Number of CPU cores",[hX]:"Heap memory used in bytes",[mX]:"Heap memory total in bytes",[gX]:"Resident Set Size in bytes",[AX]:"External memory in bytes",[yX]:"System memory usage percentage",[_X]:"Process memory usage percentage relative to Node.js limits"},hC={[uX]:"percent",[dX]:"percent",[fX]:"percent",[pX]:"cores",[hX]:"bytes",[mX]:"bytes",[gX]:"bytes",[AX]:"bytes",[yX]:"percent",[_X]:"percent"}});import*as mC from"os";var _Ne,Fkr=te(()=>{"use strict";Mkr();_Ne=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=mC.cpus().length,this.totalSystemMemory=mC.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=mC.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=mC.platform(),r=mC.arch(),n=process.version;this.options.enableCpuMetrics&&(this.cpuUsageGauge=this.meter.createObservableGauge(uX,{description:pC[uX],unit:hC[uX]}),this.cpuUserGauge=this.meter.createObservableGauge(dX,{description:pC[dX],unit:hC[dX]}),this.cpuSystemGauge=this.meter.createObservableGauge(fX,{description:pC[fX],unit:hC[fX]}),this.cpuCoresGauge=this.meter.createObservableGauge(pX,{description:pC[pX],unit:hC[pX]}),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(hX,{description:pC[hX],unit:hC[hX]}),this.memoryHeapTotalGauge=this.meter.createObservableGauge(mX,{description:pC[mX],unit:hC[mX]}),this.memoryRssGauge=this.meter.createObservableGauge(gX,{description:pC[gX],unit:hC[gX]}),this.memoryExternalGauge=this.meter.createObservableGauge(AX,{description:pC[AX],unit:hC[AX]}),this.memorySystemUsageGauge=this.meter.createObservableGauge(yX,{description:pC[yX],unit:hC[yX]}),this.memoryProcessUsageGauge=this.meter.createObservableGauge(_X,{description:pC[_X],unit:hC[_X]}),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=mC.arch();return n==="x64"||n==="arm64"?1400*1024*1024:700*1024*1024}}});function Lkr(t,e={}){if(ENe)return ENe;let r={enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0,...e};return ENe=new _Ne(t,r),ENe}var ENe,Ukr=te(()=>{"use strict";Fkr();ENe=null});import*as EX from"os";import*as vNe from"fs";function Fd(t){let e="0.3.30",r=process.env.IFLOW_ENV||"normal",n={darwin:"macOS",win32:"Windows",linux:"Linux",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",aix:"AIX"},o=EX.platform(),s=n[o]||o,a="unknown";try{if(o==="darwin")a=EX.release();else if(o==="linux")try{if(vNe.existsSync("/etc/os-release")){let m=vNe.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="(.+)"/m);m&&(a=m[1])}}catch{a=EX.release()}else o==="win32"&&(a=EX.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:Vh,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:Bkr(),iflow_env:r,usage_mode:d}}function Qkr(){return E_t||(E_t=hde.getMeter(Vh)),E_t}function jkr(){if(Wh)return;let t=Qkr();if(t){try{Lkr(t,{enableCpuMetrics:!0,enableMemoryMetrics:!0,enableSystemInfo:!0})}catch{}v_t=t.createHistogram(ukr,{description:"Counts tool calls, tagged by function name and success.",unit:"count",valueType:xc.INT}),b_t=t.createHistogram(dkr,{description:"Latency of tool calls in milliseconds.",unit:"ms",valueType:xc.INT}),C_t=t.createHistogram(fkr,{description:"Counts MCP tool calls, tagged by function name and success.",unit:"count",valueType:xc.INT}),S_t=t.createHistogram(pkr,{description:"Latency of MCP tool calls in milliseconds.",unit:"ms",valueType:xc.INT}),x_t=t.createHistogram(hkr,{description:"Counts built-in tool calls, tagged by function name and success.",unit:"count",valueType:xc.INT}),w_t=t.createHistogram(mkr,{description:"Latency of built-in tool calls in milliseconds.",unit:"ms",valueType:xc.INT}),Bpe=t.createHistogram(gkr,{description:"Counts API requests, tagged by model and status.",unit:"count",valueType:xc.INT}),Ppe=t.createHistogram(Akr,{description:"Latency of API requests in milliseconds.",unit:"ms",valueType:xc.INT}),T_t=t.createHistogram(ykr,{description:"Counts the total number of tokens used.",unit:"tokens",valueType:xc.INT}),I_t=t.createHistogram(Ekr,{description:"Counts file operations (create, read, update).",unit:"count",valueType:xc.INT}),D_t=t.createHistogram(vkr,{description:"Counts user requests from prompt to completion.",unit:"count",valueType:xc.INT}),R_t=t.createHistogram(bkr,{description:"End-to-end latency of user requests in milliseconds.",unit:"ms",valueType:xc.INT}),N_t=t.createHistogram(Ckr,{description:"User experience success rate - counts successful user experiences including retries and fixes.",unit:"count",valueType:xc.INT}),O_t=t.createHistogram(Skr,{description:"User identity for tracking unique installations.",unit:"count",valueType:xc.INT}),k_t=t.createHistogram(xkr,{description:"Counts tool scheduler lock errors when new calls are blocked by running calls.",unit:"count",valueType:xc.INT}),B_t=t.createHistogram(wkr,{description:"Counts MCP connection attempts and their success/failure status.",unit:"count",valueType:xc.INT}),P_t=t.createHistogram(Tkr,{description:"Counts loop detection events by loop type.",unit:"count",valueType:xc.INT}),M_t=t.createHistogram(Ikr,{description:"Counts paste operations, tagged by type and success.",unit:"count",valueType:xc.INT}),F_t=t.createHistogram(Dkr,{description:"Latency of paste operations in milliseconds.",unit:"ms",valueType:xc.INT}),L_t=t.createHistogram(Rkr,{description:"Counts xinliu web search operations, tagged by success and error type.",unit:"count",valueType:xc.INT}),U_t=t.createHistogram(Nkr,{description:"Latency of xinliu web search operations in milliseconds.",unit:"ms",valueType:xc.INT}),Q_t=t.createHistogram(Okr,{description:"Counts web fetch operations, tagged by success and error type.",unit:"count",valueType:xc.INT}),j_t=t.createHistogram(kkr,{description:"Latency of web fetch operations in milliseconds.",unit:"ms",valueType:xc.INT}),Wh=!0}}function bNe(t){let e=Qkr();if(!e||!Wh)return;e.createHistogram(_kr,{description:"Count of CLI sessions started.",unit:"count",valueType:xc.INT}).record(1,Fd(t))}function Gkr(t,e,r,n,o,s){if(!v_t||!b_t||!Wh)return;let a={...Fd(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};v_t.record(1,a),b_t.record(r,{...Fd(t),function_name:e??"unknown",tool_type:s??"unknown"})}function $kr(t,e,r,n,o,s){if(!C_t||!S_t||!Wh)return;let a={...Fd(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};s&&(a.execution_context=s),C_t.record(1,a),S_t.record(r,{...Fd(t),function_name:e??"unknown",execution_context:s??"unknown"})}function qkr(t,e,r,n,o,s){if(!x_t||!w_t||!Wh)return;let a={...Fd(t),function_name:e??"unknown",success:String(n),decision:o??"unknown"};s&&(a.execution_context=s),x_t.record(1,a),w_t.record(r,{...Fd(t),function_name:e??"unknown",execution_context:s??"unknown"})}function vX(t,e,r,n){!T_t||!Wh||T_t.record(r,{...Fd(t),model:e??"unknown",type:n??"unknown"})}function Hkr(t,e,r,n,o,s,a,c){if(!Bpe||!Ppe||!Wh)return;let u={...Fd(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),Bpe.record(1,u);let d={...Fd(t),model:e??"unknown",http_status_code:String(a??200),finish_reason:s??"unknown"};c!=null&&(d.business_code=String(c)),Ppe.record(r,d)}function Vkr(t,e,r,n,o,s,a){if(!Bpe||!Ppe||!Wh)return;let c={...Fd(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)),Bpe.record(1,c);let u={...Fd(t),model:e??"unknown",http_status_code:String(s??0),error:o??"unknown"};a!=null&&(u.business_code=String(a)),Ppe.record(r,u)}function oU(t,e,r,n,o){if(!I_t||!Wh)return;let s={...Fd(t),operation:e};r!==void 0&&(s.lines=String(r)),n!==void 0&&(s.mimetype=n),o!==void 0&&(s.extension=o),I_t.record(1,s)}function Wkr(t,e,r,n,o){if(!D_t||!R_t||!Wh)return;let s={...Fd(t),prompt_id:e,success:String(n)};o&&(s.error=o),D_t.record(1,s),R_t.record(r,s)}function G_t(t,e,r=!1,n=!1,o){if(!N_t||!Wh)return;let s={...Fd(t),success:String(e),had_retries:String(r),had_fixes:String(n)};o&&(s.final_error=o),N_t.record(1,s)}function zkr(t,e){if(!O_t||!Wh)return;let r={...Fd(t),user_id:e};O_t.record(1,r)}function Ykr(t,e,r){if(!k_t||!Wh)return;let n={...Fd(t),running_calls_count:String(e)};r.forEach((o,s)=>{n[`call_${s}_name`]=o.name,n[`call_${s}_status`]=o.status}),k_t.record(1,n)}function $_t(t,e,r,n,o){if(!B_t||!Wh)return;let s={...Fd(t),server_name:e,success:String(r)};n&&(s.error_type=n),o&&(s.transport_type=o),B_t.record(1,s)}function Kkr(t,e,r){if(!P_t||!Wh)return;let n={...Fd(t),loop_type:e,prompt_id:r};P_t.record(1,n)}function CNe(t,e,r,n,o="text",s,a){if(!M_t||!F_t||!Wh)return;let c={};try{c=Fd(t)}catch{c={app_name:Vh,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),M_t.record(1,u);let d={...c,paste_type:o,text_length_range:String(r),performance_ratio:luo(e,r)};F_t.record(e,d)}function luo(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 SNe(t,e,r,n,o,s){if(!L_t||!U_t||!Wh)return;let a={...Fd(t),success:String(r)};n&&(a.error_type=n),o!==void 0&&(a.results_count=String(o)),s&&(a.query_length=String(s.length)),L_t.record(1,a),U_t.record(e,{...Fd(t),error_type:n??"none"})}function sU(t,e,r,n,o,s){if(!Q_t||!j_t||!Wh)return;let a={...Fd(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)),Q_t.record(1,a),j_t.record(e,{...Fd(t),error_type:n??"none"})}var k9,E_t,v_t,b_t,C_t,S_t,x_t,w_t,Bpe,Ppe,T_t,I_t,D_t,R_t,N_t,O_t,k_t,B_t,P_t,M_t,F_t,L_t,U_t,Q_t,j_t,Wh,L3=te(()=>{"use strict";Zt();Pkr();kpe();g_();Ukr();(function(t){t.CREATE="create",t.READ="read",t.UPDATE="update"})(k9||(k9={}));Wh=!1});var Oo,vn,ko,Bo,Ld=te(()=>{"use strict";Oo=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"})(vn||(vn={}));(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"})(ko||(ko={}));(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"})(Bo||(Bo={}))});function uuo(t){switch(t){case vn.ProceedOnce:case vn.ProceedAlways:case vn.ProceedAlwaysServer:case vn.ProceedAlwaysTool:return iv.ACCEPT;case vn.ModifyWithEditor:return iv.MODIFY;case vn.Cancel:default:return iv.REJECT}}var iv,bX,CX,SX,xX,wX,NA,TX,IX,ov,DX,xNe,RX,wNe,NN=te(()=>{"use strict";Ld();g_();(function(t){t.ACCEPT="accept",t.REJECT="reject",t.MODIFY="modify"})(iv||(iv={}));bX=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()}},CX=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()}},SX=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}},xX=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?uuo(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)}},wX=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}},NA=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}},TX=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}},IX=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"})(ov||(ov={}));DX=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}},xNe=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}},RX=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}},wNe=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,Xkr=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 aU(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 TNe=te(()=>{"use strict";});import Bx,{dirname as duo,join as q_t}from"node:path";import INe from"os";import*as Jkr from"crypto";import{fileURLToPath as fuo}from"node:url";import puo from"node:fs";import{execSync as huo}from"node:child_process";function Px(t){let e=INe.homedir();return t.startsWith(e)?t.replace(e,"~"):t}function wc(t,e=35){if(t.length<=e)return t;let n=Bx.parse(t).root,o=Bx.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 Ud(t,e){let r=Bx.resolve(t),n=Bx.resolve(e);return Bx.relative(n,r)||"."}function NX(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 B9(t){return process.platform==="win32"?t.replace(/\\([ ,;!?()[\]{}])/g,"$1"):t.replace(/\\(.)/g,"$1")}function DNe(t){return Jkr.createHash("sha256").update(t).digest("hex")}function o1(t){let e=DNe(t);return Bx.join(INe.homedir(),Xm,muo,e)}function RNe(){return Bx.join(INe.homedir(),Xm,Zkr)}function NNe(t){return Bx.join(t,Xm,Zkr)}function ONe(){if(process.env.USE_BUILTIN_RIPGREP==="0")return"rg";let t=duo(fuo(import.meta.url)),e=[q_t(t,"..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),q_t(t,"..","..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`),q_t(t,"..","..","..","vendors","ripgrep",`${process.arch}-${process.platform}`,`rg${process.platform==="win32"?".exe":""}`)];for(let r of e)try{if(puo.existsSync(r))return process.platform==="darwin"&&eBr(r),r}catch{}return e[0]}function eBr(t){if(process.platform==="darwin")try{let e=["com.apple.quarantine","CachedFileMimeType","CachedFileType","FileXRayCachedResultInEA"];for(let r of e)try{huo(`xattr -d "${r}" "${t}" 2>/dev/null`,{stdio:"ignore"})}catch{}}catch{}}function Mpe(t,e){let n=INe.platform()==="win32"?Bx.win32:Bx,o=n.relative(t,e);return!o.startsWith(`..${n.sep}`)&&o!==".."&&!n.isAbsolute(o)}var Xm,H_t,muo,Zkr,Qd=te(()=>{"use strict";Xm=".iflow",H_t="google_accounts.json",muo="tmp",Zkr="commands"});import guo from"node:path";import{promises as jLa,existsSync as tBr,readFileSync as rBr}from"node:fs";import*as nBr from"os";function iBr(){return guo.join(nBr.homedir(),Xm,H_t)}function oBr(){try{let t=iBr();if(tBr(t)){let e=rBr(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 sBr(){try{let t=iBr();if(!tBr(t))return 0;let e=rBr(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 aBr=te(()=>{"use strict";Qd();});import*as cBr from"os";import*as P9 from"fs";import*as z_t from"path";import{randomUUID as Auo}from"crypto";function _uo(){P9.existsSync(V_t)||P9.mkdirSync(V_t,{recursive:!0})}function Euo(){return P9.existsSync(W_t)&&P9.readFileSync(W_t,"utf-8").trim()||null}function vuo(t){P9.writeFileSync(W_t,t,"utf-8")}function kNe(){try{_uo();let t=Euo();return t||(t=Auo(),vuo(t)),t}catch(t){return console.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}var yuo,V_t,W_t,Y_t=te(()=>{"use strict";Qd();yuo=cBr.homedir()??"",V_t=z_t.join(yuo,Xm),W_t=z_t.join(V_t,"installation_id")});var lBr,buo,Cuo,Suo,xuo,wuo,Tuo,Iuo,Duo,Ruo,Nuo,Ouo,kuo,Buo,zh,Fpe=te(()=>{"use strict";lBr=Te(Clt(),1);NN();Xkr();TNe();aBr();Y_t();buo="start_session",Cuo="new_prompt",Suo="tool_call",xuo="api_request",wuo="api_response",Tuo="api_error",Iuo="end_session",Duo="flash_fallback",Ruo="loop_detected",Nuo="next_speaker_check",Ouo="slash_command",kuo="malformed_json_response",Buo="cli_response",zh=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:aU(e)}])}createLogEvent(e,r){let n=oBr(),o=sBr();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=kNe(),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(buo,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(Cuo,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(Suo,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(xuo,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(wuo,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(Tuo,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(Duo,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(Ruo,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(Nuo,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(Ouo,r)}logMalformedJsonResponseEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.handleLogEvent(kuo,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(Buo,r)}logEndSessionEvent(e){let r=[{iflow_cli_key:Zn.IFLOW_CLI_SESSION_ID,value:e?.session_id?.toString()??""}];this.handleLogEvent(Iuo,r,!0)}getProxyAgent(){let e=this.config?.getProxy();if(e){if(e.startsWith("http"))return new lBr.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}shutdown(){let e=new CX(this.config);this.logEndSessionEvent(e)}}});import*as uBr from"node:fs";var cU,dBr,Lpe,BNe,PNe,MNe,fBr=te(()=>{"use strict";cU=Te(fi(),1),dBr=Te(zS(),1);Lpe=class{writeStream;constructor(e){this.writeStream=uBr.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)+`
486
486
  `}shutdown(){return new Promise(e=>{this.writeStream.end(e)})}},BNe=class extends Lpe{export(e,r){let n=e.map(o=>this.serialize(o)).join("");this.writeStream.write(n,o=>{r({code:o?cU.ExportResultCode.FAILED:cU.ExportResultCode.SUCCESS,error:o||void 0})})}},PNe=class extends Lpe{export(e,r){let n=e.map(o=>this.serialize(o)).join("");this.writeStream.write(n,o=>{r({code:o?cU.ExportResultCode.FAILED:cU.ExportResultCode.SUCCESS,error:o||void 0})})}},MNe=class extends Lpe{export(e,r){let n=this.serialize(e);this.writeStream.write(n,o=>{r({code:o?cU.ExportResultCode.FAILED:cU.ExportResultCode.SUCCESS,error:o||void 0})})}getPreferredAggregationTemporality(){return dBr.AggregationTemporality.CUMULATIVE}async forceFlush(){return Promise.resolve()}}});function OA(){return OX}function Puo(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){Bf.error("Invalid OTLP endpoint URL provided:",e,r);return}}function QNe(t){if(OX)return;let e=(0,LNe.defaultResource)().merge((0,LNe.resourceFromAttributes)({[Gft]:Vh,[$ft]:process.version,"session.id":t.getSessionId()})),r=t.getTelemetryOtlpEndpoint(),n=Puo(r),o=!!n,s=t.getTelemetryOutfile(),a=[];o&&a.push(new pBr.OTLPTraceExporter({url:`${n.url}/v1/traces`})),s&&a.push(new BNe(s));let c=[];o&&n&&c.push(new mBr.OTLPLogExporter({url:`${n.url}/v1/logs`})),s&&c.push(new PNe(s));let u=[];o&&u.push(new DDe({exporter:new hBr.OTLPMetricExporter({url:`${n.url}/v1/metrics`,temporalityPreference:UNe.AggregationTemporality.DELTA}),exportIntervalMillis:2e4})),s&&u.push(new UNe.PeriodicExportingMetricReader({exporter:new MNe(s),exportIntervalMillis:1e4}));let d={resource:e,serviceName:Vh,logRecordProcessors:[],spanProcessors:[],metricReaders:[]};a.forEach(f=>{d.spanProcessors.push(new ABr.BatchSpanProcessor(f,{exportTimeoutMillis:1e4}))}),c.forEach(f=>{d.logRecordProcessors.push(new yBr.BatchLogRecordProcessor(f,{exportTimeoutMillis:1e4}))}),u.forEach(f=>{d.metricReaders.push(f)}),FNe=new gBr.NodeSDK({...d});try{FNe.start(),OX=!0,jkr()}catch(f){console.error("Error starting OpenTelemetry SDK:",f)}process.on("SIGTERM",kX),process.on("SIGINT",kX)}async function _Br(){if(OX)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 kX(){if(!(!OX||!FNe))try{zh.getInstance()?.shutdown(),await FNe.shutdown()}catch(t){console.error("Error shutting down SDK:",t)}finally{OX=!1}}var pBr,hBr,mBr,gBr,LNe,ABr,yBr,UNe,FNe,OX,jNe=te(()=>{"use strict";Zt();pBr=Te(Jht(),1),hBr=Te(imt(),1),mBr=Te(smt(),1),gBr=Te($Dr(),1);HDr();$h();LNe=Te(Byt(),1),ABr=Te(i9e(),1),yBr=Te(rkr(),1),UNe=Te(zS(),1);kpe();L3();Fpe();fBr();process.env.DEBUG?Bf.setLogger(new cde,th.DEBUG):Bf.setLogger(new cde,th.NONE);OX=!1});var EBr={};Ys(EBr,{TraceContext:()=>M9});var M9,K_t=te(()=>{"use strict";Zt();jNe();M9=class{static rootSpan=null;static tracer=yu.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?gA.with(yu.setSpan(gA.active(),n),async()=>{try{return await e()}catch(o){throw n.recordException(o),n.setStatus({code:P6.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),gA.with(yu.setSpan(gA.active(),o),async()=>{try{let s=await r();return o.setStatus({code:P6.OK}),s}catch(s){throw o.recordException(s),o.setStatus({code:P6.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 _Br()}catch{}}})(),await this.spanLock,this.spanLock=null}static getActiveSpan(){return yu.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 Upe(){let t=yu.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 ON.getCurrentSession()?.traceparent}function Qpe(t){let e=Upe();return e?{...t,traceparent:e}:t}function X_t(){return Upe()}async function lU(t,e,r){let n=yu.getTracer("iflow-cli"),{TraceContext:o}=await Promise.resolve().then(()=>(K_t(),EBr)),s=o.getRootSpan(),a;if(s){let c=yu.setSpan(gA.active(),s);a=gA.with(c,()=>n.startSpan(t,{attributes:e}))}else a=n.startSpan(t,{attributes:e});try{return await gA.with(yu.setSpan(gA.active(),a),r)}catch(c){throw a.recordException(c),a.setStatus({code:P6.ERROR,message:c instanceof Error?c.message:"Unknown error"}),c}finally{a.end()}}var uU=te(()=>{"use strict";Zt();GNe();});import{release as Muo,version as Fuo}from"os";var $Ne,ON,GNe=te(()=>{"use strict";oft();sft();uU();$Ne=class{currentSession=null;async startSession(e,r,n,o){let{model:s,tool:a}=o||{},c="iflow",u="cli",d=gSe(),f=tY(),p=`${c}.${u}.${n}.${d}`,h=T0r(d,f),m=Date.now();return this.currentSession={traceId:d,parent_observation_id:f,conversationId:n,sessionId:e,userId:r,pid:c,sceneId:u,sam:p,traceparent:h,startTime:m,model:s,tool:a},await nde("/aitrack.lifecycle.run_started",{gmkey:"AI",gokey:{pid:c,sam:p,trace_id:d,observation_id:f,model:s,tool:a,sessionId:e,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,userId:u,startTime:d}=this.currentSession,f=Date.now()-d,p=tY();await nde("/aitrack.lifecycle.run_finished",{gmkey:"AI",gokey:{pid:e,sam:r,trace_id:n,observation_id:p,parent_observation_id:o,duration:f,model:s,tool:a,sessionId:c,user_id:u}})}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,userId:f}=this.currentSession,p=tY(),h="",m="";e instanceof Error?(h=e.cause?`${e.message}:${e.cause.message}`:e.message,m=e.cause?e.cause.stack||"":e.stack||""):h=String(e);let g=Upe(),A=s;if(g){let E=g.split("-");E.length>=2&&(A=E[1])}let y={gmkey:"AI",gokey:{pid:n,sam:o,trace_id:A,observation_id:p,parent_observation_id:a,sessionId:d,user_id:f,error_msg:`${h}
487
- ${m.slice(0,2e4)}`,model:c,tool:u,toolName:r?.toolName,toolArgs:r?.toolArgs?JSON.stringify(r.toolArgs):void 0,cliVer:"0.3.29-beta.2",platform:process.platform,arch:process.arch,nodeVersion:process.version,osVersion:process.platform==="darwin"?Muo():Fuo()}};await nde("/aitrack.lifecycle.run_error",y)}getCurrentSession(){return this.currentSession}},ON=new $Ne});var vBr=T((yUa,Luo)=>{Luo.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 ah=T(ki=>{"use strict";var PX=ye("os"),yC=ye("fs"),Uuo=ye("path"),iEt=ye("child_process").spawn,Quo=ye("child_process").exec,MX=ye("child_process").execSync,juo=ye("util"),fU=process.platform,oEt=fU==="linux"||fU==="android",SBr=fU==="darwin",WNe=fU==="win32",xBr=fU==="freebsd",wBr=fU==="openbsd",TBr=fU==="netbsd",J_t=0,dU="",gC="",kN=null,AC=null,sEt=process.env.WINDIR||"C:\\Windows",Yh,BX="",jpe=[],aEt=!1,HNe="",Guo="$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ",eEt="--###START###--",bBr="--ERROR--",VNe="--###ENDCMD###--",tEt="--##ID##--",Gpe={windowsHide:!0,maxBuffer:1024*2e4,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})},zNe={maxBuffer:1024*2e4,encoding:"UTF-8",stdio:["pipe","pipe","ignore"]};function $uo(t){let e=parseInt(t,10);return isNaN(e)&&(e=0),e}function quo(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 qNe=new String,rEt=new String().replace,nEt=new String().toLowerCase,IBr=new String().toString,DBr=new String().substr,RBr=new String().substring,NBr=new String().trim,OBr=new String().startsWith,kBr=Math.min;function Huo(t){return t&&{}.toString.call(t)==="[object Function]"}function Vuo(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 Wuo(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 zuo(){return J_t===0&&(J_t=PX.cpus().length),J_t}function BN(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 Yuo(t,e){return e=e||16,t.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],e))})}function Kuo(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 Xuo(t,e){e=e||"",t=t.toUpperCase();let r=0,n=0,o=Kuo(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 Juo(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=Xuo(a,o)}return r}function Zuo(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 edo(t,e,r){for(let n=0;n<t.length;n++)if(t[n][e]===r)return n;return-1}function tdo(){if(HNe="powershell.exe",WNe){let t=`${sEt}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;yC.existsSync(t)&&(HNe=t)}}function BBr(){if(PX.type()==="Windows_NT"&&!dU&&(dU=sEt+"\\system32\\wbem\\wmic.exe",!yC.existsSync(dU)))try{let t=MX("WHERE WMIC",Gpe).toString().split(`\r
487
+ ${m.slice(0,2e4)}`,model:c,tool:u,toolName:r?.toolName,toolArgs:r?.toolArgs?JSON.stringify(r.toolArgs):void 0,cliVer:"0.3.30",platform:process.platform,arch:process.arch,nodeVersion:process.version,osVersion:process.platform==="darwin"?Muo():Fuo()}};await nde("/aitrack.lifecycle.run_error",y)}getCurrentSession(){return this.currentSession}},ON=new $Ne});var vBr=T((yUa,Luo)=>{Luo.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 ah=T(ki=>{"use strict";var PX=ye("os"),yC=ye("fs"),Uuo=ye("path"),iEt=ye("child_process").spawn,Quo=ye("child_process").exec,MX=ye("child_process").execSync,juo=ye("util"),fU=process.platform,oEt=fU==="linux"||fU==="android",SBr=fU==="darwin",WNe=fU==="win32",xBr=fU==="freebsd",wBr=fU==="openbsd",TBr=fU==="netbsd",J_t=0,dU="",gC="",kN=null,AC=null,sEt=process.env.WINDIR||"C:\\Windows",Yh,BX="",jpe=[],aEt=!1,HNe="",Guo="$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ",eEt="--###START###--",bBr="--ERROR--",VNe="--###ENDCMD###--",tEt="--##ID##--",Gpe={windowsHide:!0,maxBuffer:1024*2e4,encoding:"UTF-8",env:Object.assign({},process.env,{LANG:"en_US.UTF-8"})},zNe={maxBuffer:1024*2e4,encoding:"UTF-8",stdio:["pipe","pipe","ignore"]};function $uo(t){let e=parseInt(t,10);return isNaN(e)&&(e=0),e}function quo(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 qNe=new String,rEt=new String().replace,nEt=new String().toLowerCase,IBr=new String().toString,DBr=new String().substr,RBr=new String().substring,NBr=new String().trim,OBr=new String().startsWith,kBr=Math.min;function Huo(t){return t&&{}.toString.call(t)==="[object Function]"}function Vuo(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 Wuo(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 zuo(){return J_t===0&&(J_t=PX.cpus().length),J_t}function BN(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 Yuo(t,e){return e=e||16,t.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],e))})}function Kuo(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 Xuo(t,e){e=e||"",t=t.toUpperCase();let r=0,n=0,o=Kuo(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 Juo(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=Xuo(a,o)}return r}function Zuo(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 edo(t,e,r){for(let n=0;n<t.length;n++)if(t[n][e]===r)return n;return-1}function tdo(){if(HNe="powershell.exe",WNe){let t=`${sEt}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;yC.existsSync(t)&&(HNe=t)}}function BBr(){if(PX.type()==="Windows_NT"&&!dU&&(dU=sEt+"\\system32\\wbem\\wmic.exe",!yC.existsSync(dU)))try{let t=MX("WHERE WMIC",Gpe).toString().split(`\r
488
488
  `);t&&t.length?dU=t[0]:dU="wmic"}catch{dU="wmic"}return dU}function rdo(t){return new Promise(e=>{process.nextTick(()=>{try{PBr(BBr()+" "+t).then(r=>{e(r,"")})}catch(r){e("",r)}})})}function ndo(){return WNe?`"${process.env.VBOX_INSTALL_PATH||process.env.VBOX_MSI_INSTALL_PATH}\\VBoxManage.exe"`:"vboxmanage"}function Z_t(t){let e="",r,n="";if(t.indexOf(eEt)>=0){r=t.split(eEt);let s=r[1].split(tEt);e=s[0],s.length>1&&(t=s.slice(1).join(tEt))}t.indexOf(VNe)>=0&&(r=t.split(VNe),n=r[0]);let o=-1;for(let s=0;s<jpe.length;s++)jpe[s].id===e&&(o=s,jpe[s].callback(n));o>=0&&jpe.splice(o,1)}function ido(){Yh||(Yh=iEt(HNe,["-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"})}),Yh&&Yh.pid&&(aEt=!0,Yh.stdout.on("data",function(t){BX=BX+t.toString("utf8"),t.indexOf(VNe)>=0&&(Z_t(BX),BX="")}),Yh.stderr.on("data",function(){Z_t(BX+bBr)}),Yh.on("error",function(){Z_t(BX+bBr)}),Yh.on("close",function(){Yh&&Yh.kill()})))}function odo(){try{Yh&&(Yh.stdin.write("exit"+PX.EOL),Yh.stdin.end(),aEt=!1)}catch{Yh&&Yh.kill()}Yh=null}function PBr(t){if(aEt){let e=Math.random().toString(36).substring(2,12);return new Promise(r=>{process.nextTick(()=>{function n(o){r(o)}jpe.push({id:e,cmd:t,callback:n,start:new Date});try{Yh&&Yh.pid&&Yh.stdin.write(Guo+"echo "+eEt+e+tEt+"; "+PX.EOL+t+PX.EOL+"echo "+VNe+PX.EOL)}catch{r("")}})})}else{let e="";return new Promise(r=>{process.nextTick(()=>{try{let n=iEt(HNe,["-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 sdo(t,e,r){let n="";return r=r||{},new Promise(o=>{process.nextTick(()=>{try{let s=iEt(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 ado(){if(WNe){if(!gC)try{let r=MX("chcp",Gpe).toString().split(`\r
489
489
  `)[0].split(":");gC=r.length>1?r[1].replace(".","").trim():""}catch{gC="437"}return gC}if(oEt||SBr||xBr||wBr||TBr){if(!gC)try{let r=MX("echo $LANG",zNe).toString().split(`\r
490
490
  `)[0].split(".");gC=r.length>1?r[1].trim():"",gC||(gC="UTF-8")}catch{gC="UTF-8"}return gC}}function cdo(){if(kN!==null)return kN;if(kN=!1,WNe)try{let t=MX("WHERE smartctl 2>nul",Gpe).toString().split(`\r
@@ -934,7 +934,7 @@ ${JSON.stringify(e,null,2)}`;try{let o=NMr.dirname(this.logFilePath);await RMr.m
934
934
  [${new Date().toISOString()}]
935
935
  ${n}
936
936
  ${"=".repeat(80)}
937
- `;await RMr.appendFile(this.logFilePath,a,"utf-8")}catch(o){console.debug(N.t("openaiContentGenerator.errors.failedWriteDebugLog"),o)}}logTelemetryFailure(e,r){let n=r instanceof Error&&r.message?r.message:String(r);Q3(new Error(`${e}: ${n}`))}async generateContent(e,r){let n={"model.name":this.modelName,"model.provider":"openai","api.endpoint":`${this.baseUrl}/chat/completions`};return lU("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=yu.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=yu.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=yu.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=q9.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 lSe();let{getCachedApiKey:k}=await Promise.resolve().then(()=>(jR(),Kdt)),L=await k();L&&(this.apiKey=L)}let c=await this.convertToOpenAIMessages(e),u=SMr(c);if(this.config){let O=this.config.getConversationId();if(O)try{await WEt(this.config,O,{model:this.modelName,tool:u})}catch(k){this.logTelemetryFailure("Telemetry initialization failed",k)}}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?(jOe.configureThinkingRequest(this.modelName,f,h.thinking)||console.debug(`Model ${this.modelName} does not support thinking mode`),h.thinking=null):jOe.configureNonThinkingRequest(this.modelName,f);let m=await this.calculateInputTokens(e),g=ZEt(this.modelName,m),A="global";A==="aone"&&(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(O=>y.includes(O))&&(f.extend_fields={sessionId:this.config?.getSessionId()||""});let v=Date.now(),b=X_t(),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.3.29-beta.2"}),OOe(this.config,new wX(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 O=await w.text();if(this.config)try{await TOe(this.config,new Error(O)),j3(this.config,new NA(this.modelName,O,R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"http_error",w.status,w.status,void 0))}catch(k){this.logTelemetryFailure("Telemetry error recording failed",k)}throw w.status===511?(this.config&&j3(this.config,new NA(this.modelName,"Content length exceeded",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",511,200,511)),new Error(N.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:b||w.headers.get("eagleeye-traceid")}))):w.status===514?(this.config&&j3(this.config,new NA(this.modelName,"model_error",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(N.t("openaiContentGenerator.errors.modelError",{traceId:b||w.headers.get("eagleeye-traceid")}))):w.status===429?(this.config&&j3(this.config,new NA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",429,200,429)),new Error(N.t("openaiContentGenerator.errors.modelRateLimitReached"))):new Error(N.t("openaiContentGenerator.errors.httpError",{status:w.status,body:O,traceId:b||w.headers.get("eagleeye-traceid")}))}let D;try{D=await w.json()}catch(O){throw Q3(O),new Error(N.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&&j3(this.config,new NA(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(N.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:b||w.headers.get("eagleeye-traceid")}));if(D.error_code&&D.error_code===514)throw this.config&&j3(this.config,new NA(this.modelName,"model_error",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(N.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&&j3(this.config,new NA(this.modelName,"API token expired",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"token_expired",439,200,439)),new Error(N.t("openaiContentGenerator.errors.apiTokenExpired"));if(D.msg&&(D.msg.includes("invalid apiKey")||D.msg.includes("Invalid apiKey")))throw new Error(N.t("openaiContentGenerator.errors.invalidApiKey"));if(D.status&&(D.status==="434"||D.status===434))throw this.config&&j3(this.config,new NA(this.modelName,"Invalid API key",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"invalid_api_key",434,200,434)),new Error(N.t("openaiContentGenerator.errors.invalidApiKey"));if(D.status&&(D.status==="435"||D.status===435))throw this.config&&j3(this.config,new NA(this.modelName,"Model Not Support",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"Model Not Support",435,200,435)),new Error(N.t("openaiContentGenerator.errors.modelNotSupport"));if(D.status&&D.status==="429"||D.error_code&&(D.error_code===429||D.error_code===8211))throw this.config&&j3(this.config,new NA(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(N.t("openaiContentGenerator.errors.modelRateLimitReached"));if(D.status&&D.status==="449"||D.error_code&&D.error_code===449)throw this.config&&j3(this.config,new NA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",449,200,449)),new Error(N.t("openaiContentGenerator.errors.rateLimitReached"));if(e.config?.abortSignal?.aborted)throw new Error(N.t("openaiContentGenerator.errors.userCancel"));if(!D||!D.choices||!Array.isArray(D.choices)||D.choices.length===0){let O=b||w.headers.get("eagleeye-traceid");throw new Error(N.t("openaiContentGenerator.errors.invalidResponseFormat",{traceId:O}))}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:P,hadJsonFixes:I}=await this.convertFromOpenAIResponse(D);if(a=I,o){let O=D.choices[0]?.finish_reason,k=D.error_code;o(200,k,O,D)}if(this.config)try{let O=D.choices[0]?.finish_reason;BOe(this.config,new TX(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,O,200,void 0)),await uhe(this.config),G_t(this.config,!0,!1,a)}catch(O){this.logTelemetryFailure("Telemetry cleanup failed",O)}return P}catch(c){if(Q3(c),this.config&&!(c instanceof Error&&c.message==="user cancel")&&c?.name!=="AbortError"&&(await TOe(this.config,c instanceof Error?c:new Error(String(c))),G_t(this.config,!1,!1,a,c instanceof Error?c.message:String(c))),c instanceof Error&&c.cause?.name?.includes("InvalidArgumentError"))throw new Error(N.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(N.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 Q3(r),new Error(N.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("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:N.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&&$9.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(N.t("openaiContentGenerator.errors.imageDataMissing"));let m=await this.multimodalHelper.generateImageDescription(f.data,f.mimeType);u.push({type:"text",text:`[Image Description]: ${m}`})}catch(m){Q3(m),u.push({type:"text",text:N.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(Q3(u),this.baseUrl==="https://apis.iflow.cn/v1")try{c=await this.fixInvalidJsonWithQwen(a.function.arguments),s=!0}catch(d){Q3(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
+ `;await RMr.appendFile(this.logFilePath,a,"utf-8")}catch(o){console.debug(N.t("openaiContentGenerator.errors.failedWriteDebugLog"),o)}}logTelemetryFailure(e,r){let n=r instanceof Error&&r.message?r.message:String(r);Q3(new Error(`${e}: ${n}`))}async generateContent(e,r){let n={"model.name":this.modelName,"model.provider":"openai","api.endpoint":`${this.baseUrl}/chat/completions`};return lU("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=yu.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=yu.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=yu.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=q9.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 lSe();let{getCachedApiKey:k}=await Promise.resolve().then(()=>(jR(),Kdt)),L=await k();L&&(this.apiKey=L)}let c=await this.convertToOpenAIMessages(e),u=SMr(c);if(this.config){let O=this.config.getConversationId();if(O)try{await WEt(this.config,O,{model:this.modelName,tool:u})}catch(k){this.logTelemetryFailure("Telemetry initialization failed",k)}}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?(jOe.configureThinkingRequest(this.modelName,f,h.thinking)||console.debug(`Model ${this.modelName} does not support thinking mode`),h.thinking=null):jOe.configureNonThinkingRequest(this.modelName,f);let m=await this.calculateInputTokens(e),g=ZEt(this.modelName,m),A="global";A==="aone"&&(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(O=>y.includes(O))&&(f.extend_fields={sessionId:this.config?.getSessionId()||""});let v=Date.now(),b=X_t(),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.3.30"}),OOe(this.config,new wX(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 O=await w.text();if(this.config)try{await TOe(this.config,new Error(O)),j3(this.config,new NA(this.modelName,O,R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"http_error",w.status,w.status,void 0))}catch(k){this.logTelemetryFailure("Telemetry error recording failed",k)}throw w.status===511?(this.config&&j3(this.config,new NA(this.modelName,"Content length exceeded",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"content_length_exceed",511,200,511)),new Error(N.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:b||w.headers.get("eagleeye-traceid")}))):w.status===514?(this.config&&j3(this.config,new NA(this.modelName,"model_error",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(N.t("openaiContentGenerator.errors.modelError",{traceId:b||w.headers.get("eagleeye-traceid")}))):w.status===429?(this.config&&j3(this.config,new NA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",429,200,429)),new Error(N.t("openaiContentGenerator.errors.modelRateLimitReached"))):new Error(N.t("openaiContentGenerator.errors.httpError",{status:w.status,body:O,traceId:b||w.headers.get("eagleeye-traceid")}))}let D;try{D=await w.json()}catch(O){throw Q3(O),new Error(N.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&&j3(this.config,new NA(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(N.t("openaiContentGenerator.errors.contentLengthExceed",{traceId:b||w.headers.get("eagleeye-traceid")}));if(D.error_code&&D.error_code===514)throw this.config&&j3(this.config,new NA(this.modelName,"model_error",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"model_error",514,200,514)),new Error(N.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&&j3(this.config,new NA(this.modelName,"API token expired",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"token_expired",439,200,439)),new Error(N.t("openaiContentGenerator.errors.apiTokenExpired"));if(D.msg&&(D.msg.includes("invalid apiKey")||D.msg.includes("Invalid apiKey")))throw new Error(N.t("openaiContentGenerator.errors.invalidApiKey"));if(D.status&&(D.status==="434"||D.status===434))throw this.config&&j3(this.config,new NA(this.modelName,"Invalid API key",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"invalid_api_key",434,200,434)),new Error(N.t("openaiContentGenerator.errors.invalidApiKey"));if(D.status&&(D.status==="435"||D.status===435))throw this.config&&j3(this.config,new NA(this.modelName,"Model Not Support",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"Model Not Support",435,200,435)),new Error(N.t("openaiContentGenerator.errors.modelNotSupport"));if(D.status&&D.status==="429"||D.error_code&&(D.error_code===429||D.error_code===8211))throw this.config&&j3(this.config,new NA(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(N.t("openaiContentGenerator.errors.modelRateLimitReached"));if(D.status&&D.status==="449"||D.error_code&&D.error_code===449)throw this.config&&j3(this.config,new NA(this.modelName,"Rate limit reached",R,this.config.getSessionId()||"unknown",this.config.getContentGeneratorConfig()?.authType,"rate_limit",449,200,449)),new Error(N.t("openaiContentGenerator.errors.rateLimitReached"));if(e.config?.abortSignal?.aborted)throw new Error(N.t("openaiContentGenerator.errors.userCancel"));if(!D||!D.choices||!Array.isArray(D.choices)||D.choices.length===0){let O=b||w.headers.get("eagleeye-traceid");throw new Error(N.t("openaiContentGenerator.errors.invalidResponseFormat",{traceId:O}))}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:P,hadJsonFixes:I}=await this.convertFromOpenAIResponse(D);if(a=I,o){let O=D.choices[0]?.finish_reason,k=D.error_code;o(200,k,O,D)}if(this.config)try{let O=D.choices[0]?.finish_reason;BOe(this.config,new TX(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,O,200,void 0)),await uhe(this.config),G_t(this.config,!0,!1,a)}catch(O){this.logTelemetryFailure("Telemetry cleanup failed",O)}return P}catch(c){if(Q3(c),this.config&&!(c instanceof Error&&c.message==="user cancel")&&c?.name!=="AbortError"&&(await TOe(this.config,c instanceof Error?c:new Error(String(c))),G_t(this.config,!1,!1,a,c instanceof Error?c.message:String(c))),c instanceof Error&&c.cause?.name?.includes("InvalidArgumentError"))throw new Error(N.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(N.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 Q3(r),new Error(N.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("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:N.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&&$9.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(N.t("openaiContentGenerator.errors.imageDataMissing"));let m=await this.multimodalHelper.generateImageDescription(f.data,f.mimeType);u.push({type:"text",text:`[Image Description]: ${m}`})}catch(m){Q3(m),u.push({type:"text",text:N.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(Q3(u),this.baseUrl==="https://apis.iflow.cn/v1")try{c=await this.fixInvalidJsonWithQwen(a.function.arguments),s=!0}catch(d){Q3(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=`
938
938
  \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
939
939
  \u8FD9\u4E2A\u662F\u9519\u8BEF\u7684json\u683C\u5F0F\uFF1A
940
940
  ${e}
@@ -947,7 +947,7 @@ Otherwise navigate to:
947
947
 
948
948
  ${e}
949
949
 
950
- `);try{(await hA(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 tFr(r.pollInterval);let o=await rFr(t,r);if(o.isSuccess()){let s=o.getPrivateToken();return await H9.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 YOe(t=new aJ){return await H9.hasValidToken()?(console.log("Using cached Aone authentication."),!0):await nFr(t)}async function Qx(){return await H9.loadPrivateToken()}async function KOe(){await H9.clearPrivateToken(),console.log("Aone authentication cleared.")}async function $mo(){return await H9.hasValidToken()}async function qmo(t=new aJ){return await KOe(),await YOe(t)}var XOe=te(()=>{"use strict";c6t();i9();JMr();ZMr();eFr();});async function l6t(t,e,r,n){if(e===Yt.LOGIN_WITH_IFLOW){let o=await jF(e,r),s=await H4();if(!s)throw new Error("No API key found. Please re-authenticate.");let a=r.getContentGeneratorConfig();return new bU({model:r.getModel(),apiKey:s,baseUrl:a?.baseUrl||mhe,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen3-vl-plus",config:r})}if(e===Yt.LOGIN_WITH_AONE){if(!await YOe())throw new Error("Aone authentication failed. Please try again.");let s=await Qx();if(!s)throw new Error("No Aone private token found. Please re-authenticate.");let a=r.getContentGeneratorConfig(),c=Buffer.from(s,"utf8").toString("base64");return new bU({model:r.getModel(),apiKey:c,baseUrl:a?.baseUrl||"https://ducky.code.alibaba-inc.com/v1/openai",authType:e,debugMode:r.getDebugMode(),multimodalModelName:a?.multimodalModelName,config:r})}if(e===Yt.CLOUD_SHELL){let o=await jF(e,r),s=await S0r(o);return new l9(o,s.projectId,t,n,s.userTier)}throw new Error(`Unsupported authType: ${e}`)}var u6t=te(()=>{"use strict";g_();jR();x0r();hSe();t6t();CC();XOe();});function Hmo(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function jx(t){let e=Hmo(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 _he(){return jx("apiKey")}function Ehe(){return jx("baseUrl")||jx("url")}function vhe(){return jx("modelName")||jx("model")}function iFr(t){let e=jx(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 oFr(t){let e=jx(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function sFr(t){let e=jx(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function JOe(){return!!(_he()||Ehe()||vhe())}function d6t(){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=jx(s);a!==void 0&&(t[s]=a)}),r.forEach(s=>{let a=iFr(s);a!==void 0&&(t[s]=a)}),n.forEach(s=>{let a=oFr(s);a!==void 0&&(t[s]=a)}),o.forEach(s=>{let a=sFr(s);a!==void 0&&(t[s]=a)}),t}function Vmo(){return{apiKey:_he(),baseUrl:Ehe(),model:vhe()}}var f6t=te(()=>{"use strict";});async function p6t(t,e,r){if(await Jz())try{await uSe()||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=_he(),s=Ehe(),a=vhe(),c=r?.apiKey||o,u=r?.baseUrl||s||Wmo[e],d=r?.modelName||t.getModel()||a||R_,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||mhe,f.multimodalModelName="qwen3-vl-plus",c&&(f.apiKey=c),f):([...N_,Yt.OPENAI_COMPATIBLE].includes(e)&&c&&(f.apiKey=c,f.baseUrl=u,f.model=d),f)}async function h6t(t,e,r){let o={headers:{"User-Agent":`iFlowCLI/0.3.29-beta.2 (${process.platform}; ${process.arch})`}};if(t.authType&&[...N_,Yt.IDEA_LAB].includes(t.authType)||t.authType===Yt.OPENAI_COMPATIBLE)return new bU({...t,config:e});if(t.authType===Yt.LOGIN_WITH_IFLOW||t.authType===Yt.LOGIN_WITH_AONE||t.authType===Yt.CLOUD_SHELL)return l6t(o,t.authType,e,r);throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var Yt,N_,Wmo,g_=te(()=>{"use strict";u6t();CC();t6t();f6t();jR();(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={}));N_=[Yt.IFLOW,Yt.AONE],Wmo={[Yt.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[Yt.IFLOW]:mhe,[Yt.AONE]:OMr}});var ZOe,aFr=te(()=>{"use strict";ZOe=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 an,O_=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"})(an||(an={}))});function zmo(t){return{text:t.text}}function Ymo(t,e){return[{text:N.t("mcpTool.messages.mediaDataProvided",{toolName:e,type:t.type,mimeType:t.mimeType})},{inlineData:{mimeType:t.mimeType,data:t.data}}]}function Kmo(t,e){let r=t.resource;if(r?.text)return{text:r.text};if(r?.blob){let n=r.mimeType||"application/octet-stream";return[{text:N.t("mcpTool.messages.embeddedResourceProvided",{toolName:e,mimeType:n})},{inlineData:{mimeType:n,data:r.blob}}]}return null}function Xmo(t){return{text:N.t("mcpTool.messages.resourceLink",{title:t.title||t.name,uri:t.uri})}}function Jmo(t){let e=t?.[0]?.functionResponse,r=e?.response?.content,n=e?.name||"unknown tool";return Array.isArray(r)?r.flatMap(s=>{switch(s.type){case"text":return zmo(s);case"image":case"audio":return Ymo(s,n);case"resource":return Kmo(s,n);case"resource_link":return Xmo(s);default:return null}}).filter(s=>s!==null):[{text:N.t("mcpTool.errors.parseResponseFailed")}]}function Zmo(t){let e=t?.[0]?.functionResponse?.response?.content;return Array.isArray(e)?e.map(n=>{switch(n.type){case"text":return n.text;case"image":return N.t("mcpTool.display.image",{mimeType:n.mimeType});case"audio":return N.t("mcpTool.display.audio",{mimeType:n.mimeType});case"resource_link":return N.t("mcpTool.display.resourceLink",{title:n.title||n.name,uri:n.uri});case"resource":return n.resource?.text?n.resource.text:N.t("mcpTool.display.embeddedResource",{mimeType:n.resource?.mimeType||N.t("mcpTool.display.unknownType")});default:return N.t("mcpTool.display.unknownContentType",{type:n.type})}}).join(`
950
+ `);try{(await hA(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 tFr(r.pollInterval);let o=await rFr(t,r);if(o.isSuccess()){let s=o.getPrivateToken();return await H9.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 YOe(t=new aJ){return await H9.hasValidToken()?(console.log("Using cached Aone authentication."),!0):await nFr(t)}async function Qx(){return await H9.loadPrivateToken()}async function KOe(){await H9.clearPrivateToken(),console.log("Aone authentication cleared.")}async function $mo(){return await H9.hasValidToken()}async function qmo(t=new aJ){return await KOe(),await YOe(t)}var XOe=te(()=>{"use strict";c6t();i9();JMr();ZMr();eFr();});async function l6t(t,e,r,n){if(e===Yt.LOGIN_WITH_IFLOW){let o=await jF(e,r),s=await H4();if(!s)throw new Error("No API key found. Please re-authenticate.");let a=r.getContentGeneratorConfig();return new bU({model:r.getModel(),apiKey:s,baseUrl:a?.baseUrl||mhe,authType:e,debugMode:r.getDebugMode(),multimodalModelName:"qwen3-vl-plus",config:r})}if(e===Yt.LOGIN_WITH_AONE){if(!await YOe())throw new Error("Aone authentication failed. Please try again.");let s=await Qx();if(!s)throw new Error("No Aone private token found. Please re-authenticate.");let a=r.getContentGeneratorConfig(),c=Buffer.from(s,"utf8").toString("base64");return new bU({model:r.getModel(),apiKey:c,baseUrl:a?.baseUrl||"https://ducky.code.alibaba-inc.com/v1/openai",authType:e,debugMode:r.getDebugMode(),multimodalModelName:a?.multimodalModelName,config:r})}if(e===Yt.CLOUD_SHELL){let o=await jF(e,r),s=await S0r(o);return new l9(o,s.projectId,t,n,s.userTier)}throw new Error(`Unsupported authType: ${e}`)}var u6t=te(()=>{"use strict";g_();jR();x0r();hSe();t6t();CC();XOe();});function Hmo(t){return t.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}function jx(t){let e=Hmo(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 _he(){return jx("apiKey")}function Ehe(){return jx("baseUrl")||jx("url")}function vhe(){return jx("modelName")||jx("model")}function iFr(t){let e=jx(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 oFr(t){let e=jx(t);if(e===void 0)return;let r=Number(e);return isNaN(r)?void 0:r}function sFr(t){let e=jx(t);if(e!==void 0)return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function JOe(){return!!(_he()||Ehe()||vhe())}function d6t(){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=jx(s);a!==void 0&&(t[s]=a)}),r.forEach(s=>{let a=iFr(s);a!==void 0&&(t[s]=a)}),n.forEach(s=>{let a=oFr(s);a!==void 0&&(t[s]=a)}),o.forEach(s=>{let a=sFr(s);a!==void 0&&(t[s]=a)}),t}function Vmo(){return{apiKey:_he(),baseUrl:Ehe(),model:vhe()}}var f6t=te(()=>{"use strict";});async function p6t(t,e,r){if(await Jz())try{await uSe()||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=_he(),s=Ehe(),a=vhe(),c=r?.apiKey||o,u=r?.baseUrl||s||Wmo[e],d=r?.modelName||t.getModel()||a||R_,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||mhe,f.multimodalModelName="qwen3-vl-plus",c&&(f.apiKey=c),f):([...N_,Yt.OPENAI_COMPATIBLE].includes(e)&&c&&(f.apiKey=c,f.baseUrl=u,f.model=d),f)}async function h6t(t,e,r){let o={headers:{"User-Agent":`iFlowCLI/0.3.30 (${process.platform}; ${process.arch})`}};if(t.authType&&[...N_,Yt.IDEA_LAB].includes(t.authType)||t.authType===Yt.OPENAI_COMPATIBLE)return new bU({...t,config:e});if(t.authType===Yt.LOGIN_WITH_IFLOW||t.authType===Yt.LOGIN_WITH_AONE||t.authType===Yt.CLOUD_SHELL)return l6t(o,t.authType,e,r);throw new Error(`Error creating contentGenerator: Unsupported authType: ${t.authType}`)}var Yt,N_,Wmo,g_=te(()=>{"use strict";u6t();CC();t6t();f6t();jR();(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={}));N_=[Yt.IFLOW,Yt.AONE],Wmo={[Yt.IDEA_LAB]:"https://idealab.alibaba-inc.com/api/openai/v1",[Yt.IFLOW]:mhe,[Yt.AONE]:OMr}});var ZOe,aFr=te(()=>{"use strict";ZOe=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 an,O_=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"})(an||(an={}))});function zmo(t){return{text:t.text}}function Ymo(t,e){return[{text:N.t("mcpTool.messages.mediaDataProvided",{toolName:e,type:t.type,mimeType:t.mimeType})},{inlineData:{mimeType:t.mimeType,data:t.data}}]}function Kmo(t,e){let r=t.resource;if(r?.text)return{text:r.text};if(r?.blob){let n=r.mimeType||"application/octet-stream";return[{text:N.t("mcpTool.messages.embeddedResourceProvided",{toolName:e,mimeType:n})},{inlineData:{mimeType:n,data:r.blob}}]}return null}function Xmo(t){return{text:N.t("mcpTool.messages.resourceLink",{title:t.title||t.name,uri:t.uri})}}function Jmo(t){let e=t?.[0]?.functionResponse,r=e?.response?.content,n=e?.name||"unknown tool";return Array.isArray(r)?r.flatMap(s=>{switch(s.type){case"text":return zmo(s);case"image":case"audio":return Ymo(s,n);case"resource":return Kmo(s,n);case"resource_link":return Xmo(s);default:return null}}).filter(s=>s!==null):[{text:N.t("mcpTool.errors.parseResponseFailed")}]}function Zmo(t){let e=t?.[0]?.functionResponse?.response?.content;return Array.isArray(e)?e.map(n=>{switch(n.type){case"text":return n.text;case"image":return N.t("mcpTool.display.image",{mimeType:n.mimeType});case"audio":return N.t("mcpTool.display.audio",{mimeType:n.mimeType});case"resource_link":return N.t("mcpTool.display.resourceLink",{title:n.title||n.name,uri:n.uri});case"resource":return n.resource?.text?n.resource.text:N.t("mcpTool.display.embeddedResource",{mimeType:n.resource?.mimeType||N.t("mcpTool.display.unknownType")});default:return N.t("mcpTool.display.unknownContentType",{type:n.type})}}).join(`
951
951
  `):"```json\n"+JSON.stringify(t,null,2)+"\n```"}function cFr(t){let e=t.replace(/[^a-zA-Z0-9_.-]/g,"_");return e.length>63&&(e=e.slice(0,28)+"___"+e.slice(-32)),e}var d0,bhe=te(()=>{"use strict";TNe();O_();Ld();qc();yi();d0=class t extends Oo{mcpTool;serverName;serverToolName;parameterSchemaJson;timeout;trust;static allowlist=new Set;constructor(e,r,n,o,s,a,c,u){super(u??cFr(n),`${n} (${r} MCP Server)`,o,ko.Hammer,Bo.Other,{type:pr.OBJECT},!0,!1),this.mcpTool=e,this.serverName=r,this.serverToolName=n,this.parameterSchemaJson=s,this.timeout=a,this.trust=c}asFullyQualifiedTool(){return new t(this.mcpTool,this.serverName,this.serverToolName,this.description,this.parameterSchemaJson,this.timeout,this.trust,`${this.serverName}__${this.serverToolName}`)}get schema(){return{name:this.name,description:this.description,parametersJsonSchema:this.parameterSchemaJson}}async shouldConfirmExecute(e,r){let n=this.serverName,o=`${this.serverName}.${this.serverToolName}`;return this.trust||t.allowlist.has(n)||t.allowlist.has(o)?!1:{type:"mcp",title:N.t("mcpTool.messages.confirmExecution"),serverName:this.serverName,toolName:this.serverToolName,toolDisplayName:this.name,onConfirm:async a=>{a===vn.ProceedAlwaysServer?t.allowlist.add(n):a===vn.ProceedAlwaysTool&&t.allowlist.add(o)}}}isMCPToolError(e){let n=e?.[0]?.functionResponse?.response;if(n){let o=n?.error,s=o?.isError;if(o&&(s===!0||s==="true"))return!0}return!1}async execute(e){let{callId:r,...n}=e,o=[{name:this.serverToolName,args:n}],s=await this.mcpTool.callTool(o);if(this.isMCPToolError(s)){let c=`MCP tool '${this.serverToolName}' reported tool error for function call: ${aU(o[0])} with response: ${aU(s)}`;return{llmContent:c,returnDisplay:N.t("mcpTool.errors.toolReportedError",{toolName:this.serverToolName}),error:{message:c,type:an.MCP_TOOL_ERROR}}}return{llmContent:Jmo(s),returnDisplay:Zmo(s)}}}});var uFr=T((cGa,lFr)=>{"use strict";lFr.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 AFr=T((lGa,gFr)=>{"use strict";var mFr="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",dFr=new RegExp("^"+mFr+"$"),fFr="|&;()<> \\t",ego='"((\\\\"|[^"])*?)"',tgo="'((\\\\'|[^'])*?)'",rgo=/^#$/,pFr="'",hFr='"',m6t="$",CU="",ngo=4294967296;for(g6t=0;g6t<4;g6t++)CU+=(ngo*Math.random()).toString(16);var g6t,igo=new RegExp("^"+CU);function ogo(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 sgo(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+CU+JSON.stringify(n)+CU:e+n}function ago(t,e,r){r||(r={});var n=r.escape||"\\",o="(\\"+n+`['"`+fFr+`]|[^\\s'"`+fFr+"])+",s=new RegExp(["("+mFr+")","("+o+"|"+ego+"|"+tgo+")+"].join("|"),"g"),a=ogo(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(dFr.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 sgo(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==pFr?h+=y:y===n?(g+=1,y=d.charAt(g),y===hFr||y===n||y===m6t?h+=y:h+=n+y):y===m6t?h+=A():h+=y;else if(y===hFr||y===pFr)f=y;else{if(dFr.test(y))return{op:d};if(rgo.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===m6t?h+=A():h+=y}}return m?{op:"glob",pattern:h}:h}).reduce(function(u,d){return typeof d>"u"?u:u.concat(d)},[])}gFr.exports=function(e,r,n){var o=ago(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("("+CU+".*?"+CU+")","g"));return c.length===1?s.concat(c[0]):s.concat(c.filter(Boolean).map(function(u){return igo.test(u)?JSON.parse(u.split(CU)[1]):u}))},[])}});var Che=T(A6t=>{"use strict";A6t.quote=uFr();A6t.parse=AFr()});var ia,y6t,Ln,Gx,She=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})(ia||(ia={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(y6t||(y6t={}));Ln=ia.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Gx=t=>{switch(typeof t){case"undefined":return Ln.undefined;case"string":return Ln.string;case"number":return Number.isNaN(t)?Ln.nan:Ln.number;case"boolean":return Ln.boolean;case"function":return Ln.function;case"bigint":return Ln.bigint;case"symbol":return Ln.symbol;case"object":return Array.isArray(t)?Ln.array:t===null?Ln.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Ln.promise:typeof Map<"u"&&t instanceof Map?Ln.map:typeof Set<"u"&&t instanceof Set?Ln.set:typeof Date<"u"&&t instanceof Date?Ln.date:Ln.object;default:return Ln.unknown}}});var Wr,cgo,G3,eke=te(()=>{She();Wr=ia.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"]),cgo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),G3=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,ia.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()}};G3.create=t=>new G3(t)});var lgo,V9,_6t=te(()=>{eke();She();lgo=(t,e)=>{let r;switch(t.code){case Wr.invalid_type:t.received===Ln.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Wr.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ia.jsonStringifyReplacer)}`;break;case Wr.unrecognized_keys:r=`Unrecognized key(s) in object: ${ia.joinValues(t.keys,", ")}`;break;case Wr.invalid_union:r="Invalid input";break;case Wr.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ia.joinValues(t.options)}`;break;case Wr.invalid_enum_value:r=`Invalid enum value. Expected ${ia.joinValues(t.options)}, received '${t.received}'`;break;case Wr.invalid_arguments:r="Invalid function arguments";break;case Wr.invalid_return_type:r="Invalid function return type";break;case Wr.invalid_date:r="Invalid date";break;case Wr.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}"`:ia.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Wr.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 Wr.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 Wr.custom:r="Invalid input";break;case Wr.invalid_intersection_types:r="Intersection results could not be merged";break;case Wr.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Wr.not_finite:r="Number must be finite";break;default:r=e.defaultError,ia.assertNever(t)}return{message:r}},V9=lgo});function ugo(t){yFr=t}function cJ(){return yFr}var yFr,tke=te(()=>{_6t();yFr=V9});function bn(t,e){let r=cJ(),n=xhe({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===V9?void 0:V9].filter(o=>!!o)});t.common.issues.push(n)}var xhe,dgo,f0,Xi,SU,BA,rke,nke,uO,lJ,E6t=te(()=>{tke();_6t();xhe=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}},dgo=[];f0=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"}),SU=t=>({status:"dirty",value:t}),BA=t=>({status:"valid",value:t}),rke=t=>t.status==="aborted",nke=t=>t.status==="dirty",uO=t=>t.status==="valid",lJ=t=>typeof Promise<"u"&&t instanceof Promise});var _Fr=te(()=>{});var Ei,EFr=te(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Ei||(Ei={}))});function hs(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 SFr(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 Igo(t){return new RegExp(`^${SFr(t)}$`)}function xFr(t){let e=`${CFr}T${SFr(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 Dgo(t,e){return!!((e==="v4"||!e)&&vgo.test(t)||(e==="v6"||!e)&&Cgo.test(t))}function Rgo(t,e){if(!Ago.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 Ngo(t,e){return!!((e==="v4"||!e)&&bgo.test(t)||(e==="v6"||!e)&&Sgo.test(t))}function Ogo(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 uJ(t){if(t instanceof $3){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=yv.create(uJ(n))}return new $3({...t._def,shape:()=>e})}else return t instanceof Y9?new Y9({...t._def,type:uJ(t.element)}):t instanceof yv?yv.create(uJ(t.unwrap())):t instanceof qx?qx.create(uJ(t.unwrap())):t instanceof $x?$x.create(t.items.map(e=>uJ(e))):t}function b6t(t,e){let r=Gx(t),n=Gx(e);if(t===e)return{valid:!0,data:t};if(r===Ln.object&&n===Ln.object){let o=ia.objectKeys(e),s=ia.objectKeys(t).filter(c=>o.indexOf(c)!==-1),a={...t,...e};for(let c of s){let u=b6t(t[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(r===Ln.array&&n===Ln.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=b6t(a,c);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return r===Ln.date&&n===Ln.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function wFr(t,e){return new PU({values:t,typeName:oo.ZodEnum,...hs(e)})}function bFr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function TFr(t,e={},r){return t?fO.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let c=bFr(e,n),u=c.fatal??r??!0;o.addIssue({code:"custom",...c,fatal:u})}});if(!s){let a=bFr(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}}):fO.create()}var _v,vFr,Is,fgo,pgo,hgo,mgo,ggo,Ago,ygo,_go,Ego,v6t,vgo,bgo,Cgo,Sgo,xgo,wgo,CFr,Tgo,dO,xU,wU,TU,IU,dJ,DU,RU,fO,z9,SC,fJ,Y9,$3,NU,W9,ike,OU,$x,oke,pJ,hJ,ske,kU,BU,PU,MU,pO,Ev,yv,qx,FU,LU,mJ,kgo,whe,The,UU,Bgo,oo,Pgo,IFr,DFr,Mgo,Fgo,RFr,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,u0o,d0o,f0o,p0o,h0o,m0o,g0o,A0o,NFr=te(()=>{eke();tke();EFr();E6t();She();_v=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}},vFr=(t,e)=>{if(uO(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 G3(t.common.issues);return this._error=r,this._error}}};Is=class{get description(){return this._def.description}_getType(e){return Gx(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Gx(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new f0,ctx:{common:e.parent.common,data:e.data,parsedType:Gx(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(lJ(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:Gx(e)},o=this._parseSync({data:e,path:n.path,parent:n});return vFr(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Gx(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return uO(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=>uO(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:Gx(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(lJ(o)?o:Promise.resolve(o));return vFr(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:Wr.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 Ev({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 yv.create(this,this._def)}nullable(){return qx.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Y9.create(this)}promise(){return pO.create(this,this._def)}or(e){return NU.create([this,e],this._def)}and(e){return OU.create(this,e,this._def)}transform(e){return new Ev({...hs(this._def),schema:this,typeName:oo.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new FU({...hs(this._def),innerType:this,defaultValue:r,typeName:oo.ZodDefault})}brand(){return new whe({typeName:oo.ZodBranded,type:this,...hs(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new LU({...hs(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 The.create(this,e)}readonly(){return UU.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},fgo=/^c[^\s-]{8,}$/i,pgo=/^[0-9a-z]+$/,hgo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mgo=/^[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,ggo=/^[a-z0-9_-]{21}$/i,Ago=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ygo=/^[-+]?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)?)??$/,_go=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ego="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vgo=/^(?:(?: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])$/,bgo=/^(?:(?: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])$/,Cgo=/^(([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]))$/,Sgo=/^(([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])$/,xgo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wgo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,CFr="((\\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])))",Tgo=new RegExp(`^${CFr}$`);dO=class t extends Is{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Ln.string){let s=this._getOrReturnCtx(e);return bn(s,{code:Wr.invalid_type,expected:Ln.string,received:s.parsedType}),Xi}let n=new f0,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),bn(o,{code:Wr.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),bn(o,{code:Wr.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?bn(o,{code:Wr.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&bn(o,{code:Wr.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")_go.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"email",code:Wr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")v6t||(v6t=new RegExp(Ego,"u")),v6t.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"emoji",code:Wr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")mgo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"uuid",code:Wr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ggo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"nanoid",code:Wr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")fgo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"cuid",code:Wr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")pgo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"cuid2",code:Wr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")hgo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"ulid",code:Wr.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),bn(o,{validation:"url",code:Wr.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),bn(o,{validation:"regex",code:Wr.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),bn(o,{code:Wr.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),bn(o,{code:Wr.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),bn(o,{code:Wr.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?xFr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{code:Wr.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Tgo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{code:Wr.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Igo(s).test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{code:Wr.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ygo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"duration",code:Wr.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Dgo(e.data,s.version)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"ip",code:Wr.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Rgo(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"jwt",code:Wr.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Ngo(e.data,s.version)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"cidr",code:Wr.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?xgo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"base64",code:Wr.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?wgo.test(e.data)||(o=this._getOrReturnCtx(e,o),bn(o,{validation:"base64url",code:Wr.invalid_string,message:s.message}),n.dirty()):ia.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:Wr.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}};dO.create=t=>new dO({checks:[],typeName:oo.ZodString,coerce:t?.coerce??!1,...hs(t)});xU=class t extends Is{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)!==Ln.number){let s=this._getOrReturnCtx(e);return bn(s,{code:Wr.invalid_type,expected:Ln.number,received:s.parsedType}),Xi}let n,o=new f0;for(let s of this._def.checks)s.kind==="int"?ia.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),bn(n,{code:Wr.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),bn(n,{code:Wr.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),bn(n,{code:Wr.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Ogo(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),bn(n,{code:Wr.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),bn(n,{code:Wr.not_finite,message:s.message}),o.dirty()):ia.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"&&ia.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)}};xU.create=t=>new xU({checks:[],typeName:oo.ZodNumber,coerce:t?.coerce||!1,...hs(t)});wU=class t extends Is{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)!==Ln.bigint)return this._getInvalidInput(e);let n,o=new f0;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),bn(n,{code:Wr.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),bn(n,{code:Wr.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),bn(n,{code:Wr.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ia.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return bn(r,{code:Wr.invalid_type,expected:Ln.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}};wU.create=t=>new wU({checks:[],typeName:oo.ZodBigInt,coerce:t?.coerce??!1,...hs(t)});TU=class extends Is{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Ln.boolean){let n=this._getOrReturnCtx(e);return bn(n,{code:Wr.invalid_type,expected:Ln.boolean,received:n.parsedType}),Xi}return BA(e.data)}};TU.create=t=>new TU({typeName:oo.ZodBoolean,coerce:t?.coerce||!1,...hs(t)});IU=class t extends Is{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Ln.date){let s=this._getOrReturnCtx(e);return bn(s,{code:Wr.invalid_type,expected:Ln.date,received:s.parsedType}),Xi}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return bn(s,{code:Wr.invalid_date}),Xi}let n=new f0,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),bn(o,{code:Wr.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),bn(o,{code:Wr.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ia.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}};IU.create=t=>new IU({checks:[],coerce:t?.coerce||!1,typeName:oo.ZodDate,...hs(t)});dJ=class extends Is{_parse(e){if(this._getType(e)!==Ln.symbol){let n=this._getOrReturnCtx(e);return bn(n,{code:Wr.invalid_type,expected:Ln.symbol,received:n.parsedType}),Xi}return BA(e.data)}};dJ.create=t=>new dJ({typeName:oo.ZodSymbol,...hs(t)});DU=class extends Is{_parse(e){if(this._getType(e)!==Ln.undefined){let n=this._getOrReturnCtx(e);return bn(n,{code:Wr.invalid_type,expected:Ln.undefined,received:n.parsedType}),Xi}return BA(e.data)}};DU.create=t=>new DU({typeName:oo.ZodUndefined,...hs(t)});RU=class extends Is{_parse(e){if(this._getType(e)!==Ln.null){let n=this._getOrReturnCtx(e);return bn(n,{code:Wr.invalid_type,expected:Ln.null,received:n.parsedType}),Xi}return BA(e.data)}};RU.create=t=>new RU({typeName:oo.ZodNull,...hs(t)});fO=class extends Is{constructor(){super(...arguments),this._any=!0}_parse(e){return BA(e.data)}};fO.create=t=>new fO({typeName:oo.ZodAny,...hs(t)});z9=class extends Is{constructor(){super(...arguments),this._unknown=!0}_parse(e){return BA(e.data)}};z9.create=t=>new z9({typeName:oo.ZodUnknown,...hs(t)});SC=class extends Is{_parse(e){let r=this._getOrReturnCtx(e);return bn(r,{code:Wr.invalid_type,expected:Ln.never,received:r.parsedType}),Xi}};SC.create=t=>new SC({typeName:oo.ZodNever,...hs(t)});fJ=class extends Is{_parse(e){if(this._getType(e)!==Ln.undefined){let n=this._getOrReturnCtx(e);return bn(n,{code:Wr.invalid_type,expected:Ln.void,received:n.parsedType}),Xi}return BA(e.data)}};fJ.create=t=>new fJ({typeName:oo.ZodVoid,...hs(t)});Y9=class t extends Is{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==Ln.array)return bn(r,{code:Wr.invalid_type,expected:Ln.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)&&(bn(r,{code:a?Wr.too_big:Wr.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&&(bn(r,{code:Wr.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&&(bn(r,{code:Wr.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 _v(r,a,r.path,c)))).then(a=>f0.mergeArray(n,a));let s=[...r.data].map((a,c)=>o.type._parseSync(new _v(r,a,r.path,c)));return f0.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)}};Y9.create=(t,e)=>new Y9({type:t,minLength:null,maxLength:null,exactLength:null,typeName:oo.ZodArray,...hs(e)});$3=class t extends Is{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=ia.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==Ln.object){let d=this._getOrReturnCtx(e);return bn(d,{code:Wr.invalid_type,expected:Ln.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 SC&&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 _v(o,p,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof SC){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&&(bn(o,{code:Wr.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 _v(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=>f0.mergeObjectSync(n,d)):f0.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 ia.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 ia.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return uJ(this)}partial(e){let r={};for(let n of ia.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 ia.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof yv;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return wFr(ia.objectKeys(this.shape))}};$3.create=(t,e)=>new $3({shape:()=>t,unknownKeys:"strip",catchall:SC.create(),typeName:oo.ZodObject,...hs(e)});$3.strictCreate=(t,e)=>new $3({shape:()=>t,unknownKeys:"strict",catchall:SC.create(),typeName:oo.ZodObject,...hs(e)});$3.lazycreate=(t,e)=>new $3({shape:t,unknownKeys:"strip",catchall:SC.create(),typeName:oo.ZodObject,...hs(e)});NU=class extends Is{_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 G3(c.ctx.common.issues));return bn(r,{code:Wr.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 G3(u));return bn(r,{code:Wr.invalid_union,unionErrors:c}),Xi}}get options(){return this._def.options}};NU.create=(t,e)=>new NU({options:t,typeName:oo.ZodUnion,...hs(e)});W9=t=>t instanceof kU?W9(t.schema):t instanceof Ev?W9(t.innerType()):t instanceof BU?[t.value]:t instanceof PU?t.options:t instanceof MU?ia.objectValues(t.enum):t instanceof FU?W9(t._def.innerType):t instanceof DU?[void 0]:t instanceof RU?[null]:t instanceof yv?[void 0,...W9(t.unwrap())]:t instanceof qx?[null,...W9(t.unwrap())]:t instanceof whe||t instanceof UU?W9(t.unwrap()):t instanceof LU?W9(t._def.innerType):[],ike=class t extends Is{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Ln.object)return bn(r,{code:Wr.invalid_type,expected:Ln.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}):(bn(r,{code:Wr.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=W9(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,...hs(n)})}};OU=class extends Is{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,a)=>{if(rke(s)||rke(a))return Xi;let c=b6t(s.value,a.value);return c.valid?((nke(s)||nke(a))&&r.dirty(),{status:r.value,value:c.data}):(bn(n,{code:Wr.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}))}};OU.create=(t,e,r)=>new OU({left:t,right:e,typeName:oo.ZodIntersection,...hs(r)});$x=class t extends Is{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ln.array)return bn(n,{code:Wr.invalid_type,expected:Ln.array,received:n.parsedType}),Xi;if(n.data.length<this._def.items.length)return bn(n,{code:Wr.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Xi;!this._def.rest&&n.data.length>this._def.items.length&&(bn(n,{code:Wr.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 _v(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>f0.mergeArray(r,a)):f0.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};$x.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new $x({items:t,typeName:oo.ZodTuple,rest:null,...hs(e)})};oke=class t extends Is{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!==Ln.object)return bn(n,{code:Wr.invalid_type,expected:Ln.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 _v(n,c,n.path,c)),value:a._parse(new _v(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?f0.mergeObjectAsync(r,o):f0.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Is?new t({keyType:e,valueType:r,typeName:oo.ZodRecord,...hs(n)}):new t({keyType:dO.create(),valueType:e,typeName:oo.ZodRecord,...hs(r)})}},pJ=class extends Is{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!==Ln.map)return bn(n,{code:Wr.invalid_type,expected:Ln.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 _v(n,c,n.path,[d,"key"])),value:s._parse(new _v(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}}}};pJ.create=(t,e,r)=>new pJ({valueType:e,keyType:t,typeName:oo.ZodMap,...hs(r)});hJ=class t extends Is{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==Ln.set)return bn(n,{code:Wr.invalid_type,expected:Ln.set,received:n.parsedType}),Xi;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(bn(n,{code:Wr.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&&(bn(n,{code:Wr.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 _v(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)}};hJ.create=(t,e)=>new hJ({valueType:t,minSize:null,maxSize:null,typeName:oo.ZodSet,...hs(e)});ske=class t extends Is{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Ln.function)return bn(r,{code:Wr.invalid_type,expected:Ln.function,received:r.parsedType}),Xi;function n(c,u){return xhe({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,cJ(),V9].filter(d=>!!d),issueData:{code:Wr.invalid_arguments,argumentsError:u}})}function o(c,u){return xhe({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,cJ(),V9].filter(d=>!!d),issueData:{code:Wr.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof pO){let c=this;return BA(async function(...u){let d=new G3([]),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 BA(function(...u){let d=c._def.args.safeParse(u,s);if(!d.success)throw new G3([n(u,d.error)]);let f=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(f,s);if(!p.success)throw new G3([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:$x.create(e).rest(z9.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||$x.create([]).rest(z9.create()),returns:r||z9.create(),typeName:oo.ZodFunction,...hs(n)})}},kU=class extends Is{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})}};kU.create=(t,e)=>new kU({getter:t,typeName:oo.ZodLazy,...hs(e)});BU=class extends Is{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return bn(r,{received:r.data,code:Wr.invalid_literal,expected:this._def.value}),Xi}return{status:"valid",value:e.data}}get value(){return this._def.value}};BU.create=(t,e)=>new BU({value:t,typeName:oo.ZodLiteral,...hs(e)});PU=class t extends Is{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return bn(r,{expected:ia.joinValues(n),received:r.parsedType,code:Wr.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 bn(r,{received:r.data,code:Wr.invalid_enum_value,options:n}),Xi}return BA(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})}};PU.create=wFr;MU=class extends Is{_parse(e){let r=ia.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Ln.string&&n.parsedType!==Ln.number){let o=ia.objectValues(r);return bn(n,{expected:ia.joinValues(o),received:n.parsedType,code:Wr.invalid_type}),Xi}if(this._cache||(this._cache=new Set(ia.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ia.objectValues(r);return bn(n,{received:n.data,code:Wr.invalid_enum_value,options:o}),Xi}return BA(e.data)}get enum(){return this._def.values}};MU.create=(t,e)=>new MU({values:t,typeName:oo.ZodNativeEnum,...hs(e)});pO=class extends Is{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Ln.promise&&r.common.async===!1)return bn(r,{code:Wr.invalid_type,expected:Ln.promise,received:r.parsedType}),Xi;let n=r.parsedType===Ln.promise?r.data:Promise.resolve(r.data);return BA(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};pO.create=(t,e)=>new pO({type:t,typeName:oo.ZodPromise,...hs(e)});Ev=class extends Is{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=>{bn(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"?SU(u.value):r.value==="dirty"?SU(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"?SU(c.value):r.value==="dirty"?SU(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(!uO(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=>uO(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:r.value,value:c})):Xi);ia.assertNever(o)}};Ev.create=(t,e,r)=>new Ev({schema:t,typeName:oo.ZodEffects,effect:e,...hs(r)});Ev.createWithPreprocess=(t,e,r)=>new Ev({schema:e,effect:{type:"preprocess",transform:t},typeName:oo.ZodEffects,...hs(r)});yv=class extends Is{_parse(e){return this._getType(e)===Ln.undefined?BA(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yv.create=(t,e)=>new yv({innerType:t,typeName:oo.ZodOptional,...hs(e)});qx=class extends Is{_parse(e){return this._getType(e)===Ln.null?BA(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qx.create=(t,e)=>new qx({innerType:t,typeName:oo.ZodNullable,...hs(e)});FU=class extends Is{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===Ln.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};FU.create=(t,e)=>new FU({innerType:t,typeName:oo.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...hs(e)});LU=class extends Is{_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 lJ(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new G3(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new G3(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};LU.create=(t,e)=>new LU({innerType:t,typeName:oo.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...hs(e)});mJ=class extends Is{_parse(e){if(this._getType(e)!==Ln.nan){let n=this._getOrReturnCtx(e);return bn(n,{code:Wr.invalid_type,expected:Ln.nan,received:n.parsedType}),Xi}return{status:"valid",value:e.data}}};mJ.create=t=>new mJ({typeName:oo.ZodNaN,...hs(t)});kgo=Symbol("zod_brand"),whe=class extends Is{_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}},The=class t extends Is{_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(),SU(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})}},UU=class extends Is{_parse(e){let r=this._def.innerType._parse(e),n=o=>(uO(o)&&(o.value=Object.freeze(o.value)),o);return lJ(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};UU.create=(t,e)=>new UU({innerType:t,typeName:oo.ZodReadonly,...hs(e)});Bgo={object:$3.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={}));Pgo=(t,e={message:`Input not instance of ${t.name}`})=>TFr(r=>r instanceof t,e),IFr=dO.create,DFr=xU.create,Mgo=mJ.create,Fgo=wU.create,RFr=TU.create,Lgo=IU.create,Ugo=dJ.create,Qgo=DU.create,jgo=RU.create,Ggo=fO.create,$go=z9.create,qgo=SC.create,Hgo=fJ.create,Vgo=Y9.create,Wgo=$3.create,zgo=$3.strictCreate,Ygo=NU.create,Kgo=ike.create,Xgo=OU.create,Jgo=$x.create,Zgo=oke.create,e0o=pJ.create,t0o=hJ.create,r0o=ske.create,n0o=kU.create,i0o=BU.create,o0o=PU.create,s0o=MU.create,a0o=pO.create,c0o=Ev.create,l0o=yv.create,u0o=qx.create,d0o=Ev.createWithPreprocess,f0o=The.create,p0o=()=>IFr().optional(),h0o=()=>DFr().optional(),m0o=()=>RFr().optional(),g0o={string:(t=>dO.create({...t,coerce:!0})),number:(t=>xU.create({...t,coerce:!0})),boolean:(t=>TU.create({...t,coerce:!0})),bigint:(t=>wU.create({...t,coerce:!0})),date:(t=>IU.create({...t,coerce:!0}))},A0o=Xi});var se={};Ys(se,{BRAND:()=>kgo,DIRTY:()=>SU,EMPTY_PATH:()=>dgo,INVALID:()=>Xi,NEVER:()=>A0o,OK:()=>BA,ParseStatus:()=>f0,Schema:()=>Is,ZodAny:()=>fO,ZodArray:()=>Y9,ZodBigInt:()=>wU,ZodBoolean:()=>TU,ZodBranded:()=>whe,ZodCatch:()=>LU,ZodDate:()=>IU,ZodDefault:()=>FU,ZodDiscriminatedUnion:()=>ike,ZodEffects:()=>Ev,ZodEnum:()=>PU,ZodError:()=>G3,ZodFirstPartyTypeKind:()=>oo,ZodFunction:()=>ske,ZodIntersection:()=>OU,ZodIssueCode:()=>Wr,ZodLazy:()=>kU,ZodLiteral:()=>BU,ZodMap:()=>pJ,ZodNaN:()=>mJ,ZodNativeEnum:()=>MU,ZodNever:()=>SC,ZodNull:()=>RU,ZodNullable:()=>qx,ZodNumber:()=>xU,ZodObject:()=>$3,ZodOptional:()=>yv,ZodParsedType:()=>Ln,ZodPipeline:()=>The,ZodPromise:()=>pO,ZodReadonly:()=>UU,ZodRecord:()=>oke,ZodSchema:()=>Is,ZodSet:()=>hJ,ZodString:()=>dO,ZodSymbol:()=>dJ,ZodTransformer:()=>Ev,ZodTuple:()=>$x,ZodType:()=>Is,ZodUndefined:()=>DU,ZodUnion:()=>NU,ZodUnknown:()=>z9,ZodVoid:()=>fJ,addIssueToContext:()=>bn,any:()=>Ggo,array:()=>Vgo,bigint:()=>Fgo,boolean:()=>RFr,coerce:()=>g0o,custom:()=>TFr,date:()=>Lgo,datetimeRegex:()=>xFr,defaultErrorMap:()=>V9,discriminatedUnion:()=>Kgo,effect:()=>c0o,enum:()=>o0o,function:()=>r0o,getErrorMap:()=>cJ,getParsedType:()=>Gx,instanceof:()=>Pgo,intersection:()=>Xgo,isAborted:()=>rke,isAsync:()=>lJ,isDirty:()=>nke,isValid:()=>uO,late:()=>Bgo,lazy:()=>n0o,literal:()=>i0o,makeIssue:()=>xhe,map:()=>e0o,nan:()=>Mgo,nativeEnum:()=>s0o,never:()=>qgo,null:()=>jgo,nullable:()=>u0o,number:()=>DFr,object:()=>Wgo,objectUtil:()=>y6t,oboolean:()=>m0o,onumber:()=>h0o,optional:()=>l0o,ostring:()=>p0o,pipeline:()=>f0o,preprocess:()=>d0o,promise:()=>a0o,quotelessJson:()=>cgo,record:()=>Zgo,set:()=>t0o,setErrorMap:()=>ugo,strictObject:()=>zgo,string:()=>IFr,symbol:()=>Ugo,transformer:()=>c0o,tuple:()=>Jgo,undefined:()=>Qgo,union:()=>Ygo,unknown:()=>$go,util:()=>ia,void:()=>Hgo});var C6t=te(()=>{tke();E6t();_Fr();She();NFr();eke()});var hO=te(()=>{C6t();C6t()});var gJ,OFr,ake,kFr,BFr,y0o,Cv,q3,Ihe,Hx,Sv,cke,PFr,lke,MFr,FFr,LFr,Dhe,vv,UFr,QFr,mO,QU,uke,_0o,Rhe,Nhe,jFr,E0o,v0o,b0o,S6t,GFr,$Fr,dke,C0o,fke,pke,hke,qFr,HFr,x6t,VFr,WFr,S0o,x0o,w6t,w0o,T6t,T0o,I6t,I0o,D0o,R0o,N0o,O0o,k0o,B0o,Ohe,P0o,D6t,R6t,N6t,M0o,F0o,zFr,L0o,khe,U0o,Q0o,j0o,G0o,O6t,mke,LGa,$0o,q0o,YFr,H0o,V0o,W0o,z0o,Y0o,K0o,X0o,J0o,Z0o,eAo,tAo,rAo,nAo,iAo,oAo,sAo,aAo,k6t,cAo,gke,lAo,uAo,UGa,QGa,jGa,GGa,$Ga,qGa,bv,gO=te(()=>{hO();gJ="2025-06-18",OFr=[gJ,"2025-03-26","2024-11-05","2024-10-07"],ake="2.0",kFr=se.union([se.string(),se.number().int()]),BFr=se.string(),y0o=se.object({progressToken:se.optional(kFr)}).passthrough(),Cv=se.object({_meta:se.optional(y0o)}).passthrough(),q3=se.object({method:se.string(),params:se.optional(Cv)}),Ihe=se.object({_meta:se.optional(se.object({}).passthrough())}).passthrough(),Hx=se.object({method:se.string(),params:se.optional(Ihe)}),Sv=se.object({_meta:se.optional(se.object({}).passthrough())}).passthrough(),cke=se.union([se.string(),se.number().int()]),PFr=se.object({jsonrpc:se.literal(ake),id:cke}).merge(q3).strict(),lke=t=>PFr.safeParse(t).success,MFr=se.object({jsonrpc:se.literal(ake)}).merge(Hx).strict(),FFr=t=>MFr.safeParse(t).success,LFr=se.object({jsonrpc:se.literal(ake),id:cke,result:Sv}).strict(),Dhe=t=>LFr.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"})(vv||(vv={}));UFr=se.object({jsonrpc:se.literal(ake),id:cke,error:se.object({code:se.number().int(),message:se.string(),data:se.optional(se.unknown())})}).strict(),QFr=t=>UFr.safeParse(t).success,mO=se.union([PFr,MFr,LFr,UFr]),QU=Sv.strict(),uke=Hx.extend({method:se.literal("notifications/cancelled"),params:Ihe.extend({requestId:cke,reason:se.string().optional()})}),_0o=se.object({src:se.string(),mimeType:se.optional(se.string()),sizes:se.optional(se.array(se.string()))}).passthrough(),Rhe=se.object({icons:se.array(_0o).optional()}).passthrough(),Nhe=se.object({name:se.string(),title:se.optional(se.string())}).passthrough(),jFr=Nhe.extend({version:se.string(),websiteUrl:se.optional(se.string())}).merge(Rhe),E0o=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(),v0o=q3.extend({method:se.literal("initialize"),params:Cv.extend({protocolVersion:se.string(),capabilities:E0o,clientInfo:jFr})}),b0o=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(),S6t=Sv.extend({protocolVersion:se.string(),capabilities:b0o,serverInfo:jFr,instructions:se.optional(se.string())}),GFr=Hx.extend({method:se.literal("notifications/initialized")}),$Fr=t=>GFr.safeParse(t).success,dke=q3.extend({method:se.literal("ping")}),C0o=se.object({progress:se.number(),total:se.optional(se.number()),message:se.optional(se.string())}).passthrough(),fke=Hx.extend({method:se.literal("notifications/progress"),params:Ihe.merge(C0o).extend({progressToken:kFr})}),pke=q3.extend({params:Cv.extend({cursor:se.optional(BFr)}).optional()}),hke=Sv.extend({nextCursor:se.optional(BFr)}),qFr=se.object({uri:se.string(),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).passthrough(),HFr=qFr.extend({text:se.string()}),x6t=se.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),VFr=qFr.extend({blob:x6t}),WFr=Nhe.extend({uri:se.string(),description:se.optional(se.string()),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).merge(Rhe),S0o=Nhe.extend({uriTemplate:se.string(),description:se.optional(se.string()),mimeType:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).merge(Rhe),x0o=pke.extend({method:se.literal("resources/list")}),w6t=hke.extend({resources:se.array(WFr)}),w0o=pke.extend({method:se.literal("resources/templates/list")}),T6t=hke.extend({resourceTemplates:se.array(S0o)}),T0o=q3.extend({method:se.literal("resources/read"),params:Cv.extend({uri:se.string()})}),I6t=Sv.extend({contents:se.array(se.union([HFr,VFr]))}),I0o=Hx.extend({method:se.literal("notifications/resources/list_changed")}),D0o=q3.extend({method:se.literal("resources/subscribe"),params:Cv.extend({uri:se.string()})}),R0o=q3.extend({method:se.literal("resources/unsubscribe"),params:Cv.extend({uri:se.string()})}),N0o=Hx.extend({method:se.literal("notifications/resources/updated"),params:Ihe.extend({uri:se.string()})}),O0o=se.object({name:se.string(),description:se.optional(se.string()),required:se.optional(se.boolean())}).passthrough(),k0o=Nhe.extend({description:se.optional(se.string()),arguments:se.optional(se.array(O0o)),_meta:se.optional(se.object({}).passthrough())}).merge(Rhe),B0o=pke.extend({method:se.literal("prompts/list")}),Ohe=hke.extend({prompts:se.array(k0o)}),P0o=q3.extend({method:se.literal("prompts/get"),params:Cv.extend({name:se.string(),arguments:se.optional(se.record(se.string()))})}),D6t=se.object({type:se.literal("text"),text:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),R6t=se.object({type:se.literal("image"),data:x6t,mimeType:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),N6t=se.object({type:se.literal("audio"),data:x6t,mimeType:se.string(),_meta:se.optional(se.object({}).passthrough())}).passthrough(),M0o=se.object({type:se.literal("resource"),resource:se.union([HFr,VFr]),_meta:se.optional(se.object({}).passthrough())}).passthrough(),F0o=WFr.extend({type:se.literal("resource_link")}),zFr=se.union([D6t,R6t,N6t,F0o,M0o]),L0o=se.object({role:se.enum(["user","assistant"]),content:zFr}).passthrough(),khe=Sv.extend({description:se.optional(se.string()),messages:se.array(L0o)}),U0o=Hx.extend({method:se.literal("notifications/prompts/list_changed")}),Q0o=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(),j0o=Nhe.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(Q0o),_meta:se.optional(se.object({}).passthrough())}).merge(Rhe),G0o=pke.extend({method:se.literal("tools/list")}),O6t=hke.extend({tools:se.array(j0o)}),mke=Sv.extend({content:se.array(zFr).default([]),structuredContent:se.object({}).passthrough().optional(),isError:se.optional(se.boolean())}),LGa=mke.or(Sv.extend({toolResult:se.unknown()})),$0o=q3.extend({method:se.literal("tools/call"),params:Cv.extend({name:se.string(),arguments:se.optional(se.record(se.unknown()))})}),q0o=Hx.extend({method:se.literal("notifications/tools/list_changed")}),YFr=se.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),H0o=q3.extend({method:se.literal("logging/setLevel"),params:Cv.extend({level:YFr})}),V0o=Hx.extend({method:se.literal("notifications/message"),params:Ihe.extend({level:YFr,logger:se.optional(se.string()),data:se.unknown()})}),W0o=se.object({name:se.string().optional()}).passthrough(),z0o=se.object({hints:se.optional(se.array(W0o)),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(),Y0o=se.object({role:se.enum(["user","assistant"]),content:se.union([D6t,R6t,N6t])}).passthrough(),K0o=q3.extend({method:se.literal("sampling/createMessage"),params:Cv.extend({messages:se.array(Y0o),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(z0o)})}),X0o=Sv.extend({model:se.string(),stopReason:se.optional(se.enum(["endTurn","stopSequence","maxTokens"]).or(se.string())),role:se.enum(["user","assistant"]),content:se.discriminatedUnion("type",[D6t,R6t,N6t])}),J0o=se.object({type:se.literal("boolean"),title:se.optional(se.string()),description:se.optional(se.string()),default:se.optional(se.boolean())}).passthrough(),Z0o=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(),eAo=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(),tAo=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(),rAo=se.union([J0o,Z0o,eAo,tAo]),nAo=q3.extend({method:se.literal("elicitation/create"),params:Cv.extend({message:se.string(),requestedSchema:se.object({type:se.literal("object"),properties:se.record(se.string(),rAo),required:se.optional(se.array(se.string()))}).passthrough()})}),iAo=Sv.extend({action:se.enum(["accept","decline","cancel"]),content:se.optional(se.record(se.string(),se.unknown()))}),oAo=se.object({type:se.literal("ref/resource"),uri:se.string()}).passthrough(),sAo=se.object({type:se.literal("ref/prompt"),name:se.string()}).passthrough(),aAo=q3.extend({method:se.literal("completion/complete"),params:Cv.extend({ref:se.union([sAo,oAo]),argument:se.object({name:se.string(),value:se.string()}).passthrough(),context:se.optional(se.object({arguments:se.optional(se.record(se.string(),se.string()))}))})}),k6t=Sv.extend({completion:se.object({values:se.array(se.string()).max(100),total:se.optional(se.number().int()),hasMore:se.optional(se.boolean())}).passthrough()}),cAo=se.object({uri:se.string().startsWith("file://"),name:se.optional(se.string()),_meta:se.optional(se.object({}).passthrough())}).passthrough(),gke=q3.extend({method:se.literal("roots/list")}),lAo=Sv.extend({roots:se.array(cAo)}),uAo=Hx.extend({method:se.literal("notifications/roots/list_changed")}),UGa=se.union([dke,v0o,aAo,H0o,P0o,B0o,x0o,w0o,T0o,D0o,R0o,$0o,G0o]),QGa=se.union([uke,fke,GFr,uAo]),jGa=se.union([QU,X0o,iAo,lAo]),GGa=se.union([dke,K0o,nAo,gke]),$Ga=se.union([uke,fke,V0o,N0o,I0o,q0o,U0o]),qGa=se.union([QU,S6t,k6t,khe,Ohe,w6t,T6t,I6t,mke,O6t]),bv=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}}});function KFr(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 dAo,Ake,XFr=te(()=>{gO();dAo=6e4,Ake=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(uke,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(fke,r=>{this._onprogress(r)}),this.setRequestHandler(dke,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 bv(vv.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),Dhe(u)||QFr(u)?this._onresponse(u):lke(u)?this._onrequest(u,d):FFr(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 bv(vv.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:vv.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:vv.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),Dhe(e))n(e);else{let o=new bv(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:dAo,b=()=>E(new bv(vv.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 Mhe=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 Bhe=class{};Va._CodeOrName=Bhe;Va.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var jU=class extends Bhe{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=jU;var xv=class extends Bhe{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 jU&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Va._Code=xv;Va.nil=new xv("");function JFr(t,...e){let r=[t[0]],n=0;for(;n<e.length;)P6t(r,e[n]),r.push(t[++n]);return new xv(r)}Va._=JFr;var B6t=new xv("+");function ZFr(t,...e){let r=[Phe(t[0])],n=0;for(;n<e.length;)r.push(B6t),P6t(r,e[n]),r.push(B6t,Phe(t[++n]));return fAo(r),new xv(r)}Va.str=ZFr;function P6t(t,e){e instanceof xv?t.push(...e._items):e instanceof jU?t.push(e):t.push(mAo(e))}Va.addCodeArg=P6t;function fAo(t){let e=1;for(;e<t.length-1;){if(t[e]===B6t){let r=pAo(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function pAo(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof jU||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 jU))return`"${t}${e.slice(1)}`}function hAo(t,e){return e.emptyStr()?t:t.emptyStr()?e:ZFr`${t}${e}`}Va.strConcat=hAo;function mAo(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Phe(Array.isArray(t)?t.join(","):t)}function gAo(t){return new xv(Phe(t))}Va.stringify=gAo;function Phe(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Va.safeStringify=Phe;function AAo(t){return typeof t=="string"&&Va.IDENTIFIER.test(t)?new xv(`.${t}`):JFr`[${t}]`}Va.getProperty=AAo;function yAo(t){if(typeof t=="string"&&Va.IDENTIFIER.test(t))return new xv(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Va.getEsmExportName=yAo;function _Ao(t){return new xv(t.toString())}Va.regexpCode=_Ao});var L6t=T(V3=>{"use strict";Object.defineProperty(V3,"__esModule",{value:!0});V3.ValueScope=V3.ValueScopeName=V3.Scope=V3.varKinds=V3.UsedValueState=void 0;var H3=Mhe(),M6t=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},yke;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(yke||(V3.UsedValueState=yke={}));V3.varKinds={const:new H3.Name("const"),let:new H3.Name("let"),var:new H3.Name("var")};var _ke=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof H3.Name?e:this.name(e)}name(e){return new H3.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}}};V3.Scope=_ke;var Eke=class extends H3.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,H3._)`.${new H3.Name(r)}[${n}]`}};V3.ValueScopeName=Eke;var EAo=(0,H3._)`\n`,F6t=class extends _ke{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?EAo:H3.nil}}get(){return this._scope}name(e){return new Eke(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,H3._)`${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=H3.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,yke.Started);let f=r(d);if(f){let p=this.opts.es5?V3.varKinds.var:V3.varKinds.const;s=(0,H3._)`${s}${p} ${d} = ${f};${this.opts._n}`}else if(f=o?.(d))s=(0,H3._)`${s}${f}${this.opts._n}`;else throw new M6t(d);u.set(d,yke.Completed)})}return s}};V3.ValueScope=F6t});var Ds=T($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.or=$s.and=$s.not=$s.CodeGen=$s.operators=$s.varKinds=$s.ValueScopeName=$s.ValueScope=$s.Scope=$s.Name=$s.regexpCode=$s.stringify=$s.getProperty=$s.nil=$s.strConcat=$s.str=$s._=void 0;var ba=Mhe(),xC=L6t(),AO=Mhe();Object.defineProperty($s,"_",{enumerable:!0,get:function(){return AO._}});Object.defineProperty($s,"str",{enumerable:!0,get:function(){return AO.str}});Object.defineProperty($s,"strConcat",{enumerable:!0,get:function(){return AO.strConcat}});Object.defineProperty($s,"nil",{enumerable:!0,get:function(){return AO.nil}});Object.defineProperty($s,"getProperty",{enumerable:!0,get:function(){return AO.getProperty}});Object.defineProperty($s,"stringify",{enumerable:!0,get:function(){return AO.stringify}});Object.defineProperty($s,"regexpCode",{enumerable:!0,get:function(){return AO.regexpCode}});Object.defineProperty($s,"Name",{enumerable:!0,get:function(){return AO.Name}});var Ske=L6t();Object.defineProperty($s,"Scope",{enumerable:!0,get:function(){return Ske.Scope}});Object.defineProperty($s,"ValueScope",{enumerable:!0,get:function(){return Ske.ValueScope}});Object.defineProperty($s,"ValueScopeName",{enumerable:!0,get:function(){return Ske.ValueScopeName}});Object.defineProperty($s,"varKinds",{enumerable:!0,get:function(){return Ske.varKinds}});$s.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 K9=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},U6t=class extends K9{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?xC.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=yJ(this.rhs,e,r)),this}get names(){return this.rhs instanceof ba._CodeOrName?this.rhs.names:{}}},vke=class extends K9{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=yJ(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ba.Name?{}:{...this.lhs.names};return Cke(e,this.rhs)}},Q6t=class extends vke{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},j6t=class extends K9{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},G6t=class extends K9{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},$6t=class extends K9{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},q6t=class extends K9{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=yJ(this.code,e,r),this}get names(){return this.code instanceof ba._CodeOrName?this.code.names:{}}},Fhe=class extends K9{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)||(vAo(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>qU(e,r.names),{})}},X9=class extends Fhe{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},H6t=class extends Fhe{},AJ=class extends X9{};AJ.kind="else";var GU=class t extends X9{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 AJ(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(eLr(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=yJ(this.condition,e,r),this}get names(){let e=super.names;return Cke(e,this.condition),this.else&&qU(e,this.else.names),e}};GU.kind="if";var $U=class extends X9{};$U.kind="for";var V6t=class extends $U{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=yJ(this.iteration,e,r),this}get names(){return qU(super.names,this.iteration.names)}},W6t=class extends $U{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?xC.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=Cke(super.names,this.from);return Cke(e,this.to)}},bke=class extends $U{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=yJ(this.iterable,e,r),this}get names(){return qU(super.names,this.iterable.names)}},Lhe=class extends X9{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)}};Lhe.kind="func";var Uhe=class extends Fhe{render(e){return"return "+super.render(e)}};Uhe.kind="return";var z6t=class extends X9{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&&qU(e,this.catch.names),this.finally&&qU(e,this.finally.names),e}},Qhe=class extends X9{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qhe.kind="catch";var jhe=class extends X9{render(e){return"finally"+super.render(e)}};jhe.kind="finally";var Y6t=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
952
952
  `:""},this._extScope=e,this._scope=new xC.Scope({parent:e}),this._nodes=[new H6t]}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 U6t(e,s,n)),s}const(e,r,n){return this._def(xC.varKinds.const,e,r,n)}let(e,r,n){return this._def(xC.varKinds.let,e,r,n)}var(e,r,n){return this._def(xC.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new vke(e,r,n))}add(e,r){return this._leafNode(new Q6t(e,$s.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ba.nil&&this._leafNode(new q6t(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 GU(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 GU(e))}else(){return this._elseNode(new AJ)}endIf(){return this._endBlockNode(GU,AJ)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new V6t(e),r)}forRange(e,r,n,o,s=this.opts.es5?xC.varKinds.var:xC.varKinds.let){let a=this._scope.toName(e);return this._for(new W6t(s,a,r,n),()=>o(a))}forOf(e,r,n,o=xC.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 bke("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?xC.varKinds.var:xC.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 bke("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode($U)}label(e){return this._leafNode(new j6t(e))}break(e){return this._leafNode(new G6t(e))}return(e){let r=new Uhe;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Uhe)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new z6t;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qhe(s),r(s)}return n&&(this._currNode=o.finally=new jhe,this.code(n)),this._endBlockNode(Qhe,jhe)}throw(e){return this._leafNode(new $6t(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 Lhe(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Lhe)}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 GU))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}};$s.CodeGen=Y6t;function qU(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Cke(t,e){return e instanceof ba._CodeOrName?qU(t,e.names):t}function yJ(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 vAo(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function eLr(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ba._)`!${K6t(t)}`}$s.not=eLr;var bAo=tLr($s.operators.AND);function CAo(...t){return t.reduce(bAo)}$s.and=CAo;var SAo=tLr($s.operators.OR);function xAo(...t){return t.reduce(SAo)}$s.or=xAo;function tLr(t){return(e,r)=>e===ba.nil?r:r===ba.nil?e:(0,ba._)`${K6t(e)} ${t} ${K6t(r)}`}function K6t(t){return t instanceof ba.Name?t:(0,ba._)`(${t})`}});var Wa=T(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.checkStrictMode=Ks.getErrorPath=Ks.Type=Ks.useFunc=Ks.setEvaluated=Ks.evaluatedPropsToName=Ks.mergeEvaluated=Ks.eachItem=Ks.unescapeJsonPointer=Ks.escapeJsonPointer=Ks.escapeFragment=Ks.unescapeFragment=Ks.schemaRefOrVal=Ks.schemaHasRulesButRef=Ks.schemaHasRules=Ks.checkUnknownRules=Ks.alwaysValidSchema=Ks.toHash=void 0;var Yl=Ds(),wAo=Mhe();function TAo(t){let e={};for(let r of t)e[r]=!0;return e}Ks.toHash=TAo;function IAo(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(iLr(t,e),!oLr(e,t.self.RULES.all))}Ks.alwaysValidSchema=IAo;function iLr(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]||cLr(t,`unknown keyword: "${s}"`)}Ks.checkUnknownRules=iLr;function oLr(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Ks.schemaHasRules=oLr;function DAo(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Ks.schemaHasRulesButRef=DAo;function RAo({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Yl._)`${r}`}return(0,Yl._)`${t}${e}${(0,Yl.getProperty)(n)}`}Ks.schemaRefOrVal=RAo;function NAo(t){return sLr(decodeURIComponent(t))}Ks.unescapeFragment=NAo;function OAo(t){return encodeURIComponent(J6t(t))}Ks.escapeFragment=OAo;function J6t(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Ks.escapeJsonPointer=J6t;function sLr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Ks.unescapeJsonPointer=sLr;function kAo(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Ks.eachItem=kAo;function rLr({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,a,c)=>{let u=a===void 0?s:a instanceof Yl.Name?(s instanceof Yl.Name?t(o,s,a):e(o,s,a),a):s instanceof Yl.Name?(e(o,a,s),s):r(s,a);return c===Yl.Name&&!(u instanceof Yl.Name)?n(o,u):u}}Ks.mergeEvaluated={props:rLr({mergeNames:(t,e,r)=>t.if((0,Yl._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Yl._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Yl._)`${r} || {}`).code((0,Yl._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Yl._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Yl._)`${r} || {}`),Z6t(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:aLr}),items:rLr({mergeNames:(t,e,r)=>t.if((0,Yl._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Yl._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Yl._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Yl._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function aLr(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Yl._)`{}`);return e!==void 0&&Z6t(t,r,e),r}Ks.evaluatedPropsToName=aLr;function Z6t(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Yl._)`${e}${(0,Yl.getProperty)(n)}`,!0))}Ks.setEvaluated=Z6t;var nLr={};function BAo(t,e){return t.scopeValue("func",{ref:e,code:nLr[e.code]||(nLr[e.code]=new wAo._Code(e.code))})}Ks.useFunc=BAo;var X6t;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(X6t||(Ks.Type=X6t={}));function PAo(t,e,r){if(t instanceof Yl.Name){let n=e===X6t.Num;return r?n?(0,Yl._)`"[" + ${t} + "]"`:(0,Yl._)`"['" + ${t} + "']"`:n?(0,Yl._)`"/" + ${t}`:(0,Yl._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Yl.getProperty)(t).toString():"/"+J6t(t)}Ks.getErrorPath=PAo;function cLr(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Ks.checkStrictMode=cLr});var J9=T(evt=>{"use strict";Object.defineProperty(evt,"__esModule",{value:!0});var PA=Ds(),MAo={data:new PA.Name("data"),valCxt:new PA.Name("valCxt"),instancePath:new PA.Name("instancePath"),parentData:new PA.Name("parentData"),parentDataProperty:new PA.Name("parentDataProperty"),rootData:new PA.Name("rootData"),dynamicAnchors:new PA.Name("dynamicAnchors"),vErrors:new PA.Name("vErrors"),errors:new PA.Name("errors"),this:new PA.Name("this"),self:new PA.Name("self"),scope:new PA.Name("scope"),json:new PA.Name("json"),jsonPos:new PA.Name("jsonPos"),jsonLen:new PA.Name("jsonLen"),jsonPart:new PA.Name("jsonPart")};evt.default=MAo});var Ghe=T(MA=>{"use strict";Object.defineProperty(MA,"__esModule",{value:!0});MA.extendErrors=MA.resetErrorsCount=MA.reportExtraError=MA.reportError=MA.keyword$DataError=MA.keywordError=void 0;var Ma=Ds(),xke=Wa(),c1=J9();MA.keywordError={message:({keyword:t})=>(0,Ma.str)`must pass "${t}" keyword validation`};MA.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 FAo(t,e=MA.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:a,allErrors:c}=o,u=dLr(t,e,r);n??(a||c)?lLr(s,u):uLr(o,(0,Ma._)`[${u}]`)}MA.reportError=FAo;function LAo(t,e=MA.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:a}=n,c=dLr(t,e,r);lLr(o,c),s||a||uLr(n,c1.default.vErrors)}MA.reportExtraError=LAo;function UAo(t,e){t.assign(c1.default.errors,e),t.if((0,Ma._)`${c1.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Ma._)`${c1.default.vErrors}.length`,e),()=>t.assign(c1.default.vErrors,null)))}MA.resetErrorsCount=UAo;function QAo({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,c1.default.errors,c=>{t.const(a,(0,Ma._)`${c1.default.vErrors}[${c}]`),t.if((0,Ma._)`${a}.instancePath === undefined`,()=>t.assign((0,Ma._)`${a}.instancePath`,(0,Ma.strConcat)(c1.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))})}MA.extendErrors=QAo;function lLr(t,e){let r=t.const("err",e);t.if((0,Ma._)`${c1.default.vErrors} === null`,()=>t.assign(c1.default.vErrors,(0,Ma._)`[${r}]`),(0,Ma._)`${c1.default.vErrors}.push(${r})`),t.code((0,Ma._)`${c1.default.errors}++`)}function uLr(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 HU={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 dLr(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Ma._)`{}`:jAo(t,e,r)}function jAo(t,e,r={}){let{gen:n,it:o}=t,s=[GAo(o,r),$Ao(t,r)];return qAo(t,e,s),n.object(...s)}function GAo({errorPath:t},{instancePath:e}){let r=e?(0,Ma.str)`${t}${(0,xke.getErrorPath)(e,xke.Type.Str)}`:t;return[c1.default.instancePath,(0,Ma.strConcat)(c1.default.instancePath,r)]}function $Ao({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,xke.getErrorPath)(r,xke.Type.Str)}`),[HU.schemaPath,o]}function qAo(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([HU.keyword,o],[HU.params,typeof e=="function"?e(t):e||(0,Ma._)`{}`]),u.messages&&n.push([HU.message,typeof r=="function"?r(t):r]),u.verbose&&n.push([HU.schema,a],[HU.parentSchema,(0,Ma._)`${f}${p}`],[c1.default.data,s]),d&&n.push([HU.propertyName,d])}});var pLr=T(_J=>{"use strict";Object.defineProperty(_J,"__esModule",{value:!0});_J.boolOrEmptySchema=_J.topBoolOrEmptySchema=void 0;var HAo=Ghe(),VAo=Ds(),WAo=J9(),zAo={message:"boolean schema is false"};function YAo(t){let{gen:e,schema:r,validateName:n}=t;r===!1?fLr(t,!1):typeof r=="object"&&r.$async===!0?e.return(WAo.default.data):(e.assign((0,VAo._)`${n}.errors`,null),e.return(!0))}_J.topBoolOrEmptySchema=YAo;function KAo(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),fLr(t)):r.var(e,!0)}_J.boolOrEmptySchema=KAo;function fLr(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,HAo.reportError)(o,zAo,void 0,e)}});var tvt=T(EJ=>{"use strict";Object.defineProperty(EJ,"__esModule",{value:!0});EJ.getRules=EJ.isJSONType=void 0;var XAo=["string","number","integer","boolean","null","object","array"],JAo=new Set(XAo);function ZAo(t){return typeof t=="string"&&JAo.has(t)}EJ.isJSONType=ZAo;function e2o(){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:{}}}EJ.getRules=e2o});var rvt=T(yO=>{"use strict";Object.defineProperty(yO,"__esModule",{value:!0});yO.shouldUseRule=yO.shouldUseGroup=yO.schemaHasRulesForType=void 0;function t2o({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&hLr(t,n)}yO.schemaHasRulesForType=t2o;function hLr(t,e){return e.rules.some(r=>mLr(t,r))}yO.shouldUseGroup=hLr;function mLr(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))}yO.shouldUseRule=mLr});var $he=T(FA=>{"use strict";Object.defineProperty(FA,"__esModule",{value:!0});FA.reportTypeError=FA.checkDataTypes=FA.checkDataType=FA.coerceAndCheckDataType=FA.getJSONTypes=FA.getSchemaTypes=FA.DataType=void 0;var r2o=tvt(),n2o=rvt(),i2o=Ghe(),vs=Ds(),gLr=Wa(),vJ;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(vJ||(FA.DataType=vJ={}));function o2o(t){let e=ALr(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}FA.getSchemaTypes=o2o;function ALr(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(r2o.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}FA.getJSONTypes=ALr;function s2o(t,e){let{gen:r,data:n,opts:o}=t,s=a2o(e,o.coerceTypes),a=e.length>0&&!(s.length===0&&e.length===1&&(0,n2o.schemaHasRulesForType)(t,e[0]));if(a){let c=ivt(e,n,o.strictNumbers,vJ.Wrong);r.if(c,()=>{s.length?c2o(t,e,s):ovt(t)})}return a}FA.coerceAndCheckDataType=s2o;var yLr=new Set(["string","number","integer","boolean","null"]);function a2o(t,e){return e?t.filter(r=>yLr.has(r)||e==="array"&&r==="array"):[]}function c2o(t,e,r){let{gen:n,data:o,opts:s}=t,a=n.let("dataType",(0,vs._)`typeof ${o}`),c=n.let("coerced",(0,vs._)`undefined`);s.coerceTypes==="array"&&n.if((0,vs._)`${a} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,vs._)`${o}[0]`).assign(a,(0,vs._)`typeof ${o}`).if(ivt(e,o,s.strictNumbers),()=>n.assign(c,o))),n.if((0,vs._)`${c} !== undefined`);for(let d of r)(yLr.has(d)||d==="array"&&s.coerceTypes==="array")&&u(d);n.else(),ovt(t),n.endIf(),n.if((0,vs._)`${c} !== undefined`,()=>{n.assign(o,c),l2o(t,c)});function u(d){switch(d){case"string":n.elseIf((0,vs._)`${a} == "number" || ${a} == "boolean"`).assign(c,(0,vs._)`"" + ${o}`).elseIf((0,vs._)`${o} === null`).assign(c,(0,vs._)`""`);return;case"number":n.elseIf((0,vs._)`${a} == "boolean" || ${o} === null
953
953
  || (${a} == "string" && ${o} && ${o} == +${o})`).assign(c,(0,vs._)`+${o}`);return;case"integer":n.elseIf((0,vs._)`${a} === "boolean" || ${o} === null
@@ -961,7 +961,7 @@ ${e}
961
961
  `;break;case"id":c=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new oBe(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:E}));break;default:r(new oBe(`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(`
962
962
  `)?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 kEo(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),s=t.indexOf(`
963
963
  `,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]===`
964
- `&&n++}}return[e,r]}var oBe,Mbt=te(()=>{oBe=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 BEo(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Fbt(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Fbt).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Fbt(t.cause)}`:t.message:`${t}`}function Njr(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function PEo(){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 cBe,kjr,Hbt,oa,Xh,Gd,t7,Y3,XU,FJ,aBe,lBe,dme,QJ,fme,xO,LJ,jJ,UJ,lme,RC,Lbt,Ubt,Qbt,Ojr,jbt,Gbt,ume,$bt,qbt,JU,Bjr=te(()=>{Mbt();cBe=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(Njr(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Njr(this),r)}};kjr=t=>{throw TypeError(t)},Hbt=(t,e,r)=>e.has(t)||kjr("Cannot "+r),oa=(t,e,r)=>(Hbt(t,e,"read from private field"),r?r.call(t):e.get(t)),Xh=(t,e,r)=>e.has(t)?kjr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Gd=(t,e,r,n)=>(Hbt(t,e,"write to private field"),e.set(t,r),r),t7=(t,e,r)=>(Hbt(t,e,"access private method"),r),JU=class extends EventTarget{constructor(e,r){var n,o;super(),Xh(this,RC),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Xh(this,Y3),Xh(this,XU),Xh(this,FJ),Xh(this,aBe),Xh(this,lBe),Xh(this,dme),Xh(this,QJ),Xh(this,fme,null),Xh(this,xO),Xh(this,LJ),Xh(this,jJ,null),Xh(this,UJ,null),Xh(this,lme,null),Xh(this,Ubt,async s=>{var a;oa(this,LJ).reset();let{body:c,redirected:u,status:d,headers:f}=s;if(d===204){t7(this,RC,ume).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Gd(this,FJ,new URL(s.url)):Gd(this,FJ,void 0),d!==200){t7(this,RC,ume).call(this,`Non-200 status code (${d})`,d);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){t7(this,RC,ume).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(oa(this,Y3)===this.CLOSED)return;Gd(this,Y3,this.OPEN);let p=new Event("open");if((a=oa(this,lme))==null||a.call(this,p),this.dispatchEvent(p),typeof c!="object"||!c||!("getReader"in c)){t7(this,RC,ume).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&&oa(this,LJ).feed(h.decode(y,{stream:!A})),A&&(g=!1,oa(this,LJ).reset(),t7(this,RC,$bt).call(this))}while(g)}),Xh(this,Qbt,s=>{Gd(this,xO,void 0),!(s.name==="AbortError"||s.type==="aborted")&&t7(this,RC,$bt).call(this,Fbt(s))}),Xh(this,jbt,s=>{typeof s.id=="string"&&Gd(this,fme,s.id);let a=new MessageEvent(s.event||"message",{data:s.data,origin:oa(this,FJ)?oa(this,FJ).origin:oa(this,XU).origin,lastEventId:s.id||""});oa(this,UJ)&&(!s.event||s.event==="message")&&oa(this,UJ).call(this,a),this.dispatchEvent(a)}),Xh(this,Gbt,s=>{Gd(this,dme,s)}),Xh(this,qbt,()=>{Gd(this,QJ,void 0),oa(this,Y3)===this.CONNECTING&&t7(this,RC,Lbt).call(this)});try{if(e instanceof URL)Gd(this,XU,e);else if(typeof e=="string")Gd(this,XU,new URL(e,PEo()));else throw new Error("Invalid URL")}catch{throw BEo("An invalid or illegal string was specified")}Gd(this,LJ,sBe({onEvent:oa(this,jbt),onRetry:oa(this,Gbt)})),Gd(this,Y3,this.CONNECTING),Gd(this,dme,3e3),Gd(this,lBe,(n=r?.fetch)!=null?n:globalThis.fetch),Gd(this,aBe,(o=r?.withCredentials)!=null?o:!1),t7(this,RC,Lbt).call(this)}get readyState(){return oa(this,Y3)}get url(){return oa(this,XU).href}get withCredentials(){return oa(this,aBe)}get onerror(){return oa(this,jJ)}set onerror(e){Gd(this,jJ,e)}get onmessage(){return oa(this,UJ)}set onmessage(e){Gd(this,UJ,e)}get onopen(){return oa(this,lme)}set onopen(e){Gd(this,lme,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(){oa(this,QJ)&&clearTimeout(oa(this,QJ)),oa(this,Y3)!==this.CLOSED&&(oa(this,xO)&&oa(this,xO).abort(),Gd(this,Y3,this.CLOSED),Gd(this,xO,void 0))}};Y3=new WeakMap,XU=new WeakMap,FJ=new WeakMap,aBe=new WeakMap,lBe=new WeakMap,dme=new WeakMap,QJ=new WeakMap,fme=new WeakMap,xO=new WeakMap,LJ=new WeakMap,jJ=new WeakMap,UJ=new WeakMap,lme=new WeakMap,RC=new WeakSet,Lbt=function(){Gd(this,Y3,this.CONNECTING),Gd(this,xO,new AbortController),oa(this,lBe)(oa(this,XU),t7(this,RC,Ojr).call(this)).then(oa(this,Ubt)).catch(oa(this,Qbt))},Ubt=new WeakMap,Qbt=new WeakMap,Ojr=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...oa(this,fme)?{"Last-Event-ID":oa(this,fme)}:void 0},cache:"no-store",signal:(t=oa(this,xO))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},jbt=new WeakMap,Gbt=new WeakMap,ume=function(t,e){var r;oa(this,Y3)!==this.CLOSED&&Gd(this,Y3,this.CLOSED);let n=new cBe("error",{code:e,message:t});(r=oa(this,jJ))==null||r.call(this,n),this.dispatchEvent(n)},$bt=function(t,e){var r;if(oa(this,Y3)===this.CLOSED)return;Gd(this,Y3,this.CONNECTING);let n=new cBe("error",{code:e,message:t});(r=oa(this,jJ))==null||r.call(this,n),this.dispatchEvent(n),Gd(this,QJ,setTimeout(oa(this,qbt),oa(this,dme)))},qbt=new WeakMap,JU.CONNECTING=0,JU.OPEN=1,JU.CLOSED=2});async function MEo(t){return(await Vbt).getRandomValues(new Uint8Array(t))}async function FEo(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await MEo(t);for(let o=0;o<t;o++){let s=n[o]%e.length;r+=e[s]}return r}async function LEo(t){return await FEo(t)}async function UEo(t){let e=await(await Vbt).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Wbt(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await LEo(t),r=await UEo(e);return{code_verifier:e,code_challenge:r}}var Vbt,Pjr=te(()=>{Vbt=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var m0,Fjr,zbt,QEo,Ljr,Ybt,Ujr,Mjr,jEo,GEo,Qjr,Uqa,Qqa,Kbt=te(()=>{hO();m0=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"}),Fjr=se.object({resource:se.string().url(),authorization_servers:se.array(m0).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(),zbt=se.object({issuer:se.string(),authorization_endpoint:m0,token_endpoint:m0,registration_endpoint:m0.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:m0.optional(),revocation_endpoint:m0.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(),QEo=se.object({issuer:se.string(),authorization_endpoint:m0,token_endpoint:m0,userinfo_endpoint:m0.optional(),jwks_uri:m0,registration_endpoint:m0.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:m0.optional(),op_tos_uri:m0.optional()}).passthrough(),Ljr=QEo.merge(zbt.pick({code_challenge_methods_supported:!0})),Ybt=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(),Ujr=se.object({error:se.string(),error_description:se.string().optional(),error_uri:se.string().optional()}),Mjr=m0.optional().or(se.literal("").transform(()=>{})),jEo=se.object({redirect_uris:se.array(m0),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:m0.optional(),logo_uri:Mjr,scope:se.string().optional(),contacts:se.array(se.string()).optional(),tos_uri:Mjr,policy_uri:se.string().optional(),jwks_uri:m0.optional(),jwks:se.any().optional(),software_id:se.string().optional(),software_version:se.string().optional(),software_statement:se.string().optional()}).strip(),GEo=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(),Qjr=jEo.merge(GEo),Uqa=se.object({error:se.string(),error_description:se.string().optional()}).strip(),Qqa=se.object({token:se.string(),token_type_hint:se.string().optional()}).strip()});function jjr(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Gjr({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 $jr=te(()=>{});var uh,pme,ZU,eQ,tQ,hme,mme,gme,r7,Ame,yme,_me,Eme,vme,bme,Cme,Sme,qjr,Hjr=te(()=>{uh=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}},pme=class extends uh{};pme.errorCode="invalid_request";ZU=class extends uh{};ZU.errorCode="invalid_client";eQ=class extends uh{};eQ.errorCode="invalid_grant";tQ=class extends uh{};tQ.errorCode="unauthorized_client";hme=class extends uh{};hme.errorCode="unsupported_grant_type";mme=class extends uh{};mme.errorCode="invalid_scope";gme=class extends uh{};gme.errorCode="access_denied";r7=class extends uh{};r7.errorCode="server_error";Ame=class extends uh{};Ame.errorCode="temporarily_unavailable";yme=class extends uh{};yme.errorCode="unsupported_response_type";_me=class extends uh{};_me.errorCode="unsupported_token_type";Eme=class extends uh{};Eme.errorCode="invalid_token";vme=class extends uh{};vme.errorCode="method_not_allowed";bme=class extends uh{};bme.errorCode="too_many_requests";Cme=class extends uh{};Cme.errorCode="invalid_client_metadata";Sme=class extends uh{};Sme.errorCode="insufficient_scope";qjr={[pme.errorCode]:pme,[ZU.errorCode]:ZU,[eQ.errorCode]:eQ,[tQ.errorCode]:tQ,[hme.errorCode]:hme,[mme.errorCode]:mme,[gme.errorCode]:gme,[r7.errorCode]:r7,[Ame.errorCode]:Ame,[yme.errorCode]:yme,[_me.errorCode]:_me,[Eme.errorCode]:Eme,[vme.errorCode]:vme,[bme.errorCode]:bme,[Cme.errorCode]:Cme,[Sme.errorCode]:Sme}});function $Eo(t){return["client_secret_basic","client_secret_post","none"].includes(t)}function Wjr(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&&$Eo(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 zjr(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":qEo(o,s,r);return;case"client_secret_post":HEo(o,s,n);return;case"none":VEo(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function qEo(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 HEo(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function VEo(t,e){e.set("client_id",t)}async function e4t(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=Ujr.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,c=qjr[o]||r7;return new c(s||"",a)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new r7(o)}}async function wO(t,e){var r,n;try{return await Zbt(t,e)}catch(o){if(o instanceof ZU||o instanceof tQ)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Zbt(t,e);if(o instanceof eQ)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await Zbt(t,e);throw o}}async function Zbt(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,c;try{a=await zEo(e,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(c=a.authorization_servers[0])}catch{}c||(c=e);let u=await WEo(e,t,a),d=await ZEo(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 t6o(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 r4t(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 n4t(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 uh)||A instanceof r7))throw A}let h=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:g}=await e6o(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 WEo(t,e,r){let n=jjr(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Gjr({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 xme(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 zEo(t,e,r=fetch){let n=await XEo(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 Fjr.parse(await n.json())}async function t4t(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?t4t(t,void 0,r):void 0;throw n}}function YEo(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Vjr(t,e,r=fetch){return await t4t(t,{"MCP-Protocol-Version":e},r)}function KEo(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function XEo(t,e,r,n){var o,s;let a=new URL(t),c=(o=n?.protocolVersion)!==null&&o!==void 0?o:gJ,u;if(n?.metadataUrl)u=new URL(n.metadataUrl);else{let f=YEo(e,a.pathname);u=new URL(f,(s=n?.metadataServerUrl)!==null&&s!==void 0?s:a),u.search=a.search}let d=await Vjr(u,c,r);if(!n?.metadataUrl&&KEo(d,a.pathname)){let f=new URL(`/.well-known/${e}`,a);d=await Vjr(f,c,r)}return d}function JEo(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 ZEo(t,{fetchFn:e=fetch,protocolVersion:r=gJ}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=JEo(t);for(let{url:s,type:a}of o){let c=await t4t(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"?zbt.parse(await c.json()):Ljr.parse(await c.json())}}}async function e6o(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(Xbt))throw new Error(`Incompatible auth server: does not support response type ${Xbt}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Jbt))throw new Error(`Incompatible auth server: does not support code challenge method ${Jbt}`)}else c=new URL("/authorize",t);let u=await Wbt(),d=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",Xbt),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",Jbt),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 r4t(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=Wjr(r,A);zjr(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 e4t(g);return Ybt.parse(await g.json())}async function n4t(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=Wjr(r,m);zjr(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 e4t(h);return Ybt.parse({refresh_token:n,...await h.json()})}async function t6o(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 e4t(s);return Qjr.parse(await s.json())}var K3,Xbt,Jbt,uBe=te(()=>{Pjr();gO();Kbt();Kbt();$jr();Hjr();K3=class extends Error{constructor(e){super(e??"Unauthorized")}};Xbt="code",Jbt="S256"});var i4t,GJ,Yjr=te(()=>{Bjr();gO();uBe();i4t=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},GJ=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 K3("No auth provider");let r;try{r=await wO(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 K3;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 JU(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}=xme(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 i4t(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=mO.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 K3("No auth provider");if(await wO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new K3("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}=xme(c);if(this._resourceMetadataUrl=d,this._scope=f,await wO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new K3;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 dBe,Kjr=te(()=>{Mbt();dBe=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(s){o=sBe({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 r6o,$J,TO,o4t=te(()=>{gO();uBe();Kjr();r6o={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},$J=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},TO=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:r6o}async _authThenStart(){var e;if(!this._authProvider)throw new K3("No auth provider");let r;try{r=await wO(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 K3;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 $J(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 dBe).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=mO.parse(JSON.parse(m.data));s!==void 0&&Dhe(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 K3("No auth provider");if(await wO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new K3("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:lke(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 $J(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:v}=xme(p);if(this._resourceMetadataUrl=E,this._scope=v,await wO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new K3;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){$Fr(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=>mO.parse(v)):[mO.parse(y)];for(let v of E)(s=this.onmessage)===null||s===void 0||s.call(this,v)}else throw new $J(-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 $J(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 n6o}from"node:fs/promises";var wme,Tme,rQ,s4t=te(()=>{"use strict";lue();uBe();yi();(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"})(wme||(wme={}));Tme=class extends Error{code;constructor(e,r){super(r),this.code=e}},rQ=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||EF.default}async start(){if(this._isClosed)throw new Error(N.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 n4t(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(N.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 Tme(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 Tme(void 0,`Failed to create WebSocket: ${a}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error(N.t("websocketClient.errors.noAuthProvider"));try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),o=await r4t(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(N.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===EF.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error(N.t("websocketClient.errors.transportClosed"));if(!this._websocket)throw new Error(N.t("websocketClient.errors.transportNotStarted"));if(this._websocket.readyState!==EF.default.OPEN)throw new Error(N.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 Tme(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:wme.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.3.29-beta.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:wme.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{filePath:n,originalText:await n6o(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:wme.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 Xjr,fBe,Jjr=te(()=>{"use strict";Xjr=Te(q5e(),1);yi();fBe=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(N.t("mcp.auth.scopesRequired"));this.auth=new Xjr.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(N.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 eGr(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 Zjr(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 Zjr(c,[t],o);return}catch{continue}}throw new Error(`Failed to open browser: ${s instanceof Error?s.message:"Unknown error"}`)}}var Zjr,tGr=te(()=>{"use strict";Zjr=o6o(i6o)});function Mo(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 a4t(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 hBe(r.error.message);case 401:return new IO(r.error.message);case 403:return new pBe(r.error.message);default:}}return t}function l6o(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var pBe,IO,hBe,td=te(()=>{"use strict";pBe=class extends Error{},IO=class extends Error{},hBe=class extends Error{}});import{promises as qJ}from"node:fs";import*as mBe from"node:path";import*as rGr from"node:os";var Zm,gBe=te(()=>{"use strict";td();yi();Zm=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=rGr.homedir();return mBe.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=mBe.dirname(this.getTokenFilePath());await qJ.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await qJ.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(N.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 qJ.writeFile(d,JSON.stringify(u,null,2),{mode:384})}catch(f){throw console.error(N.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 qJ.unlink(o):await qJ.writeFile(o,JSON.stringify(n,null,2),{mode:384})}catch(s){console.error(N.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 qJ.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(N.t("mcp.tokenStorage.errors.failedToClearTokens",{error:_r(e)}))}}}});var eg,ABe=te(()=>{"use strict";td();yi();eg=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(N.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(N.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(N.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(N.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 nGr from"node:http";import*as Ime from"node:crypto";import{URL as c4t}from"node:url";var B_,l4t=te(()=>{"use strict";tGr();gBe();td();ABe();yi();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(N.t("mcp.auth.clientRegistrationFailed",{status:s.status,statusText:s.statusText,error:a}))}return await s.json()}static async discoverOAuthFromMCPServer(e){let r=eg.extractBaseUrl(e);return eg.discoverOAuthConfig(r)}static generatePKCEParams(){let e=Ime.randomBytes(32).toString("base64url"),r=Ime.createHash("sha256").update(e).digest("base64url"),n=Ime.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let o=nGr.createServer(async(s,a)=>{try{let c=new c4t(s.url,`http://localhost:${this.REDIRECT_PORT}`);if(c.pathname!==this.REDIRECT_PATH){a.writeHead(404),a.end(N.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(`
964
+ `&&n++}}return[e,r]}var oBe,Mbt=te(()=>{oBe=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 BEo(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Fbt(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Fbt).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Fbt(t.cause)}`:t.message:`${t}`}function Njr(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function PEo(){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 cBe,kjr,Hbt,oa,Xh,Gd,t7,Y3,XU,FJ,aBe,lBe,dme,QJ,fme,xO,LJ,jJ,UJ,lme,RC,Lbt,Ubt,Qbt,Ojr,jbt,Gbt,ume,$bt,qbt,JU,Bjr=te(()=>{Mbt();cBe=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(Njr(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Njr(this),r)}};kjr=t=>{throw TypeError(t)},Hbt=(t,e,r)=>e.has(t)||kjr("Cannot "+r),oa=(t,e,r)=>(Hbt(t,e,"read from private field"),r?r.call(t):e.get(t)),Xh=(t,e,r)=>e.has(t)?kjr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Gd=(t,e,r,n)=>(Hbt(t,e,"write to private field"),e.set(t,r),r),t7=(t,e,r)=>(Hbt(t,e,"access private method"),r),JU=class extends EventTarget{constructor(e,r){var n,o;super(),Xh(this,RC),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Xh(this,Y3),Xh(this,XU),Xh(this,FJ),Xh(this,aBe),Xh(this,lBe),Xh(this,dme),Xh(this,QJ),Xh(this,fme,null),Xh(this,xO),Xh(this,LJ),Xh(this,jJ,null),Xh(this,UJ,null),Xh(this,lme,null),Xh(this,Ubt,async s=>{var a;oa(this,LJ).reset();let{body:c,redirected:u,status:d,headers:f}=s;if(d===204){t7(this,RC,ume).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Gd(this,FJ,new URL(s.url)):Gd(this,FJ,void 0),d!==200){t7(this,RC,ume).call(this,`Non-200 status code (${d})`,d);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){t7(this,RC,ume).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(oa(this,Y3)===this.CLOSED)return;Gd(this,Y3,this.OPEN);let p=new Event("open");if((a=oa(this,lme))==null||a.call(this,p),this.dispatchEvent(p),typeof c!="object"||!c||!("getReader"in c)){t7(this,RC,ume).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&&oa(this,LJ).feed(h.decode(y,{stream:!A})),A&&(g=!1,oa(this,LJ).reset(),t7(this,RC,$bt).call(this))}while(g)}),Xh(this,Qbt,s=>{Gd(this,xO,void 0),!(s.name==="AbortError"||s.type==="aborted")&&t7(this,RC,$bt).call(this,Fbt(s))}),Xh(this,jbt,s=>{typeof s.id=="string"&&Gd(this,fme,s.id);let a=new MessageEvent(s.event||"message",{data:s.data,origin:oa(this,FJ)?oa(this,FJ).origin:oa(this,XU).origin,lastEventId:s.id||""});oa(this,UJ)&&(!s.event||s.event==="message")&&oa(this,UJ).call(this,a),this.dispatchEvent(a)}),Xh(this,Gbt,s=>{Gd(this,dme,s)}),Xh(this,qbt,()=>{Gd(this,QJ,void 0),oa(this,Y3)===this.CONNECTING&&t7(this,RC,Lbt).call(this)});try{if(e instanceof URL)Gd(this,XU,e);else if(typeof e=="string")Gd(this,XU,new URL(e,PEo()));else throw new Error("Invalid URL")}catch{throw BEo("An invalid or illegal string was specified")}Gd(this,LJ,sBe({onEvent:oa(this,jbt),onRetry:oa(this,Gbt)})),Gd(this,Y3,this.CONNECTING),Gd(this,dme,3e3),Gd(this,lBe,(n=r?.fetch)!=null?n:globalThis.fetch),Gd(this,aBe,(o=r?.withCredentials)!=null?o:!1),t7(this,RC,Lbt).call(this)}get readyState(){return oa(this,Y3)}get url(){return oa(this,XU).href}get withCredentials(){return oa(this,aBe)}get onerror(){return oa(this,jJ)}set onerror(e){Gd(this,jJ,e)}get onmessage(){return oa(this,UJ)}set onmessage(e){Gd(this,UJ,e)}get onopen(){return oa(this,lme)}set onopen(e){Gd(this,lme,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(){oa(this,QJ)&&clearTimeout(oa(this,QJ)),oa(this,Y3)!==this.CLOSED&&(oa(this,xO)&&oa(this,xO).abort(),Gd(this,Y3,this.CLOSED),Gd(this,xO,void 0))}};Y3=new WeakMap,XU=new WeakMap,FJ=new WeakMap,aBe=new WeakMap,lBe=new WeakMap,dme=new WeakMap,QJ=new WeakMap,fme=new WeakMap,xO=new WeakMap,LJ=new WeakMap,jJ=new WeakMap,UJ=new WeakMap,lme=new WeakMap,RC=new WeakSet,Lbt=function(){Gd(this,Y3,this.CONNECTING),Gd(this,xO,new AbortController),oa(this,lBe)(oa(this,XU),t7(this,RC,Ojr).call(this)).then(oa(this,Ubt)).catch(oa(this,Qbt))},Ubt=new WeakMap,Qbt=new WeakMap,Ojr=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...oa(this,fme)?{"Last-Event-ID":oa(this,fme)}:void 0},cache:"no-store",signal:(t=oa(this,xO))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},jbt=new WeakMap,Gbt=new WeakMap,ume=function(t,e){var r;oa(this,Y3)!==this.CLOSED&&Gd(this,Y3,this.CLOSED);let n=new cBe("error",{code:e,message:t});(r=oa(this,jJ))==null||r.call(this,n),this.dispatchEvent(n)},$bt=function(t,e){var r;if(oa(this,Y3)===this.CLOSED)return;Gd(this,Y3,this.CONNECTING);let n=new cBe("error",{code:e,message:t});(r=oa(this,jJ))==null||r.call(this,n),this.dispatchEvent(n),Gd(this,QJ,setTimeout(oa(this,qbt),oa(this,dme)))},qbt=new WeakMap,JU.CONNECTING=0,JU.OPEN=1,JU.CLOSED=2});async function MEo(t){return(await Vbt).getRandomValues(new Uint8Array(t))}async function FEo(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await MEo(t);for(let o=0;o<t;o++){let s=n[o]%e.length;r+=e[s]}return r}async function LEo(t){return await FEo(t)}async function UEo(t){let e=await(await Vbt).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Wbt(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await LEo(t),r=await UEo(e);return{code_verifier:e,code_challenge:r}}var Vbt,Pjr=te(()=>{Vbt=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var m0,Fjr,zbt,QEo,Ljr,Ybt,Ujr,Mjr,jEo,GEo,Qjr,Uqa,Qqa,Kbt=te(()=>{hO();m0=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"}),Fjr=se.object({resource:se.string().url(),authorization_servers:se.array(m0).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(),zbt=se.object({issuer:se.string(),authorization_endpoint:m0,token_endpoint:m0,registration_endpoint:m0.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:m0.optional(),revocation_endpoint:m0.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(),QEo=se.object({issuer:se.string(),authorization_endpoint:m0,token_endpoint:m0,userinfo_endpoint:m0.optional(),jwks_uri:m0,registration_endpoint:m0.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:m0.optional(),op_tos_uri:m0.optional()}).passthrough(),Ljr=QEo.merge(zbt.pick({code_challenge_methods_supported:!0})),Ybt=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(),Ujr=se.object({error:se.string(),error_description:se.string().optional(),error_uri:se.string().optional()}),Mjr=m0.optional().or(se.literal("").transform(()=>{})),jEo=se.object({redirect_uris:se.array(m0),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:m0.optional(),logo_uri:Mjr,scope:se.string().optional(),contacts:se.array(se.string()).optional(),tos_uri:Mjr,policy_uri:se.string().optional(),jwks_uri:m0.optional(),jwks:se.any().optional(),software_id:se.string().optional(),software_version:se.string().optional(),software_statement:se.string().optional()}).strip(),GEo=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(),Qjr=jEo.merge(GEo),Uqa=se.object({error:se.string(),error_description:se.string().optional()}).strip(),Qqa=se.object({token:se.string(),token_type_hint:se.string().optional()}).strip()});function jjr(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Gjr({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 $jr=te(()=>{});var uh,pme,ZU,eQ,tQ,hme,mme,gme,r7,Ame,yme,_me,Eme,vme,bme,Cme,Sme,qjr,Hjr=te(()=>{uh=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}},pme=class extends uh{};pme.errorCode="invalid_request";ZU=class extends uh{};ZU.errorCode="invalid_client";eQ=class extends uh{};eQ.errorCode="invalid_grant";tQ=class extends uh{};tQ.errorCode="unauthorized_client";hme=class extends uh{};hme.errorCode="unsupported_grant_type";mme=class extends uh{};mme.errorCode="invalid_scope";gme=class extends uh{};gme.errorCode="access_denied";r7=class extends uh{};r7.errorCode="server_error";Ame=class extends uh{};Ame.errorCode="temporarily_unavailable";yme=class extends uh{};yme.errorCode="unsupported_response_type";_me=class extends uh{};_me.errorCode="unsupported_token_type";Eme=class extends uh{};Eme.errorCode="invalid_token";vme=class extends uh{};vme.errorCode="method_not_allowed";bme=class extends uh{};bme.errorCode="too_many_requests";Cme=class extends uh{};Cme.errorCode="invalid_client_metadata";Sme=class extends uh{};Sme.errorCode="insufficient_scope";qjr={[pme.errorCode]:pme,[ZU.errorCode]:ZU,[eQ.errorCode]:eQ,[tQ.errorCode]:tQ,[hme.errorCode]:hme,[mme.errorCode]:mme,[gme.errorCode]:gme,[r7.errorCode]:r7,[Ame.errorCode]:Ame,[yme.errorCode]:yme,[_me.errorCode]:_me,[Eme.errorCode]:Eme,[vme.errorCode]:vme,[bme.errorCode]:bme,[Cme.errorCode]:Cme,[Sme.errorCode]:Sme}});function $Eo(t){return["client_secret_basic","client_secret_post","none"].includes(t)}function Wjr(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&&$Eo(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 zjr(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":qEo(o,s,r);return;case"client_secret_post":HEo(o,s,n);return;case"none":VEo(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function qEo(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 HEo(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function VEo(t,e){e.set("client_id",t)}async function e4t(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=Ujr.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,c=qjr[o]||r7;return new c(s||"",a)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new r7(o)}}async function wO(t,e){var r,n;try{return await Zbt(t,e)}catch(o){if(o instanceof ZU||o instanceof tQ)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Zbt(t,e);if(o instanceof eQ)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await Zbt(t,e);throw o}}async function Zbt(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,c;try{a=await zEo(e,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(c=a.authorization_servers[0])}catch{}c||(c=e);let u=await WEo(e,t,a),d=await ZEo(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 t6o(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 r4t(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 n4t(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 uh)||A instanceof r7))throw A}let h=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:g}=await e6o(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 WEo(t,e,r){let n=jjr(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Gjr({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 xme(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 zEo(t,e,r=fetch){let n=await XEo(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 Fjr.parse(await n.json())}async function t4t(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?t4t(t,void 0,r):void 0;throw n}}function YEo(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Vjr(t,e,r=fetch){return await t4t(t,{"MCP-Protocol-Version":e},r)}function KEo(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function XEo(t,e,r,n){var o,s;let a=new URL(t),c=(o=n?.protocolVersion)!==null&&o!==void 0?o:gJ,u;if(n?.metadataUrl)u=new URL(n.metadataUrl);else{let f=YEo(e,a.pathname);u=new URL(f,(s=n?.metadataServerUrl)!==null&&s!==void 0?s:a),u.search=a.search}let d=await Vjr(u,c,r);if(!n?.metadataUrl&&KEo(d,a.pathname)){let f=new URL(`/.well-known/${e}`,a);d=await Vjr(f,c,r)}return d}function JEo(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 ZEo(t,{fetchFn:e=fetch,protocolVersion:r=gJ}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=JEo(t);for(let{url:s,type:a}of o){let c=await t4t(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"?zbt.parse(await c.json()):Ljr.parse(await c.json())}}}async function e6o(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(Xbt))throw new Error(`Incompatible auth server: does not support response type ${Xbt}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Jbt))throw new Error(`Incompatible auth server: does not support code challenge method ${Jbt}`)}else c=new URL("/authorize",t);let u=await Wbt(),d=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",Xbt),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",Jbt),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 r4t(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=Wjr(r,A);zjr(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 e4t(g);return Ybt.parse(await g.json())}async function n4t(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=Wjr(r,m);zjr(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 e4t(h);return Ybt.parse({refresh_token:n,...await h.json()})}async function t6o(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 e4t(s);return Qjr.parse(await s.json())}var K3,Xbt,Jbt,uBe=te(()=>{Pjr();gO();Kbt();Kbt();$jr();Hjr();K3=class extends Error{constructor(e){super(e??"Unauthorized")}};Xbt="code",Jbt="S256"});var i4t,GJ,Yjr=te(()=>{Bjr();gO();uBe();i4t=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},GJ=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 K3("No auth provider");let r;try{r=await wO(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 K3;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 JU(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}=xme(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 i4t(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=mO.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 K3("No auth provider");if(await wO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new K3("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}=xme(c);if(this._resourceMetadataUrl=d,this._scope=f,await wO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new K3;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 dBe,Kjr=te(()=>{Mbt();dBe=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(s){o=sBe({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 r6o,$J,TO,o4t=te(()=>{gO();uBe();Kjr();r6o={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},$J=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},TO=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:r6o}async _authThenStart(){var e;if(!this._authProvider)throw new K3("No auth provider");let r;try{r=await wO(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 K3;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 $J(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 dBe).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=mO.parse(JSON.parse(m.data));s!==void 0&&Dhe(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 K3("No auth provider");if(await wO(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new K3("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:lke(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 $J(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:v}=xme(p);if(this._resourceMetadataUrl=E,this._scope=v,await wO(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new K3;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){$Fr(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=>mO.parse(v)):[mO.parse(y)];for(let v of E)(s=this.onmessage)===null||s===void 0||s.call(this,v)}else throw new $J(-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 $J(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 n6o}from"node:fs/promises";var wme,Tme,rQ,s4t=te(()=>{"use strict";lue();uBe();yi();(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"})(wme||(wme={}));Tme=class extends Error{code;constructor(e,r){super(r),this.code=e}},rQ=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||EF.default}async start(){if(this._isClosed)throw new Error(N.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 n4t(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(N.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 Tme(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 Tme(void 0,`Failed to create WebSocket: ${a}`))}})}async finishAuth(e){if(!this._authProvider)throw new Error(N.t("websocketClient.errors.noAuthProvider"));try{let r=await this._authProvider.clientInformation();if(r){let n=this._authProvider.redirectUrl.toString(),o=await r4t(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(N.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===EF.default.OPEN?this._websocket.close():this.onclose?.()}async send(e){if(this._isClosed)throw new Error(N.t("websocketClient.errors.transportClosed"));if(!this._websocket)throw new Error(N.t("websocketClient.errors.transportNotStarted"));if(this._websocket.readyState!==EF.default.OPEN)throw new Error(N.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 Tme(void 0,`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async _transformRequest(e){if(e.method==="initialize")return{type:wme.CLI_CONNECT,id:e.id,timestamp:Date.now(),payload:{clientInfo:{version:"0.3.30",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:wme.SHOW_DIFF,id:e.id,timestamp:Date.now(),payload:{filePath:n,originalText:await n6o(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:wme.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 Xjr,fBe,Jjr=te(()=>{"use strict";Xjr=Te(q5e(),1);yi();fBe=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(N.t("mcp.auth.scopesRequired"));this.auth=new Xjr.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(N.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 eGr(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 Zjr(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 Zjr(c,[t],o);return}catch{continue}}throw new Error(`Failed to open browser: ${s instanceof Error?s.message:"Unknown error"}`)}}var Zjr,tGr=te(()=>{"use strict";Zjr=o6o(i6o)});function Mo(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 a4t(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 hBe(r.error.message);case 401:return new IO(r.error.message);case 403:return new pBe(r.error.message);default:}}return t}function l6o(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}var pBe,IO,hBe,td=te(()=>{"use strict";pBe=class extends Error{},IO=class extends Error{},hBe=class extends Error{}});import{promises as qJ}from"node:fs";import*as mBe from"node:path";import*as rGr from"node:os";var Zm,gBe=te(()=>{"use strict";td();yi();Zm=class{static TOKEN_FILE="mcp-oauth-tokens.json";static CONFIG_DIR=".iflow";static getTokenFilePath(){let e=rGr.homedir();return mBe.join(e,this.CONFIG_DIR,this.TOKEN_FILE)}static async ensureConfigDir(){let e=mBe.dirname(this.getTokenFilePath());await qJ.mkdir(e,{recursive:!0})}static async loadTokens(){let e=new Map;try{let r=this.getTokenFilePath(),n=await qJ.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(N.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 qJ.writeFile(d,JSON.stringify(u,null,2),{mode:384})}catch(f){throw console.error(N.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 qJ.unlink(o):await qJ.writeFile(o,JSON.stringify(n,null,2),{mode:384})}catch(s){console.error(N.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 qJ.unlink(e)}catch(e){e.code!=="ENOENT"&&console.error(N.t("mcp.tokenStorage.errors.failedToClearTokens",{error:_r(e)}))}}}});var eg,ABe=te(()=>{"use strict";td();yi();eg=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(N.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(N.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(N.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(N.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 nGr from"node:http";import*as Ime from"node:crypto";import{URL as c4t}from"node:url";var B_,l4t=te(()=>{"use strict";tGr();gBe();td();ABe();yi();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(N.t("mcp.auth.clientRegistrationFailed",{status:s.status,statusText:s.statusText,error:a}))}return await s.json()}static async discoverOAuthFromMCPServer(e){let r=eg.extractBaseUrl(e);return eg.discoverOAuthConfig(r)}static generatePKCEParams(){let e=Ime.randomBytes(32).toString("base64url"),r=Ime.createHash("sha256").update(e).digest("base64url"),n=Ime.randomBytes(16).toString("base64url");return{codeVerifier:e,codeChallenge:r,state:n}}static async startCallbackServer(e){return new Promise((r,n)=>{let o=nGr.createServer(async(s,a)=>{try{let c=new c4t(s.url,`http://localhost:${this.REDIRECT_PORT}`);if(c.pathname!==this.REDIRECT_PATH){a.writeHead(404),a.end(N.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(`
965
965
  <html>
966
966
  <body>
967
967
  <h1>${N.t("mcp.ui.authenticationFailed")}</h1>
@@ -4538,7 +4538,7 @@ ${g.join(`
4538
4538
  `,e-1),[o,s]=tsa(r);return{line:n===-1?o:t.slice(0,n+1).match(/\n/g).length+o,column:e-n-1+s}}function ner(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 rsa(t,e,r)}var nsa=t=>`\\u{${t.codePointAt(0).toString(16)}}`,ier=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??=`${osa(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:e}=this;return`${this.#r}${this.fileName?` in ${this.fileName}`:""}${e?`
4539
4539
 
4540
4540
  ${e}
4541
- `:""}`}set message(e){this.#r=e}#o(e){if(!this.#t)return;let r=this.#e,n=isa(r,this.#t.message);if(n)return(0,$ri.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}},isa=(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)}:ner(t,Number(n),{oneBased:!0})},osa=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${nsa(n)})`);function oer(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new ier({jsonParseError:n,fileName:r,input:t})}}var Zni=Te(Xni(),1);import{fileURLToPath as Iaa}from"node:url";function Jni(t){return t instanceof URL?Iaa(t):t}var Naa=t=>Raa.resolve(Jni(t)??".","package.json"),Oaa=(t,e)=>{let r=typeof t=="string"?oer(t):t;return e&&(0,Zni.default)(r),r};async function eii({cwd:t,normalize:e=!0}={}){let r=await Daa.readFile(Naa(t),"utf8");return Oaa(r,e)}async function tii(t){let e=await yri("package.json",t);if(e)return{packageJson:await eii({...t,cwd:kaa.dirname(e)}),path:e}}import{fileURLToPath as Baa}from"url";import Paa from"path";var Maa=Baa(import.meta.url),Faa=Paa.dirname(Maa),Wtt;async function ZP(){if(Wtt)return Wtt;let t=await tii({cwd:Faa});if(t)return Wtt=t.packageJson,Wtt}async function eM(){let t=await ZP();return"0.3.29-beta.2"}var L6e=Te(lii(),1);import*as uii from"node:os";var dii=["docker","podman","sandbox-exec"];function Vaa(t){return dii.includes(t)}function Waa(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(Vaa(t)||(console.error(`ERROR: invalid sandbox command '${t}'. Must be one of ${dii.join(", ")}`),process.exit(1)),L6e.default.sync(t))return t;console.error(`ERROR: missing sandbox command '${t}' (from IFLOW_SANDBOX)`),process.exit(1)}return uii.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 fii(t,e){let r=e.sandbox??t.sandbox,n=Waa(r),o=await ZP(),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}vl();Gt();import*as Rer from"path";import{homedir as zaa}from"os";import*as U6e from"fs";function Yaa(t){try{let e=Rer.resolve(t),r=Rer.resolve(zaa()),n=U6e.existsSync(e)?U6e.realpathSync(e):e,o=U6e.realpathSync(r);return n===o}catch{return!1}}async function Kaa(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"&&Yaa(m)&&(console.log(N.t("mcpAdd.info.detectedHomeDirectory")),o="user");let g=o==="user"?"User":"Workspace",A=El(process.cwd()),y={},E=c?.reduce((w,R)=>{let[D,...P]=R.split(":"),I=P.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,P]=R.split("=");return D&&P&&(w[D]=P),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(N.t("mcpAdd.info.serverAlreadyConfigured",{name:t,scope:o})),b[t]=y,A.setValue(g,"mcpServers",b),console.log(S?N.t("mcpAdd.info.serverUpdated",{name:t,scope:o}):N.t("mcpAdd.info.serverAdded",{name:t,scope:o,transport:s}))}var pii={command:"add <name> <commandOrUrl> [args...]",describe:N.t("mcpAdd.description"),builder:t=>t.usage(N.t("mcpAdd.usage")).parserConfiguration({"unknown-options-as-args":!0,"populate--":!0}).positional("name",{describe:N.t("mcpAdd.options.name"),type:"string",demandOption:!0}).positional("commandOrUrl",{describe:N.t("mcpAdd.options.commandOrUrl"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:N.t("mcpAdd.options.scope"),type:"string",default:"project",choices:["user","project"]}).option("transport",{alias:"t",describe:N.t("mcpAdd.options.transport"),type:"string",default:"stdio",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:N.t("mcpAdd.options.env"),type:"array",string:!0}).option("header",{alias:"H",describe:N.t("mcpAdd.options.header"),type:"array",string:!0}).option("timeout",{describe:N.t("mcpAdd.options.timeout"),type:"number"}).option("trust",{describe:N.t("mcpAdd.options.trust"),type:"boolean"}).option("description",{describe:N.t("mcpAdd.options.description"),type:"string"}).option("include-tools",{describe:N.t("mcpAdd.options.includeTools"),type:"array",string:!0}).option("exclude-tools",{describe:N.t("mcpAdd.options.excludeTools"),type:"array",string:!0}).middleware(e=>{if(e["--"]){let r=e.args||[];e.args=[...r,...e["--"]]}}),handler:async t=>{await Kaa(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})}};vl();Gt();async function Xaa(t,e){let{scope:r}=e,n=r==="user"?"User":"Workspace",o=El(process.cwd()),a=o.forScope(n).settings.mcpServers||{};if(!a[t]){console.log(N.t("mcpRemove.errors.serverNotFound",{name:t,scope:r}));return}delete a[t],o.setValue(n,"mcpServers",a),console.log(N.t("mcpRemove.info.serverRemoved",{name:t,scope:r}))}var hii={command:"remove <name>",describe:N.t("mcpRemove.description"),builder:t=>t.usage(N.t("mcpRemove.usage")).positional("name",{describe:N.t("mcpRemove.options.name"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:N.t("mcpRemove.options.scope"),type:"string",default:"project",choices:["user","project"]}),handler:async t=>{await Xaa(t.name,{scope:t.scope})}};vl();Gt();kJ();var Jaa="\x1B[32m",Zaa="\x1B[33m",eca="\x1B[31m",Ner="\x1B[0m";async function tca(){let t=El(process.cwd()),e=YP(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 rca(t,e){let r=new k_({name:"mcp-test-client",version:"0.0.1"}),n;try{n=await Ome(t,e,!1)}catch{return await r.close(),Rs.DISCONNECTED}try{return await r.connect(n,{timeout:5e3}),await r.ping(),await r.close(),Rs.CONNECTED}catch{return await n.close(),Rs.DISCONNECTED}}async function nca(t,e){return await rca(t,e)}async function ica(){let t=await tca(),e=Object.keys(t);if(e.length===0){console.log(N.t("mcpList.info.noServersConfigured"));return}console.log(N.t("mcpList.info.configuredServers"));for(let r of e){let n=t[r],o=await nca(r,n),s="",a="";switch(o){case Rs.CONNECTED:s=Jaa+"\u2713"+Ner,a=N.t("mcpList.status.connected");break;case Rs.CONNECTING:s=Zaa+"\u2026"+Ner,a=N.t("mcpList.status.connecting");break;case Rs.DISCONNECTED:default:s=eca+"\u2717"+Ner,a=N.t("mcpList.status.disconnected");break}let c=`${r}: `;if(n.httpUrl)c+=N.t("mcpList.info.serverInfoHttp",{url:n.httpUrl});else if(n.url)c+=N.t("mcpList.info.serverInfoSse",{url:n.url});else if(n.command){let u=n.args?.join(" ")||"";c+=N.t("mcpList.info.serverInfoStdio",{command:n.command,args:u})}console.log(N.t("mcpList.info.serverStatusLine",{statusIndicator:s,serverInfo:c,statusText:a}))}}var mii={command:"list",describe:N.t("mcpList.description"),handler:async()=>{await ica()}};vl();Gt();import*as Oer from"path";import{homedir as oca}from"os";import*as Q6e from"fs";import{execSync as sca}from"child_process";function aca(t){try{let e=Oer.resolve(t),r=Oer.resolve(oca()),n=Q6e.existsSync(e)?Q6e.realpathSync(e):e,o=Q6e.realpathSync(r);return n===o}catch{return!1}}function cca(){try{return sca("uv --version",{stdio:"pipe"}),!0}catch{return!1}}function lca(t){return t.search(/uvx/)!==-1}async function uca(t,e,r){let{scope:n}=r,o=process.cwd();n==="project"&&aca(o)&&(console.log(N.t("mcpAdd.info.detectedHomeDirectory")),n="user");let s=n==="user"?"User":"Workspace",a=El(process.cwd()),c;try{c=JSON.parse(e)}catch(m){console.error(N.t("mcpAddJson.errors.invalidJson")),console.error(m);return}if(typeof c!="object"||c===null||Array.isArray(c)){console.error(N.t("mcpAddJson.errors.mustBeObject"));return}let u=c,d=u;if(d.command&&lca(d.command)&&!cca()){console.error(N.t("mcpAddJson.errors.uvxRequiresUv")),console.error(N.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(N.t("mcpAddJson.errors.noTransport"));return}let p=a.forScope(s).settings.mcpServers||{},h=!!p[t];h&&console.log(N.t("mcpAdd.info.serverAlreadyConfigured",{name:t,scope:n})),p[t]=u,a.setValue(s,"mcpServers",p),console.log(h?N.t("mcpAdd.info.serverUpdated",{name:t,scope:n}):N.t("mcpAddJson.info.serverAdded",{name:t,scope:n})),d.command?(console.log(N.t("mcpAddJson.info.transportStdio")),console.log(N.t("mcpAddJson.info.command",{command:d.command})),d.args&&Array.isArray(d.args)&&d.args.length>0&&console.log(N.t("mcpAddJson.info.arguments",{args:d.args.join(" ")}))):d.url?(console.log(N.t("mcpAddJson.info.transportSse")),console.log(N.t("mcpAddJson.info.url",{url:d.url}))):d.httpUrl?(console.log(N.t("mcpAddJson.info.transportHttp")),console.log(N.t("mcpAddJson.info.url",{url:d.httpUrl}))):d.tcp&&(console.log(N.t("mcpAddJson.info.transportWebsocket")),console.log(N.t("mcpAddJson.info.tcp",{tcp:d.tcp}))),d.description&&console.log(N.t("mcpAddJson.info.description",{description:d.description})),d.env&&typeof d.env=="object"&&Object.keys(d.env).length>0&&console.log(N.t("mcpAddJson.info.envVars",{vars:Object.keys(d.env).join(", ")})),d.headers&&typeof d.headers=="object"&&Object.keys(d.headers).length>0&&console.log(N.t("mcpAddJson.info.headers",{headers:Object.keys(d.headers).join(", ")})),d.oauth?.enabled&&console.log(N.t("mcpAddJson.info.oauthEnabled"))}var gii={command:"add-json <name> <json>",describe:N.t("mcpAddJson.description"),builder:t=>t.usage(N.t("mcpAddJson.usage")).positional("name",{describe:N.t("mcpAdd.options.name"),type:"string",demandOption:!0}).positional("json",{describe:N.t("mcpAddJson.options.json"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:N.t("mcpAdd.options.scope"),type:"string",default:"project",choices:["user","project"]}),handler:async t=>{await uca(t.name,t.json,{scope:t.scope})}};vl();Gt();async function dca(){let t=El(process.cwd()),e=YP(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 fca(t){let e=await dca();if(!e[t]){console.log(N.t("mcpGet.errors.serverNotFound",{name:t}));return}let r=e[t];if(console.log(N.t("mcpGet.info.serverTitle",{name:t})),console.log(),console.log(N.t("mcpGet.info.configuration")),r.command?(console.log(N.t("mcpGet.info.transportStdio")),console.log(N.t("mcpGet.info.command",{command:r.command})),r.args&&r.args.length>0&&(console.log(N.t("mcpGet.info.arguments")),r.args.forEach((n,o)=>{console.log(N.t("mcpGet.info.argumentItem",{index:o,arg:n}))}))):r.url?(console.log(N.t("mcpGet.info.transportSse")),console.log(N.t("mcpGet.info.url",{url:r.url}))):r.httpUrl?(console.log(N.t("mcpGet.info.transportHttp")),console.log(N.t("mcpGet.info.url",{url:r.httpUrl}))):console.log(N.t("mcpGet.info.transportUnknown")),r.env&&Object.keys(r.env).length>0){console.log(N.t("mcpGet.info.environmentVariables"));for(let[n,o]of Object.entries(r.env))console.log(N.t("mcpGet.info.envVar",{key:n,value:o}))}if(r.headers&&Object.keys(r.headers).length>0){console.log(N.t("mcpGet.info.headers"));for(let[n,o]of Object.entries(r.headers))console.log(N.t("mcpGet.info.header",{key:n,value:o}))}r.description&&console.log(N.t("mcpGet.info.description",{description:r.description})),r.timeout!==void 0&&console.log(N.t("mcpGet.info.timeout",{timeout:r.timeout})),r.trust!==void 0&&console.log(N.t("mcpGet.info.trusted",{trusted:r.trust?N.t("mcpGet.common.yes"):N.t("mcpGet.common.no")})),r.includeTools&&r.includeTools.length>0&&(console.log(N.t("mcpGet.info.includeTools")),r.includeTools.forEach((n,o)=>{console.log(N.t("mcpGet.info.toolItem",{index:o,tool:n}))})),r.excludeTools&&r.excludeTools.length>0&&(console.log(N.t("mcpGet.info.excludeTools")),r.excludeTools.forEach((n,o)=>{console.log(N.t("mcpGet.info.toolItem",{index:o,tool:n}))})),r.extensionName&&console.log(N.t("mcpGet.info.extension",{extension:r.extensionName})),console.log(),console.log(N.t("mcpGet.info.rawJsonConfiguration")),console.log(JSON.stringify(r,null,2))}var Aii={command:"get <name>",describe:N.t("mcpGet.description"),builder:t=>t.usage(N.t("mcpGet.usage")).positional("name",{describe:N.t("mcpGet.options.name"),type:"string",demandOption:!0}),handler:async t=>{await fca(t.name)}};sG();Gt();import*as Ytt from"fs";import*as yii from"path";async function pca(){let t=process.cwd();try{let e=await Yv("**/.mcp.json",{cwd:t,absolute:!0,ignore:["**/node_modules/**","**/.*/**"]});if(e.length===0){console.log(N.t("mcpResetProjectChoices.info.noFilesFound"));return}console.log(N.t("mcpResetProjectChoices.info.foundFiles",{count:e.length}));let r=0,n=0;for(let o of e){let s=yii.relative(t,o);try{let a=Ytt.readFileSync(o,"utf8"),c;try{c=JSON.parse(a)}catch{console.log(N.t("mcpResetProjectChoices.info.invalidJson",{path:s}));continue}c.approvedServers||c.rejectedServers||c.mcpServerChoices?(Ytt.unlinkSync(o),console.log(N.t("mcpResetProjectChoices.info.fileDeleted",{path:s})),r++):console.log(N.t("mcpResetProjectChoices.info.noChoicesSkipping",{path:s}))}catch(a){console.log(N.t("mcpResetProjectChoices.errors.fileError",{path:s,error:a})),n++}}console.log(),console.log(N.t("mcpResetProjectChoices.info.summary")),console.log(N.t("mcpResetProjectChoices.info.deletedFiles",{count:r})),n>0&&console.log(N.t("mcpResetProjectChoices.info.errorFiles",{count:n})),r>0&&(console.log(),console.log(N.t("mcpResetProjectChoices.info.resetComplete")),console.log(N.t("mcpResetProjectChoices.info.extensionPrompt")))}catch(e){console.error(N.t("mcpResetProjectChoices.errors.searchError"),e)}}var _ii={command:"reset-project-choices",describe:N.t("mcpResetProjectChoices.description"),builder:t=>t.usage(N.t("mcpResetProjectChoices.usage")),handler:async()=>{await pca()}};Gt();var Eii={command:"mcp",describe:N.t("mcpCommand.description"),builder:t=>t.command(pii).command(hii).command(mii).command(gii).command(Aii).command(_ii).demandCommand(1,N.t("mcpCommand.demandCommand")).version(!1),handler:()=>{}};Fer();Uer();vl();Gt();import Bg from"fs/promises";import q5 from"path";import Jca from"os";var Zca=async(t,e=1,r=20)=>{try{if(!t)return{success:!1,message:N.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=N.t("workflowAdd.unableToLoadWorkflows");return o.status===401?c=N.t("workflowAdd.authenticationFailed"):o.status===403?c=N.t("workflowAdd.accessDenied"):o.status===404?c=N.t("workflowAdd.serviceNotFound"):o.status>=500&&(c=N.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||N.t("workflowAdd.failedToLoadFromServer")}}catch(n){let o=N.t("workflowAdd.connectionError");return n instanceof Error&&n.message.includes("Failed to fetch")&&(o=N.t("workflowAdd.networkError")),{success:!1,message:o}}},ela=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||N.t("workflowAdd.failedToFetchDetails"));return n.data||null}catch(r){return console.error(N.t("workflowAdd.failedToFetchDetails"),r),null}},tla=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 Bg.writeFile(e,Buffer.from(n))},rla=t=>{let e=new URL(t).pathname;return q5.extname(e).toLowerCase()},nla=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}},ila=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 nla(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(`\u2705 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"}`)},ola=async(t,e,r)=>{try{switch(r){case".zip":await ila(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}`)}},sla=async t=>{try{let e=await Bg.readFile(t,{flag:"r"});if(e.length>=4){let r=e.readUInt32BE(0);return r===333319||r===333312}return!1}catch{return!1}},Kii=async t=>{try{let e=await Bg.readdir(t,{withFileTypes:!0});for(let r of e){let n=q5.join(t,r.name);if(r.isDirectory())await Kii(n),r.name==="__MACOSX"&&await Bg.rm(n,{recursive:!0,force:!0});else{let o=!1;(r.name===".DS_Store"||r.name.startsWith("._")&&await sla(n))&&(o=!0),o&&await Bg.rm(n,{force:!0})}}}catch(e){console.warn(`Warning: Failed to clean up macOS files in ${t}: ${e}`)}},ala=async(t,e,r)=>{try{let n;try{n=JSON.parse(t.extInfo)}catch(u){return{success:!1,message:N.t("workflowAdd.invalidExtInfo",{error:u instanceof Error?u.message:String(u)})}}if(!n.url)return{success:!1,message:N.t("workflowAdd.noDownloadUrl")};let o=rla(n.url),s=await Bg.mkdtemp(q5.join(Jca.tmpdir(),"iflow-workflow-")),a=q5.join(s,`workflow${o}`),c=q5.join(s,"extracted");try{console.log(N.t("workflowAdd.downloading",{url:n.url})),await tla(n.url,a),console.log(N.t("workflowAdd.extracting")),await Bg.mkdir(c,{recursive:!0}),await ola(a,c,o),await Kii(c);let u=await cla(c);console.log(N.t("workflowAdd.copyingFiles"));let d=e||process.cwd(),f=await Bg.readdir(c);for(let p of f){let h=q5.join(c,p),m=q5.join(d,p);(await Bg.stat(h)).isDirectory()?(console.log(`Copying directory: ${h} -> ${m}`),await Xii(h,m)):(console.log(`\u{1F4C4} Copying file: ${h} -> ${m}`),await Bg.copyFile(h,m))}return u&&await lla(d),await Bg.rm(s,{recursive:!0,force:!0}),{success:!0,message:N.t("workflowAdd.installSuccess",{workflowName:r,targetDir:d})}}catch(u){try{await Bg.rm(s,{recursive:!0,force:!0})}catch{}throw u}}catch(n){let o=n instanceof Error?n.message:String(n);return{success:!1,message:N.t("workflowAdd.installFailed",{workflowName:r,error:o})}}},Xii=async(t,e)=>{await Bg.mkdir(e,{recursive:!0});let r=await Bg.readdir(t,{withFileTypes:!0});for(let n of r){let o=q5.join(t,n.name),s=q5.join(e,n.name);n.isDirectory()?await Xii(o,s):await Bg.copyFile(o,s)}},cla=async t=>{let e=q5.join(t,"command_setup.sh");try{return await Bg.access(e,Bg.constants.F_OK),console.log("\u{1F50D} Detected command_setup.sh in workflow"),!0}catch{return!1}},lla=async t=>{let e=q5.join(t,"command_setup.sh");try{console.log("\u{1F527} Executing command_setup.sh..."),await Bg.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("\u2705 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 ula(t){let r=El(process.cwd()).merged.apiKey;r||(console.error(N.t("workflowAdd.apiKeyNotFound")),console.error(N.t("workflowAdd.pleaseAuthenticate")),process.exit(1)),console.log(N.t("workflowAdd.searching",{nameOrId:t}));try{let n=null;if(/^\d+$/.test(t)){let u=parseInt(t,10);n=await ela(r,u)}if(!n){let u=await Zca(r,1,500);u.success||(console.error(N.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(N.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(N.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(N.t("workflowAdd.workflowDescription",{description:s})),console.log(N.t("workflowAdd.installing"));let a=process.cwd(),c=await ala(n,a,o);c.success?console.log(c.message):(console.error(c.message),process.exit(1))}catch(n){console.error(N.t("workflowAdd.errorAdding",{error:n})),process.exit(1)}}var Jii={command:"add <name-or-id>",describe:N.t("workflowAdd.description"),builder:t=>t.usage(N.t("workflowAdd.usage")).positional("name-or-id",{describe:N.t("workflowAdd.workflowIdOrNumericIdOption"),type:"string",demandOption:!0}),handler:async t=>{await ula(t["name-or-id"])}};Gt();var Zii={command:"workflow",describe:N.t("workflowCommand.description"),builder:t=>t.command(Jii).demandCommand(1,N.t("workflowCommand.demandCommand")).version(!1),handler:()=>{}};var Ger={debug:(...t)=>console.debug("[DEBUG]",...t),warn:(...t)=>console.warn("[WARN]",...t),error:(...t)=>console.error("[ERROR]",...t)};function fla(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 trt(){let t=fla(gm.argv),e=Mti(RZt(t)).locale("en").scriptName("iflow").usage(`Usage: iflow [options] [command]
4541
+ `:""}`}set message(e){this.#r=e}#o(e){if(!this.#t)return;let r=this.#e,n=isa(r,this.#t.message);if(n)return(0,$ri.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}},isa=(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)}:ner(t,Number(n),{oneBased:!0})},osa=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${nsa(n)})`);function oer(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new ier({jsonParseError:n,fileName:r,input:t})}}var Zni=Te(Xni(),1);import{fileURLToPath as Iaa}from"node:url";function Jni(t){return t instanceof URL?Iaa(t):t}var Naa=t=>Raa.resolve(Jni(t)??".","package.json"),Oaa=(t,e)=>{let r=typeof t=="string"?oer(t):t;return e&&(0,Zni.default)(r),r};async function eii({cwd:t,normalize:e=!0}={}){let r=await Daa.readFile(Naa(t),"utf8");return Oaa(r,e)}async function tii(t){let e=await yri("package.json",t);if(e)return{packageJson:await eii({...t,cwd:kaa.dirname(e)}),path:e}}import{fileURLToPath as Baa}from"url";import Paa from"path";var Maa=Baa(import.meta.url),Faa=Paa.dirname(Maa),Wtt;async function ZP(){if(Wtt)return Wtt;let t=await tii({cwd:Faa});if(t)return Wtt=t.packageJson,Wtt}async function eM(){let t=await ZP();return"0.3.30"}var L6e=Te(lii(),1);import*as uii from"node:os";var dii=["docker","podman","sandbox-exec"];function Vaa(t){return dii.includes(t)}function Waa(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(Vaa(t)||(console.error(`ERROR: invalid sandbox command '${t}'. Must be one of ${dii.join(", ")}`),process.exit(1)),L6e.default.sync(t))return t;console.error(`ERROR: missing sandbox command '${t}' (from IFLOW_SANDBOX)`),process.exit(1)}return uii.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 fii(t,e){let r=e.sandbox??t.sandbox,n=Waa(r),o=await ZP(),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}vl();Gt();import*as Rer from"path";import{homedir as zaa}from"os";import*as U6e from"fs";function Yaa(t){try{let e=Rer.resolve(t),r=Rer.resolve(zaa()),n=U6e.existsSync(e)?U6e.realpathSync(e):e,o=U6e.realpathSync(r);return n===o}catch{return!1}}async function Kaa(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"&&Yaa(m)&&(console.log(N.t("mcpAdd.info.detectedHomeDirectory")),o="user");let g=o==="user"?"User":"Workspace",A=El(process.cwd()),y={},E=c?.reduce((w,R)=>{let[D,...P]=R.split(":"),I=P.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,P]=R.split("=");return D&&P&&(w[D]=P),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(N.t("mcpAdd.info.serverAlreadyConfigured",{name:t,scope:o})),b[t]=y,A.setValue(g,"mcpServers",b),console.log(S?N.t("mcpAdd.info.serverUpdated",{name:t,scope:o}):N.t("mcpAdd.info.serverAdded",{name:t,scope:o,transport:s}))}var pii={command:"add <name> <commandOrUrl> [args...]",describe:N.t("mcpAdd.description"),builder:t=>t.usage(N.t("mcpAdd.usage")).parserConfiguration({"unknown-options-as-args":!0,"populate--":!0}).positional("name",{describe:N.t("mcpAdd.options.name"),type:"string",demandOption:!0}).positional("commandOrUrl",{describe:N.t("mcpAdd.options.commandOrUrl"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:N.t("mcpAdd.options.scope"),type:"string",default:"project",choices:["user","project"]}).option("transport",{alias:"t",describe:N.t("mcpAdd.options.transport"),type:"string",default:"stdio",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:N.t("mcpAdd.options.env"),type:"array",string:!0}).option("header",{alias:"H",describe:N.t("mcpAdd.options.header"),type:"array",string:!0}).option("timeout",{describe:N.t("mcpAdd.options.timeout"),type:"number"}).option("trust",{describe:N.t("mcpAdd.options.trust"),type:"boolean"}).option("description",{describe:N.t("mcpAdd.options.description"),type:"string"}).option("include-tools",{describe:N.t("mcpAdd.options.includeTools"),type:"array",string:!0}).option("exclude-tools",{describe:N.t("mcpAdd.options.excludeTools"),type:"array",string:!0}).middleware(e=>{if(e["--"]){let r=e.args||[];e.args=[...r,...e["--"]]}}),handler:async t=>{await Kaa(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})}};vl();Gt();async function Xaa(t,e){let{scope:r}=e,n=r==="user"?"User":"Workspace",o=El(process.cwd()),a=o.forScope(n).settings.mcpServers||{};if(!a[t]){console.log(N.t("mcpRemove.errors.serverNotFound",{name:t,scope:r}));return}delete a[t],o.setValue(n,"mcpServers",a),console.log(N.t("mcpRemove.info.serverRemoved",{name:t,scope:r}))}var hii={command:"remove <name>",describe:N.t("mcpRemove.description"),builder:t=>t.usage(N.t("mcpRemove.usage")).positional("name",{describe:N.t("mcpRemove.options.name"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:N.t("mcpRemove.options.scope"),type:"string",default:"project",choices:["user","project"]}),handler:async t=>{await Xaa(t.name,{scope:t.scope})}};vl();Gt();kJ();var Jaa="\x1B[32m",Zaa="\x1B[33m",eca="\x1B[31m",Ner="\x1B[0m";async function tca(){let t=El(process.cwd()),e=YP(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 rca(t,e){let r=new k_({name:"mcp-test-client",version:"0.0.1"}),n;try{n=await Ome(t,e,!1)}catch{return await r.close(),Rs.DISCONNECTED}try{return await r.connect(n,{timeout:5e3}),await r.ping(),await r.close(),Rs.CONNECTED}catch{return await n.close(),Rs.DISCONNECTED}}async function nca(t,e){return await rca(t,e)}async function ica(){let t=await tca(),e=Object.keys(t);if(e.length===0){console.log(N.t("mcpList.info.noServersConfigured"));return}console.log(N.t("mcpList.info.configuredServers"));for(let r of e){let n=t[r],o=await nca(r,n),s="",a="";switch(o){case Rs.CONNECTED:s=Jaa+"\u2713"+Ner,a=N.t("mcpList.status.connected");break;case Rs.CONNECTING:s=Zaa+"\u2026"+Ner,a=N.t("mcpList.status.connecting");break;case Rs.DISCONNECTED:default:s=eca+"\u2717"+Ner,a=N.t("mcpList.status.disconnected");break}let c=`${r}: `;if(n.httpUrl)c+=N.t("mcpList.info.serverInfoHttp",{url:n.httpUrl});else if(n.url)c+=N.t("mcpList.info.serverInfoSse",{url:n.url});else if(n.command){let u=n.args?.join(" ")||"";c+=N.t("mcpList.info.serverInfoStdio",{command:n.command,args:u})}console.log(N.t("mcpList.info.serverStatusLine",{statusIndicator:s,serverInfo:c,statusText:a}))}}var mii={command:"list",describe:N.t("mcpList.description"),handler:async()=>{await ica()}};vl();Gt();import*as Oer from"path";import{homedir as oca}from"os";import*as Q6e from"fs";import{execSync as sca}from"child_process";function aca(t){try{let e=Oer.resolve(t),r=Oer.resolve(oca()),n=Q6e.existsSync(e)?Q6e.realpathSync(e):e,o=Q6e.realpathSync(r);return n===o}catch{return!1}}function cca(){try{return sca("uv --version",{stdio:"pipe"}),!0}catch{return!1}}function lca(t){return t.search(/uvx/)!==-1}async function uca(t,e,r){let{scope:n}=r,o=process.cwd();n==="project"&&aca(o)&&(console.log(N.t("mcpAdd.info.detectedHomeDirectory")),n="user");let s=n==="user"?"User":"Workspace",a=El(process.cwd()),c;try{c=JSON.parse(e)}catch(m){console.error(N.t("mcpAddJson.errors.invalidJson")),console.error(m);return}if(typeof c!="object"||c===null||Array.isArray(c)){console.error(N.t("mcpAddJson.errors.mustBeObject"));return}let u=c,d=u;if(d.command&&lca(d.command)&&!cca()){console.error(N.t("mcpAddJson.errors.uvxRequiresUv")),console.error(N.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(N.t("mcpAddJson.errors.noTransport"));return}let p=a.forScope(s).settings.mcpServers||{},h=!!p[t];h&&console.log(N.t("mcpAdd.info.serverAlreadyConfigured",{name:t,scope:n})),p[t]=u,a.setValue(s,"mcpServers",p),console.log(h?N.t("mcpAdd.info.serverUpdated",{name:t,scope:n}):N.t("mcpAddJson.info.serverAdded",{name:t,scope:n})),d.command?(console.log(N.t("mcpAddJson.info.transportStdio")),console.log(N.t("mcpAddJson.info.command",{command:d.command})),d.args&&Array.isArray(d.args)&&d.args.length>0&&console.log(N.t("mcpAddJson.info.arguments",{args:d.args.join(" ")}))):d.url?(console.log(N.t("mcpAddJson.info.transportSse")),console.log(N.t("mcpAddJson.info.url",{url:d.url}))):d.httpUrl?(console.log(N.t("mcpAddJson.info.transportHttp")),console.log(N.t("mcpAddJson.info.url",{url:d.httpUrl}))):d.tcp&&(console.log(N.t("mcpAddJson.info.transportWebsocket")),console.log(N.t("mcpAddJson.info.tcp",{tcp:d.tcp}))),d.description&&console.log(N.t("mcpAddJson.info.description",{description:d.description})),d.env&&typeof d.env=="object"&&Object.keys(d.env).length>0&&console.log(N.t("mcpAddJson.info.envVars",{vars:Object.keys(d.env).join(", ")})),d.headers&&typeof d.headers=="object"&&Object.keys(d.headers).length>0&&console.log(N.t("mcpAddJson.info.headers",{headers:Object.keys(d.headers).join(", ")})),d.oauth?.enabled&&console.log(N.t("mcpAddJson.info.oauthEnabled"))}var gii={command:"add-json <name> <json>",describe:N.t("mcpAddJson.description"),builder:t=>t.usage(N.t("mcpAddJson.usage")).positional("name",{describe:N.t("mcpAdd.options.name"),type:"string",demandOption:!0}).positional("json",{describe:N.t("mcpAddJson.options.json"),type:"string",demandOption:!0}).option("scope",{alias:"s",describe:N.t("mcpAdd.options.scope"),type:"string",default:"project",choices:["user","project"]}),handler:async t=>{await uca(t.name,t.json,{scope:t.scope})}};vl();Gt();async function dca(){let t=El(process.cwd()),e=YP(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 fca(t){let e=await dca();if(!e[t]){console.log(N.t("mcpGet.errors.serverNotFound",{name:t}));return}let r=e[t];if(console.log(N.t("mcpGet.info.serverTitle",{name:t})),console.log(),console.log(N.t("mcpGet.info.configuration")),r.command?(console.log(N.t("mcpGet.info.transportStdio")),console.log(N.t("mcpGet.info.command",{command:r.command})),r.args&&r.args.length>0&&(console.log(N.t("mcpGet.info.arguments")),r.args.forEach((n,o)=>{console.log(N.t("mcpGet.info.argumentItem",{index:o,arg:n}))}))):r.url?(console.log(N.t("mcpGet.info.transportSse")),console.log(N.t("mcpGet.info.url",{url:r.url}))):r.httpUrl?(console.log(N.t("mcpGet.info.transportHttp")),console.log(N.t("mcpGet.info.url",{url:r.httpUrl}))):console.log(N.t("mcpGet.info.transportUnknown")),r.env&&Object.keys(r.env).length>0){console.log(N.t("mcpGet.info.environmentVariables"));for(let[n,o]of Object.entries(r.env))console.log(N.t("mcpGet.info.envVar",{key:n,value:o}))}if(r.headers&&Object.keys(r.headers).length>0){console.log(N.t("mcpGet.info.headers"));for(let[n,o]of Object.entries(r.headers))console.log(N.t("mcpGet.info.header",{key:n,value:o}))}r.description&&console.log(N.t("mcpGet.info.description",{description:r.description})),r.timeout!==void 0&&console.log(N.t("mcpGet.info.timeout",{timeout:r.timeout})),r.trust!==void 0&&console.log(N.t("mcpGet.info.trusted",{trusted:r.trust?N.t("mcpGet.common.yes"):N.t("mcpGet.common.no")})),r.includeTools&&r.includeTools.length>0&&(console.log(N.t("mcpGet.info.includeTools")),r.includeTools.forEach((n,o)=>{console.log(N.t("mcpGet.info.toolItem",{index:o,tool:n}))})),r.excludeTools&&r.excludeTools.length>0&&(console.log(N.t("mcpGet.info.excludeTools")),r.excludeTools.forEach((n,o)=>{console.log(N.t("mcpGet.info.toolItem",{index:o,tool:n}))})),r.extensionName&&console.log(N.t("mcpGet.info.extension",{extension:r.extensionName})),console.log(),console.log(N.t("mcpGet.info.rawJsonConfiguration")),console.log(JSON.stringify(r,null,2))}var Aii={command:"get <name>",describe:N.t("mcpGet.description"),builder:t=>t.usage(N.t("mcpGet.usage")).positional("name",{describe:N.t("mcpGet.options.name"),type:"string",demandOption:!0}),handler:async t=>{await fca(t.name)}};sG();Gt();import*as Ytt from"fs";import*as yii from"path";async function pca(){let t=process.cwd();try{let e=await Yv("**/.mcp.json",{cwd:t,absolute:!0,ignore:["**/node_modules/**","**/.*/**"]});if(e.length===0){console.log(N.t("mcpResetProjectChoices.info.noFilesFound"));return}console.log(N.t("mcpResetProjectChoices.info.foundFiles",{count:e.length}));let r=0,n=0;for(let o of e){let s=yii.relative(t,o);try{let a=Ytt.readFileSync(o,"utf8"),c;try{c=JSON.parse(a)}catch{console.log(N.t("mcpResetProjectChoices.info.invalidJson",{path:s}));continue}c.approvedServers||c.rejectedServers||c.mcpServerChoices?(Ytt.unlinkSync(o),console.log(N.t("mcpResetProjectChoices.info.fileDeleted",{path:s})),r++):console.log(N.t("mcpResetProjectChoices.info.noChoicesSkipping",{path:s}))}catch(a){console.log(N.t("mcpResetProjectChoices.errors.fileError",{path:s,error:a})),n++}}console.log(),console.log(N.t("mcpResetProjectChoices.info.summary")),console.log(N.t("mcpResetProjectChoices.info.deletedFiles",{count:r})),n>0&&console.log(N.t("mcpResetProjectChoices.info.errorFiles",{count:n})),r>0&&(console.log(),console.log(N.t("mcpResetProjectChoices.info.resetComplete")),console.log(N.t("mcpResetProjectChoices.info.extensionPrompt")))}catch(e){console.error(N.t("mcpResetProjectChoices.errors.searchError"),e)}}var _ii={command:"reset-project-choices",describe:N.t("mcpResetProjectChoices.description"),builder:t=>t.usage(N.t("mcpResetProjectChoices.usage")),handler:async()=>{await pca()}};Gt();var Eii={command:"mcp",describe:N.t("mcpCommand.description"),builder:t=>t.command(pii).command(hii).command(mii).command(gii).command(Aii).command(_ii).demandCommand(1,N.t("mcpCommand.demandCommand")).version(!1),handler:()=>{}};Fer();Uer();vl();Gt();import Bg from"fs/promises";import q5 from"path";import Jca from"os";var Zca=async(t,e=1,r=20)=>{try{if(!t)return{success:!1,message:N.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=N.t("workflowAdd.unableToLoadWorkflows");return o.status===401?c=N.t("workflowAdd.authenticationFailed"):o.status===403?c=N.t("workflowAdd.accessDenied"):o.status===404?c=N.t("workflowAdd.serviceNotFound"):o.status>=500&&(c=N.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||N.t("workflowAdd.failedToLoadFromServer")}}catch(n){let o=N.t("workflowAdd.connectionError");return n instanceof Error&&n.message.includes("Failed to fetch")&&(o=N.t("workflowAdd.networkError")),{success:!1,message:o}}},ela=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||N.t("workflowAdd.failedToFetchDetails"));return n.data||null}catch(r){return console.error(N.t("workflowAdd.failedToFetchDetails"),r),null}},tla=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 Bg.writeFile(e,Buffer.from(n))},rla=t=>{let e=new URL(t).pathname;return q5.extname(e).toLowerCase()},nla=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}},ila=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 nla(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(`\u2705 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"}`)},ola=async(t,e,r)=>{try{switch(r){case".zip":await ila(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}`)}},sla=async t=>{try{let e=await Bg.readFile(t,{flag:"r"});if(e.length>=4){let r=e.readUInt32BE(0);return r===333319||r===333312}return!1}catch{return!1}},Kii=async t=>{try{let e=await Bg.readdir(t,{withFileTypes:!0});for(let r of e){let n=q5.join(t,r.name);if(r.isDirectory())await Kii(n),r.name==="__MACOSX"&&await Bg.rm(n,{recursive:!0,force:!0});else{let o=!1;(r.name===".DS_Store"||r.name.startsWith("._")&&await sla(n))&&(o=!0),o&&await Bg.rm(n,{force:!0})}}}catch(e){console.warn(`Warning: Failed to clean up macOS files in ${t}: ${e}`)}},ala=async(t,e,r)=>{try{let n;try{n=JSON.parse(t.extInfo)}catch(u){return{success:!1,message:N.t("workflowAdd.invalidExtInfo",{error:u instanceof Error?u.message:String(u)})}}if(!n.url)return{success:!1,message:N.t("workflowAdd.noDownloadUrl")};let o=rla(n.url),s=await Bg.mkdtemp(q5.join(Jca.tmpdir(),"iflow-workflow-")),a=q5.join(s,`workflow${o}`),c=q5.join(s,"extracted");try{console.log(N.t("workflowAdd.downloading",{url:n.url})),await tla(n.url,a),console.log(N.t("workflowAdd.extracting")),await Bg.mkdir(c,{recursive:!0}),await ola(a,c,o),await Kii(c);let u=await cla(c);console.log(N.t("workflowAdd.copyingFiles"));let d=e||process.cwd(),f=await Bg.readdir(c);for(let p of f){let h=q5.join(c,p),m=q5.join(d,p);(await Bg.stat(h)).isDirectory()?(console.log(`Copying directory: ${h} -> ${m}`),await Xii(h,m)):(console.log(`\u{1F4C4} Copying file: ${h} -> ${m}`),await Bg.copyFile(h,m))}return u&&await lla(d),await Bg.rm(s,{recursive:!0,force:!0}),{success:!0,message:N.t("workflowAdd.installSuccess",{workflowName:r,targetDir:d})}}catch(u){try{await Bg.rm(s,{recursive:!0,force:!0})}catch{}throw u}}catch(n){let o=n instanceof Error?n.message:String(n);return{success:!1,message:N.t("workflowAdd.installFailed",{workflowName:r,error:o})}}},Xii=async(t,e)=>{await Bg.mkdir(e,{recursive:!0});let r=await Bg.readdir(t,{withFileTypes:!0});for(let n of r){let o=q5.join(t,n.name),s=q5.join(e,n.name);n.isDirectory()?await Xii(o,s):await Bg.copyFile(o,s)}},cla=async t=>{let e=q5.join(t,"command_setup.sh");try{return await Bg.access(e,Bg.constants.F_OK),console.log("\u{1F50D} Detected command_setup.sh in workflow"),!0}catch{return!1}},lla=async t=>{let e=q5.join(t,"command_setup.sh");try{console.log("\u{1F527} Executing command_setup.sh..."),await Bg.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("\u2705 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 ula(t){let r=El(process.cwd()).merged.apiKey;r||(console.error(N.t("workflowAdd.apiKeyNotFound")),console.error(N.t("workflowAdd.pleaseAuthenticate")),process.exit(1)),console.log(N.t("workflowAdd.searching",{nameOrId:t}));try{let n=null;if(/^\d+$/.test(t)){let u=parseInt(t,10);n=await ela(r,u)}if(!n){let u=await Zca(r,1,500);u.success||(console.error(N.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(N.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(N.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(N.t("workflowAdd.workflowDescription",{description:s})),console.log(N.t("workflowAdd.installing"));let a=process.cwd(),c=await ala(n,a,o);c.success?console.log(c.message):(console.error(c.message),process.exit(1))}catch(n){console.error(N.t("workflowAdd.errorAdding",{error:n})),process.exit(1)}}var Jii={command:"add <name-or-id>",describe:N.t("workflowAdd.description"),builder:t=>t.usage(N.t("workflowAdd.usage")).positional("name-or-id",{describe:N.t("workflowAdd.workflowIdOrNumericIdOption"),type:"string",demandOption:!0}),handler:async t=>{await ula(t["name-or-id"])}};Gt();var Zii={command:"workflow",describe:N.t("workflowCommand.description"),builder:t=>t.command(Jii).demandCommand(1,N.t("workflowCommand.demandCommand")).version(!1),handler:()=>{}};var Ger={debug:(...t)=>console.debug("[DEBUG]",...t),warn:(...t)=>console.warn("[WARN]",...t),error:(...t)=>console.error("[ERROR]",...t)};function fla(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 trt(){let t=fla(gm.argv),e=Mti(RZt(t)).locale("en").scriptName("iflow").usage(`Usage: iflow [options] [command]
4542
4542
 
4543
4543
  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:gm.env.modelName||gm.env.MODELNAME||gm.env.MODEL_NAME||gm.env.model_name||gm.env.model||gm.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(Eii).command(Mer).command(Ler).command(Zii).strict().version(await eM()).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"&&gm.exit(0),r._.length>0&&r._[0]==="workflow"&&gm.exit(0),r}async function $er(t,e,r,n,o=[],s="tree",a){let c=Qer.realpathSync(jer.resolve(t)),u=Qer.realpathSync(jer.resolve(dla())),f=c===u?"":t;return e&&Ger.debug(`CLI: Delegating hierarchical memory load to server for CWD: ${t} (memoryImportFormat: ${s})`),S$(f,e,r,o,s,a,n.memoryDiscoveryMaxDirs)}async function SH(t,e,r,n,o=gm.cwd()){let s=n.debug||[gm.env.DEBUG,gm.env.DEBUG_MODE].some(S=>S==="true"||S==="1")||!1,a=t.memoryImportFormat||"tree",c=gri(e,n.extensions||[]),u=e.filter((S,w)=>c[w].isActive);t.contextFileName?lne(t.contextFileName):lne(une());let d=u.flatMap(S=>S.contextFiles),f=new g$(o),p={...uie,...t.fileFiltering};JEt(t.errorLog);let{memoryContent:h,fileCount:m}=await $er(o,s,f,t,d,a,p),g=pla(t,u),A=hla(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 fii(t,n),v=new np,b=!1;try{await v.initialize(),b=!0}catch(S){Ger.error("History manager initialization failed. History features will be disabled.",S)}return new Gye({cna:t.cna,language:t.language,sessionId:r,embeddingModel:iJ,sandbox:E,targetDir:o||gm.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?ei.DEFAULT:n.autoEdit?ei.AUTO_EDIT:n.plan?ei.PLAN:n.yolo?ei.YOLO:ei.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??gm.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||gm.env.HTTPS_PROXY||gm.env.https_proxy||gm.env.HTTP_PROXY||gm.env.http_proxy,cwd:o,fileDiscoveryService:f,bugCommand:t.bugCommand,model:n.model||t.modelName||jd,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:!!gm.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||n.experimentalAcp,disableTelemetry:t.disableTelemetry??!1,enableBuildInTask:t.enableBuildInTask,outputStyle:t.outputStyle,shouldUseNodePtyShell:t.enableInteractiveShell??!1,hasIdeOnboardingBeenShown:t.hasIdeOnboardingBeenShown})}function pla(t,e){let r={...t.mcpServers||{}};for(let n of e)Object.entries(n.config.mcpServers||{}).forEach(([o,s])=>{if(r[o]){Ger.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 hla(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 mla}from"fs";import{join as gla}from"path";var Ala=[];function j6e(t){Ala.push(t)}async function eoi(){let t=o1(process.cwd()),e=gla(t,"checkpoints");try{await mla.rm(e,{recursive:!0,force:!0})}catch{}}import{EventEmitter as yla}from"events";var Hs=new yla;Hs.setMaxListeners(20);Gt();Gt();import*as pae from"fs";import*as rrt from"path";function nrt(t,e){let r=process.argv[1];if(!r)return{packageManager:"unknown",isGlobal:!1};try{let n=pae.realpathSync(r).replace(/\\/g,"/"),o=t?.replace(/\\/g,"/");if(Ou(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 pae.existsSync(rrt.join(t,"yarn.lock"))?u="yarn":pae.existsSync(rrt.join(t,"pnpm-lock.yaml"))?u="pnpm":pae.existsSync(rrt.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?N.t("autoUpdate.fallback",{updateCommand:c}):N.t("autoUpdate.installWithNpm")}}catch(n){return console.log(n),{packageManager:"unknown",isGlobal:!1}}}import{EventEmitter as _la}from"events";var Pg=new _la;Fs();import{spawn as Ela}from"child_process";var irt=Ela;function toi(t,e,r,n=irt){if(!t)return;let o=nrt(r,e.merged.disableAutoUpdate??!1),s=t.message;if(o.updateMessage&&(s+=`
4544
4544
  ${o.updateMessage}`),Pg.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?Pg.emit("update-success",{message:"Update successful! The new version will be used on your next run."}):Pg.emit("update-failed",{message:`Automatic update failed. Please try updating manually. (command: ${u}, stderr: ${f.trim()})`})}),d.on("error",p=>{Pg.emit("update-failed",{message:`Automatic update failed. Please try updating manually. (error: ${p.message})`})}),d}function roi(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:N.t("autoUpdate.failed")},Date.now())},s=()=>{r=!0,e(null),t({type:"info",text:N.t("autoUpdate.ok")},Date.now())},a=c=>{t({type:"info",text:c.message},Date.now())};return Pg.on("update-received",n),Pg.on("update-failed",o),Pg.on("update-success",s),Pg.on("update-info",a),()=>{Pg.off("update-received",n),Pg.off("update-failed",o),Pg.off("update-success",s),Pg.off("update-info",a)}}Dn();var Y0=Te(nr(),1);await Zr();Dn();var Aae=Te(nr(),1);await Zr();var Uoi=Te(nr(),1);await Zr();var H5=Te(nr(),1);import lrt from"node:readline";import{PassThrough as Bla}from"node:stream";var Her="[99;5u";var Loi=Te(Mt(),1);var Noi="\x1B[I",Ooi="\x1B[O",Zb="\x1B",koi=`${Zb}[200~`,Boi=`${Zb}[201~`,Poi=(0,H5.createContext)(void 0);function Moi(){let t=(0,H5.useContext)(Poi);if(!t)throw new Error("useKeypressContext must be used within a KeypressProvider");return t}function Foi({children:t,kittyProtocolEnabled:e,config:r,debugKeystrokeLogging:n}){let{stdin:o,setRawMode:s}=vS(),a=(0,H5.useRef)(new Set).current,c=(0,H5.useCallback)(d=>{a.add(d)},[a]),u=(0,H5.useCallback)(d=>{a.delete(d)},[a]);return(0,H5.useEffect)(()=>{let d=o.isRaw;d===!1&&s(!0);let f=new Bla,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=$=>{let j=new RegExp(`^${Zb}\\[Z`),H=$.match(j);if(H)return{key:{name:"tab",ctrl:!1,meta:!1,shift:!0,paste:!1,sequence:$.slice(0,H[0].length),kittyProtocol:!0},length:H[0].length};let W=new RegExp(`^${Zb}\\[1;(\\d+)Z`);if(H=$.match(W),H){let Y=parseInt(H[1],10);Y>=128&&(Y-=128);let J=Y-1,ue=(J&2)===2;return{key:{name:"tab",ctrl:(J&4)===4,meta:ue,shift:!0,paste:!1,sequence:$.slice(0,H[0].length),kittyProtocol:!0},length:H[0].length}}let Q=new RegExp(`^${Zb}\\[1;(\\d+)([ABCDHFPQSR])`);if(H=$.match(Q),H){let Y=parseInt(H[1],10);Y>=128&&(Y-=128);let J=Y-1,ue=(J&1)===1,Se=(J&2)===2,le=(J&4)===4,Ce=H[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:le,meta:Se,shift:ue,paste:!1,sequence:$.slice(0,H[0].length),kittyProtocol:!0},length:H[0].length}:null}let X=new RegExp(`^${Zb}\\[(\\d+)(;(\\d+))?([u~])`);if(H=$.match(X),H){let Y=parseInt(H[1],10),J=H[3]?parseInt(H[3],10):1;J>=128&&(J-=128);let ue=J-1,Se=(ue&1)===1,le=(ue&2)===2,Ce=(ue&4)===4;if(H[4]==="~"){let _e=null;switch(Y){case 1:_e="home";break;case 2:_e="insert";break;case 3:_e="delete";break;case 4:_e="end";break;case 5:_e="pageup";break;case 6:_e="pagedown";break;default:break}if(_e)return{key:{name:_e,ctrl:Ce,meta:le,shift:Se,paste:!1,sequence:$.slice(0,H[0].length),kittyProtocol:!0},length:H[0].length}}let ae={27:"escape",9:"tab",127:"backspace",13:"return",57414:"return"}[Y];if(ae)return{key:{name:ae,ctrl:Ce,meta:le,shift:Se,paste:!1,sequence:$.slice(0,H[0].length),kittyProtocol:!0},length:H[0].length};if(Ce&&Y>=97&&Y<=122)return{key:{name:String.fromCharCode(Y),ctrl:!0,meta:le,shift:Se,paste:!1,sequence:$.slice(0,H[0].length),kittyProtocol:!0},length:H[0].length}}let z=new RegExp(`^${Zb}\\[([ABCDHF])`);if(H=$.match(z),H){let Y=H[1];return{key:{name:{A:"up",B:"down",C:"right",D:"left",H:"home",F:"end"}[Y],ctrl:!1,meta:!1,shift:!1,paste:!1,sequence:$.slice(0,H[0].length),kittyProtocol:!0},length:H[0].length}}return null},D=$=>{for(let j of a)j($)},P=($,j)=>{if(j.name==="paste-start"){m=!0,w=performance.now();return}if(j.name==="paste-end"){m=!1;let W=g.toString(),Q=performance.now(),X=w?Q-w:0;D({name:"",ctrl:!1,meta:!1,shift:!1,paste:!0,sequence:W,...w&&{pasteDuration:X,pasteTextLength:W.length}}),g=Buffer.alloc(0),w=null;return}if(m){g=Buffer.concat([g,Buffer.from(j.sequence)]);return}b&&j.name!=="return"&&(S&&(clearTimeout(S),S=null),D({...b,shift:!0}),b=null);let H=Date.now();if(j.name==="return"&&v>0&&!E)if(H-v<30)j.shift=!0;else{b={...j,paste:m},S=setTimeout(()=>{b&&(D(b),b=null),S=null},30),v=H;return}if(v=H,["up","down","left","right"].includes(j.name)){D(j);return}if(j.ctrl&&j.name==="c"||j.sequence===`${Zb}${Her}`){A&&n&&console.log("[DEBUG] Kitty buffer cleared on Ctrl+C:",A),A="",j.sequence===`${Zb}${Her}`?D({name:"c",ctrl:!0,meta:!1,shift:!1,paste:!1,sequence:j.sequence,kittyProtocol:!0}):D(j);return}if(e&&(A||j.sequence.startsWith(`${Zb}[`)&&!j.sequence.startsWith(koi)&&!j.sequence.startsWith(Boi)&&!j.sequence.startsWith(Noi)&&!j.sequence.startsWith(Ooi))){A+=j.sequence,n&&console.log("[DEBUG] Kitty buffer accumulating:",A);let W=!1;for(;A;){let Q=R(A);if(!Q){let X=A.indexOf(`${Zb}[`,1);if(X>0){n&&console.log("[DEBUG] Skipping incomplete/invalid CSI prefix:",A.slice(0,X)),A=A.slice(X);continue}break}if(n){let X=A.slice(0,Q.length);A.length>Q.length?console.log("[DEBUG] Kitty sequence parsed successfully (prefix):",X):console.log("[DEBUG] Kitty sequence parsed successfully:",X)}A=A.slice(Q.length),D(Q.key),W=!0}if(W)return;if(r?.getDebugMode()||n){let Q=Array.from(A).map(X=>X.charCodeAt(0));console.warn("Kitty sequence buffer has char codes:",Q)}if(A.length>32)n&&console.log("[DEBUG] Kitty buffer overflow, clearing:",A),A="";else return}j.name==="return"&&j.sequence===`${Zb}\r`&&(j.meta=!0),D({...j,paste:m})},I=null,O=40,k=null,L=($,j)=>{if(!(j.sequence===Noi||j.sequence===Ooi)){if(I)clearTimeout(I),I=null,!m&&k&&(w=performance.now(),g=Buffer.concat([g,Buffer.from(k.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,k=null,I=null)},O);else{if(m||j.ctrl||j.meta||j.name==="paste-start"||j.name==="paste-end"||j.name==="backspace"||j.name==="delete"||j.name==="left"||j.name==="right"||j.name==="up"||j.name==="down"){P($,j);return}if(j.name==="return"&&E){y&&(clearTimeout(y),y=null),E=!1,D({...j,shift:!0,sequence:"\r"});return}if(j.sequence==="\\"&&!j.name){E=!0,y=setTimeout(()=>{E=!1,y=null,D(j)},5);return}E&&j.name!=="return"&&(y&&(clearTimeout(y),y=null),E=!1,D({name:"",sequence:"\\",ctrl:!1,meta:!1,shift:!1,paste:!1})),k=j,I=setTimeout(()=>{k&&(P($,k),k=null),I=null},O);return}P($,j)}},F=$=>{let j=Buffer.from(koi),H=Buffer.from(Boi),W=0;for(;W<$.length;){let Q=$.indexOf(j,W),X=$.indexOf(H,W),z=Q!==-1&&(X===-1||Q<X),Y=X!==-1&&(Q===-1||X<Q),J=-1,ue=0;if(z?J=Q:Y&&(J=X),ue=H.length,J===-1){f.write($.slice(W));return}let Se=$.slice(W,J);Se.length>0&&f.write(Se);let le=Ce=>({name:Ce,ctrl:!1,meta:!1,shift:!1,paste:!1,sequence:""});z?P(void 0,le("paste-start")):Y&&P(void 0,le("paste-end")),W=J+ue}},M;return p?(M=lrt.createInterface({input:f,escapeCodeTimeout:0}),lrt.emitKeypressEvents(f,M),f.on("keypress",L),o.on("data",F)):(M=lrt.createInterface({input:o,escapeCodeTimeout:0}),lrt.emitKeypressEvents(o,M),o.on("keypress",L)),()=>{p?(f.removeListener("keypress",L),o.removeListener("data",F)):o.removeListener("keypress",L),M.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,Loi.jsx)(Poi.Provider,{value:{subscribe:c,unsubscribe:u},children:t})}function Mn(t,{isActive:e}){let{subscribe:r,unsubscribe:n}=Moi();(0,Uoi.useEffect)(()=>{if(e)return r(t),()=>{n(t)}},[e,t,r,n])}Dn();Ai();var e4=Te(Mt(),1);function Pla(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 UE({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,Aae.useReducer)(Pla,{value:s,cursorPosition:s.length}),{value:h,cursorPosition:m}=f,[g,A]=(0,Aae.useState)(!0);(0,Aae.useEffect)(()=>{if(!o)return;let v=setInterval(()=>{A(b=>!b)},500);return()=>clearInterval(v)},[o]),Mn(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,e4.jsxs)(fe,{flexDirection:"column",children:[(0,e4.jsx)(fe,{children:(0,e4.jsxs)(ne,{color:Ae.Gray,children:[d," "]})}),(0,e4.jsx)(fe,{marginTop:1,children:(0,e4.jsx)(fe,{borderStyle:"round",borderColor:o?Ae.AccentBlue:Ae.Gray,paddingX:1,width:"100%",children:h?(0,e4.jsx)(ne,{children:E}):(0,e4.jsxs)(ne,{children:[(0,e4.jsx)(ne,{color:Ae.Gray,children:u}),y]})})}),(0,e4.jsx)(fe,{marginTop:1,children:(0,e4.jsx)(ne,{color:Ae.Gray,dimColor:!0,children:c("textInput.instructions")})})]})}Ai();var dr=Te(Mt(),1);var Qoi=(0,Y0.memo)(({config:t,onExit:e,onStatusUpdate:r})=>{let{t:n}=fr(),[o,s]=(0,Y0.useState)("location"),[a,c]=(0,Y0.useState)(0),[u,d]=(0,Y0.useState)({}),[f,p]=(0,Y0.useState)(null),[h,m]=(0,Y0.useState)(null),[g,A]=(0,Y0.useState)(!1),[y,E]=(0,Y0.useState)([]),[v,b]=(0,Y0.useState)([]),[S,w]=(0,Y0.useState)(""),[R,D]=(0,Y0.useState)(null),[P,I]=(0,Y0.useState)("");(0,Y0.useEffect)(()=>{(async()=>{try{let ie=await t.getToolRegistry();if(ie){let oe=["task","exit_plan_mode","save_memory"],q=ie.getAllTools().filter(K=>{let Ee="serverName"in K&&K.serverName!==void 0,ge=oe.filter(ve=>ve===K.name).length>0;return!Ee&&!ge}).map(K=>K.name);E(q),d(K=>({...K,selectedTools:q}))}let ae=t.getMcpServers()||{},_e=Object.keys(ae);b(_e),d(oe=>({...oe,selectedMcps:_e}))}catch(ie){console.error("Failed to initialize data:",ie)}})()},[t]);let k={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],L=k?.options?.filter(Z=>Z.available)||[];(0,Y0.useEffect)(()=>{c(0),p(null),A(!1),D(null),I("")},[o]);let F=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 _e=u.method==="iFlow"?ae:ie,oe=_e.indexOf(Z);return oe<_e.length-1?_e[oe+1]:null},M=Z=>{let ie=["location","method","agentType","systemPrompt","description","tools","mcps","color","preview"],ae=["location","method","agentGoal","generating","generated-preview","tools","mcps","color","preview"],_e=u.method==="iFlow"?ae:ie,oe=_e.indexOf(Z);return oe>0?_e[oe-1]:null},$=()=>{switch(o){case"agentGoal":return u.agentGoal||"";case"agentType":return u.agentType||"";case"systemPrompt":return u.systemPrompt||"";case"description":return u.description||"";default:return""}},j=Z=>{if(o==="agentGoal"){if(d(ae=>({...ae,agentGoal:Z})),u.method==="iFlow"){X(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=F(o);ie&&(s(ie),c(0))},H=()=>{A(!1),D(null),I("")},W=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("")},Q=()=>{D(null),I("")},X=async Z=>{try{s("generating"),p(null),r?.(n("agentInstallDialog.generatingFromGoal"));let{generateAgentConfig:ie}=await Promise.resolve().then(()=>(Gt(),Uy)),ae=await ie(t,{agentGoal:Z,onProgress:_e=>{w(_e),r?.(_e)}});d(_e=>({..._e,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}))}},z=async()=>{try{s("installing"),r?.(n("agentInstallDialog.creatingAgent",{agentType:u.agentType}));let{createAgent:Z}=await Promise.resolve().then(()=>(Gt(),Uy)),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}))}},Y=()=>{let Z=k;if(!Z)return;if(Z.type==="select"){let ae=L[a];if(ae)if(o==="location")d(_e=>({..._e,location:ae.id}));else if(o==="method"){let _e=ae.id;if(d(me=>({...me,method:_e})),_e==="online"){m(n("agentInstallDialog.redirectingToOnline")),r?.(n("agentInstallDialog.useAgentsOnline")),setTimeout(()=>{e()},2e3);return}let oe=null;_e==="template"?oe="agentType":_e==="iFlow"&&(oe="agentGoal"),oe&&(s(oe),c(0),A(!1),p(null));return}else o==="color"&&d(_e=>({..._e,color:ae.id}))}else if(Z.type==="input"){if(!g){A(!0);return}}else if(Z.type==="multiselect")if(a===0){let ae=F(o);ae&&(s(ae),c(0),A(!1),p(null));return}else{let ae=L[a-1];if(o==="tools"){let _e=u.selectedTools||[],oe=_e.includes(ae.id);d(oe?me=>({...me,selectedTools:_e.filter(he=>he!==ae.id)}):me=>({...me,selectedTools:[..._e,ae.id]}))}else if(o==="mcps"){let _e=u.selectedMcps||[],oe=_e.includes(ae.id);d(oe?me=>({...me,selectedMcps:_e.filter(he=>he!==ae.id)}):me=>({...me,selectedMcps:[..._e,ae.id]}))}return}else if(Z.type==="edit"){if(R)return;if(a===0){let ae=F(o);ae&&(s(ae),c(0),A(!1),p(null))}else{let ae=L[a-1];D(ae.id);let _e="";ae.id==="agentType"?_e=u.agentType||"":ae.id==="description"?_e=u.description||"":ae.id==="systemPrompt"&&(_e=u.systemPrompt||""),I(_e)}return}else if(Z.type==="preview"){z();return}let ie=F(o);ie&&(s(ie),c(0),A(!1),p(null))},J=()=>{if(g){A(!1);return}if(R){D(null),I("");return}let Z=M(o);Z?(s(Z),c(0),p(null)):e()};Mn(Z=>{if(g||R)return;if(Z.name==="escape"){J();return}if(Z.sequence==="q"){e();return}let ie=k;if(ie){if(ie.type==="select"||ie.type==="multiselect"||ie.type==="edit"){let ae=ie.type==="multiselect"||ie.type==="edit"?L.length:L.length-1;Z.name==="up"||Z.sequence==="k"?c(_e=>Math.max(0,_e-1)):Z.name==="down"||Z.sequence==="j"?c(_e=>Math.min(ae,_e+1)):Z.name==="return"&&Y()}else if(ie.type==="input")Z.name==="return"&&Y();else if(ie.type==="preview"){if(Z.name==="up"||Z.name==="down"||Z.sequence==="k"||Z.sequence==="j")return;Z.name==="return"&&Y()}}},{isActive:!0});let ue=()=>{if(u.method==="online"){let oe=["location","method"],me=oe.indexOf(o);return(0,dr.jsxs)(fe,{marginBottom:1,children:[(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.stepOf",{current:me+1,total:oe.length})}),(0,dr.jsx)(fe,{marginLeft:2,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:oe.map((he,q)=>q<me?"\u2713 ":q===me?"\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,_e=ae.indexOf(o);return(0,dr.jsxs)(fe,{marginBottom:1,children:[(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.stepOf",{current:_e+1,total:ae.length})}),(0,dr.jsx)(fe,{marginLeft:2,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:ae.map((oe,me)=>me<_e?"\u2713 ":me===_e?"\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:Ae.AccentCyan,children:n("agentInstallDialog.editField",{field:Z[R]})}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.modifyField",{field:R})})}),(0,dr.jsx)(fe,{marginTop:2,children:(0,dr.jsx)(UE,{onSubmit:W,onCancel:Q,placeholder:n("agentInstallDialog.enterField",{field:R}),label:Z[R],defaultValue:P,isFocused:!0})})]})}return(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:Ae.AccentCyan,children:n("agentInstallDialog.generatedPreviewTitle")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:Ae.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?Ae.AccentCyan:void 0,children:[a===0?"> ":" ",n("agentInstallDialog.continueToToolsSelection")]})}),(0,dr.jsx)(fe,{marginLeft:4,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.proceedToNextStep")})})]},"continue"),L.map((Z,ie)=>{let _e=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:_e?Ae.AccentCyan:void 0,children:[_e?"> ":" ",Z.title]})}),(0,dr.jsx)(fe,{marginLeft:4,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:Z.description})})]},Z.id)})]}),(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.navigation")}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.navigateOptions")}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.enterToEditField")}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.escToBack")}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.qToExit")})]})]})},le=()=>(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:Ae.AccentCyan,children:n("agentInstallDialog.previewTitle")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:Ae.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:Ae.AccentBlue,children:u.description})}),(0,dr.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:Ae.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:Ae.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:Ae.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:Ae.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:Ae.AccentYellow,children:n("agentInstallDialog.actions")}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.enterToCreate")}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.escToBackEdit")}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.qToExit")})]})]}),Ce=()=>k?o==="preview"?le():o==="generated-preview"?Se():o==="generating"?(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:Ae.AccentCyan,children:n("agentInstallDialog.generatingTitle")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.generatingDescription")})}),(0,dr.jsx)(fe,{marginTop:2,children:(0,dr.jsx)(ne,{color:Ae.AccentYellow,children:S||n("agentInstallDialog.startingGeneration")})}),(0,dr.jsx)(fe,{marginTop:2,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.pleaseWait")})})]}):g&&k.type==="input"?(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:Ae.AccentCyan,children:k.title}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:k.description})}),(0,dr.jsx)(fe,{marginTop:2,children:(0,dr.jsx)(UE,{onSubmit:j,onCancel:H,placeholder:k.placeholder,label:k.title,defaultValue:$(),isFocused:!0})})]}):(0,dr.jsxs)(fe,{flexDirection:"column",children:[(0,dr.jsx)(ne,{bold:!0,color:Ae.AccentCyan,children:k.title}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:k.description})}),k.type==="input"&&!g&&(0,dr.jsxs)(fe,{marginTop:2,children:[(0,dr.jsx)(ne,{color:Ae.AccentYellow,children:$()?n("agentInstallDialog.currentValue",{value:$()}):n("agentInstallDialog.currentValueNotSet")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.pressEnterToEdit")})})]}),(k.type==="select"||k.type==="multiselect")&&(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[k.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?Ae.AccentCyan:void 0,children:[a===0?"> ":" ",n("agentInstallDialog.continue")]})}),(0,dr.jsx)(fe,{marginLeft:4,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.proceedToNextStep")})})]},"continue"),L.map((Z,ie)=>{let _e=(k.type==="multiselect"?ie+1:ie)===a,oe=k.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:_e?Ae.AccentCyan:void 0,children:[_e?"> ":" ",k.type==="multiselect"&&(0,dr.jsx)(ne,{children:oe?"[\u2713] ":"[ ] "}),k.type==="select"&&Z.id==="red"&&(0,dr.jsx)(ne,{color:Ae.AccentRed,children:"\u2588 "}),k.type==="select"&&Z.id==="blue"&&(0,dr.jsx)(ne,{color:Ae.AccentBlue,children:"\u2588 "}),k.type==="select"&&Z.id==="green"&&(0,dr.jsx)(ne,{color:Ae.AccentGreen,children:"\u2588 "}),k.type==="select"&&Z.id==="yellow"&&(0,dr.jsx)(ne,{color:Ae.AccentYellow,children:"\u2588 "}),k.type==="select"&&Z.id==="purple"&&(0,dr.jsx)(ne,{color:Ae.AccentPurple,children:"\u2588 "}),k.type==="select"&&Z.id==="orange"&&(0,dr.jsx)(ne,{color:Ae.AccentYellow,children:"\u2588 "}),k.type==="select"&&Z.id==="pink"&&(0,dr.jsx)(ne,{color:Ae.AccentPurple,children:"\u2588 "}),k.type==="select"&&Z.id==="cyan"&&(0,dr.jsx)(ne,{color:Ae.AccentCyan,children:"\u2588 "}),Z.title]})}),Z.description&&(0,dr.jsx)(fe,{marginLeft:4,children:(0,dr.jsx)(ne,{color:Ae.Gray,children:Z.description})})]},Z.id)})]}),(0,dr.jsxs)(fe,{marginTop:2,flexDirection:"column",children:[(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.navigation")}),k.type==="input"&&!g&&(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.enterToEdit")}),(k.type==="select"||k.type==="multiselect"||k.type==="edit")&&(0,dr.jsxs)(dr.Fragment,{children:[(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.navigateOptions")}),(0,dr.jsxs)(ne,{color:Ae.Gray,children:[" ","\u2022"," ",k.type==="edit"?n("agentInstallDialog.enterToEditField"):n("agentInstallDialog.enterToSelect")]})]}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.escToBack")}),(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.qToExit")})]})]}):(0,dr.jsx)(fe,{flexDirection:"column",children:(0,dr.jsx)(ne,{color:Ae.Gray,children:n("agentInstallDialog.generatingTitle")})});return h?(0,dr.jsxs)(fe,{borderStyle:"round",borderColor:Ae.AccentGreen,flexDirection:"column",padding:1,width:"100%",children:[(0,dr.jsx)(ne,{bold:!0,color:Ae.AccentGreen,children:n("agentInstallDialog.agentInstallation")}),(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsxs)(ne,{color:Ae.AccentGreen,children:["\u2705 ",h]})})]}):(0,dr.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,dr.jsx)(ne,{bold:!0,children:n("agentInstallDialog.title")}),ue(),Ce(),f&&(0,dr.jsx)(fe,{marginTop:1,children:(0,dr.jsxs)(ne,{color:Ae.AccentRed,children:["\u274C ",f]})})]})},(t,e)=>t.config===e.config);var Q8=Te(nr(),1);await Zr();Dn();Ai();var Rn=Te(Mt(),1);function joi({settings:t,config:e,onExit:r,onStatusUpdate:n}){let{t:o}=fr(),[s,a]=(0,Q8.useState)("loading"),[c,u]=(0,Q8.useState)([]),[d,f]=(0,Q8.useState)(0),[p,h]=(0,Q8.useState)(0),[m,g]=(0,Q8.useState)(null),[A,y]=(0,Q8.useState)(null),[E,v]=(0,Q8.useState)(null),b=10,S=Math.ceil(c.length/b);(0,Q8.useEffect)(()=>{let I=async()=>{try{if(!t.merged.apiKey)return{success:!1,message:o("agentsOnlineDialog.authRequired")};let L=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(!L.ok){let M=o("agentsOnlineDialog.loadFailed");return L.status===401?M=o("agentsOnlineDialog.authFailed"):L.status===403?M=o("agentsOnlineDialog.accessDenied"):L.status===404?M=o("agentsOnlineDialog.serviceNotFound"):L.status>=500&&(M=o("agentsOnlineDialog.serverError")),{success:!1,message:M}}let F=await L.json();return F.success?{success:!0,data:F.data?.data||[]}:{success:!1,message:F.message||o("agentsOnlineDialog.serverLoadFailed")}}catch(k){let L=o("agentsOnlineDialog.connectionError");return k instanceof Error&&k.message.includes("Failed to fetch")&&(L=o("agentsOnlineDialog.networkError")),{success:!1,message:L}}};(async()=>{let k=await I();k.success&&k.data?(u(k.data),a("list"),k.data.length===0&&y(o("agentsOnlineDialog.noAgentsFound"))):(y(k.message||o("agentsOnlineDialog.loadAgentsFailed")),a("list"))})()},[t.merged.apiKey,o]);let w=async(I,O)=>{try{let{AgentRegistry:k}=await Promise.resolve().then(()=>(Gt(),Uy)),L=new k,F=[],M=!0,$=!0,j,H=null;if(I.extInfo&&typeof I.extInfo=="string")try{H=JSON.parse(I.extInfo)}catch{}if(H){if(M=H["is-inherit-tools"],$=H["is-inherit-mcps"]!==void 0?H["is-inherit-mcps"]:!0,H["allowed-tools"]){let X=H["allowed-tools"].split(",").map(z=>z.trim()).filter(z=>z);X.length>0?F=X:F=H["is-inherit-tools"]?["*"]:[]}else F=H["is-inherit-tools"]?["*"]:[];if(H.mcps){let X=H.mcps.split(",").map(z=>z.trim()).filter(z=>z);X.length>0?j=X:j=H["is-inherit-mcps"]?void 0:[]}else j=H["is-inherit-mcps"]?void 0:[]}else{try{let X=JSON.parse(I.tools||"[]");F=Array.isArray(X)?X:["*"]}catch{F=["*"]}if(I.mcps)try{let X=JSON.parse(I.mcps);Array.isArray(X)&&X.length>0&&(j=X)}catch{let X=I.mcps.split(",").map(z=>z.trim()).filter(z=>z.length>0);X.length>0&&(j=X)}}let W={agentType:I.name.toLowerCase().replace(/[^a-z0-9]/g,"-"),name:I.name,description:I.description,whenToUse:I.description,allowedTools:F,allowedMcps:j,systemPrompt:I.detailContext||I.description,location:O==="user"?"global":"project",model:I.modelName,isInheritTools:M,isInheritMcps:$};return await L.createAgent(W)?{success:!0,message:o("agentsCommand.install.successfullyInstalled",{name:I.name,scope:O})}:{success:!1,message:o("agentsOnlineDialog.createAgentFailed",{name:I.name})}}catch(k){return{success:!1,message:o("agentsOnlineDialog.installFailedWithError",{name:I.name,error:k})}}},R=async(I,O)=>{try{n?.(o("agentsOnlineDialog.installing",{name:I.name}));let k=await w(I,O);k.success?(v(k.message),y(null),n?.(k.message)):(y(k.message),v(null),n?.(`\u274C ${k.message}`))}catch(k){let L=k instanceof Error?k.message:o("agentsOnlineDialog.installationFailed");y(L),v(null),n?.(`\u274C ${L}`)}};Mn(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 O=Math.max(p-1,0);h(O);let k=Math.floor(O/b);f(k)}else if(I.name==="down"||I.sequence==="j"){let O=Math.min(p+1,c.length-1);h(O);let k=Math.floor(O/b);f(k)}else if(I.name==="left"||I.sequence==="h"){let O=Math.max(d-1,0);f(O),h(O*b)}else if(I.name==="right"||I.sequence==="l"){let O=Math.min(d+1,S-1);f(O),h(Math.min(O*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,Rn.jsxs)(fe,{flexDirection:"column",children:[(0,Rn.jsx)(ne,{bold:!0,children:o("agentsOnlineDialog.availableAgents")}),(0,Rn.jsx)(fe,{marginTop:1,children:(0,Rn.jsx)(ne,{color:Ae.AccentRed,children:A||o("agentsOnlineDialog.noAgentsAvailable")})})]});let I=d*b,O=Math.min(I+b,c.length),k=c.slice(I,O);return(0,Rn.jsxs)(fe,{flexDirection:"column",children:[(0,Rn.jsx)(ne,{bold:!0,children:o("agentsOnlineDialog.availableAgentsWithCount",{count:c.length})}),(0,Rn.jsx)(fe,{marginTop:1,flexDirection:"column",children:k.map((L,F)=>{let $=I+F===p;return(0,Rn.jsxs)(fe,{marginBottom:1,flexDirection:"row",children:[(0,Rn.jsxs)(fe,{width:30,flexShrink:0,flexDirection:"column",children:[(0,Rn.jsxs)(ne,{color:$?Ae.AccentCyan:void 0,children:[$?"> ":" ",F+1,". ",L.name]}),(0,Rn.jsx)(fe,{marginLeft:4,flexDirection:"column",children:(0,Rn.jsx)(ne,{color:Ae.Gray,children:o("agentsOnlineDialog.category",{category:L.category})})})]}),(0,Rn.jsx)(fe,{marginLeft:3,flexGrow:1,children:(0,Rn.jsx)(ne,{color:Ae.Gray,children:L.description})})]},L.id)})}),(0,Rn.jsx)(fe,{marginTop:1,children:(0,Rn.jsx)(ne,{color:Ae.AccentBlue,children:o("agentsOnlineDialog.pageOf",{current:d+1,total:S})})}),(0,Rn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Rn.jsx)(ne,{color:Ae.Gray,children:o("agentsOnlineDialog.navigation")}),(0,Rn.jsxs)(ne,{color:Ae.Gray,children:[" ",o("agentsOnlineDialog.navigateUpDown")]}),(0,Rn.jsxs)(ne,{color:Ae.Gray,children:[" ",o("agentsOnlineDialog.prevNextPage")]}),(0,Rn.jsxs)(ne,{color:Ae.Gray,children:[" ",o("agentsOnlineDialog.viewDetails")]}),(0,Rn.jsxs)(ne,{color:Ae.Gray,children:[" ",o("agentsOnlineDialog.exit")]})]})]})},P=()=>m?(0,Rn.jsxs)(fe,{flexDirection:"column",children:[(0,Rn.jsx)(ne,{bold:!0,children:m.name}),(0,Rn.jsx)(fe,{marginTop:1,children:(0,Rn.jsx)(ne,{color:Ae.AccentBlue,children:m.description})}),(0,Rn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Rn.jsx)(ne,{color:Ae.AccentCyan,children:o("agentsOnlineDialog.details")}),(0,Rn.jsxs)(ne,{children:[" ","\u2022"," ",o("agentsOnlineDialog.model",{model:m.modelName})]}),(0,Rn.jsxs)(ne,{children:[" ","\u2022"," ",o("agentsOnlineDialog.categoryLabel",{category:m.category})]}),(0,Rn.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,Rn.jsxs)(Rn.Fragment,{children:[(0,Rn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Rn.jsx)(ne,{color:Ae.AccentCyan,children:o("agentsOnlineDialog.tools")}),(0,Rn.jsx)(fe,{marginLeft:2,children:(0,Rn.jsx)(ne,{children:(()=>{let O=I["allowed-tools"]?I["allowed-tools"].split(",").map(L=>L.trim()).filter(L=>L):[],k=I["is-inherit-tools"]?o("agentsOnlineDialog.inherit"):o("agentsOnlineDialog.noInherit");return O.length>0?O.join(", ")+k:I["is-inherit-tools"]?o("agentsOnlineDialog.allToolsAvailableInherit"):o("agentsOnlineDialog.noToolsAvailableNoInherit")})()})})]}),(0,Rn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Rn.jsx)(ne,{color:Ae.AccentCyan,children:o("agentsOnlineDialog.mcpServers")}),(0,Rn.jsx)(fe,{marginLeft:2,children:(0,Rn.jsx)(ne,{children:(()=>{let O=I.mcps?I.mcps.split(",").map(L=>L.trim()).filter(L=>L):[],k=I["is-inherit-mcps"]?o("agentsOnlineDialog.inherit"):o("agentsOnlineDialog.noInherit");return O.length>0?O.join(", ")+k:I["is-inherit-mcps"]?o("agentsOnlineDialog.allMcpServersAvailableInherit"):o("agentsOnlineDialog.noMcpServersAvailableNoInherit")})()})})]})]}):(0,Rn.jsxs)(Rn.Fragment,{children:[(0,Rn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Rn.jsx)(ne,{color:Ae.AccentCyan,children:o("agentsOnlineDialog.tools")}),(0,Rn.jsx)(fe,{marginLeft:2,children:(0,Rn.jsx)(ne,{children:(()=>{if(!m.tools)return o("agentsOnlineDialog.allToolsAvailableInherit");try{let O=JSON.parse(m.tools);return Array.isArray(O)?O.length>0?O.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,Rn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Rn.jsx)(ne,{color:Ae.AccentCyan,children:o("agentsOnlineDialog.mcpServers")}),(0,Rn.jsx)(fe,{marginLeft:2,children:(0,Rn.jsx)(ne,{children:(()=>{if(!m.mcps||m.mcps.trim()==="")return o("agentsOnlineDialog.allMcpServersAvailableInherit");try{let O=JSON.parse(m.mcps);return Array.isArray(O)?O.length>0?O.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,Rn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Rn.jsx)(ne,{color:Ae.AccentCyan,children:o("agentsOnlineDialog.systemPrompt")}),(0,Rn.jsx)(fe,{marginLeft:2,children:(0,Rn.jsx)(ne,{children:m.detailContext.length>800?`${m.detailContext.substring(0,800)}...`:m.detailContext})})]}),(0,Rn.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Rn.jsx)(ne,{color:Ae.AccentYellow,children:o("agentsOnlineDialog.actions")}),(0,Rn.jsxs)(ne,{color:Ae.Gray,children:[" ",o("agentsOnlineDialog.installProject")]}),(0,Rn.jsxs)(ne,{color:Ae.Gray,children:[" ",o("agentsOnlineDialog.installUser")]}),(0,Rn.jsxs)(ne,{color:Ae.Gray,children:[" ",o("agentsOnlineDialog.backToList")]}),(0,Rn.jsxs)(ne,{color:Ae.Gray,children:[" ",o("agentsOnlineDialog.exit")]})]}),E&&(0,Rn.jsx)(fe,{marginTop:1,children:(0,Rn.jsxs)(ne,{color:Ae.AccentGreen,children:["\u2705 ",E]})}),A&&(0,Rn.jsx)(fe,{marginTop:1,children:(0,Rn.jsx)(ne,{color:Ae.AccentRed,children:A})})]}):null;return s==="loading"?(0,Rn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Rn.jsx)(ne,{bold:!0,children:o("agentsOnlineDialog.loadingTitle")}),(0,Rn.jsx)(fe,{marginTop:1,children:(0,Rn.jsx)(ne,{children:o("agentsOnlineDialog.loadingMessage")})})]}):(0,Rn.jsx)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:s==="list"?D():P()})}var V5=Te(nr(),1);await Zr();Dn();var wD=Te(nr(),1);await Zr();Dn();var QE=Te(Mt(),1);function Uu({items:t,initialIndex:e=0,onSelect:r,onHighlight:n,isFocused:o,showScrollArrows:s=!1,maxItemsToShow:a=10,showNumbers:c=!0}){let[u,d]=(0,wD.useState)(e),[f,p]=(0,wD.useState)(0),[h,m]=(0,wD.useState)(""),g=(0,wD.useRef)(null);(0,wD.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,wD.useEffect)(()=>()=>{g.current&&clearTimeout(g.current)},[]),Mn(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,QE.jsxs)(fe,{flexDirection:"column",children:[s&&(0,QE.jsx)(ne,{color:f>0?Ae.Foreground:Ae.Gray,children:"\u25B2"}),A.map((y,E)=>{let v=f+E,b=u===v,S=Ae.Foreground,w=Ae.Foreground;b?(S=Ae.AccentGreen,w=Ae.AccentGreen):y.disabled&&(S=Ae.Gray,w=Ae.Gray),c||(w=Ae.Gray);let R=String(t.length).length,D=`${String(v+1).padStart(R)}.`;return(0,QE.jsxs)(fe,{alignItems:"center",children:[(0,QE.jsx)(fe,{minWidth:2,flexShrink:0,children:(0,QE.jsx)(ne,{color:b?Ae.AccentGreen:Ae.Foreground,children:b?"\u25CF":" "})}),(0,QE.jsx)(fe,{marginRight:1,flexShrink:0,minWidth:D.length,children:(0,QE.jsx)(ne,{color:w,children:D})}),y.themeNameDisplay&&y.themeTypeDisplay?(0,QE.jsxs)(ne,{color:S,wrap:"truncate",children:[y.themeNameDisplay," ",(0,QE.jsx)(ne,{color:Ae.Gray,children:y.themeTypeDisplay})]}):(0,QE.jsx)(ne,{color:S,wrap:"truncate",children:y.label})]},y.label)}),s&&(0,QE.jsx)(ne,{color:f+a<t.length?Ae.Foreground:Ae.Gray,children:"\u25BC"})]})}var yae=Te(nr(),1);await Zr();Dn();var Mla=/^[a-zA-Z0-9!@#$%^&*()\-_=+\[\]{}|\\:;"'<>,.?/~]+$/;function urt(t){return!t||t.trim().length===0?!1:Mla.test(t)}Ai();var jE=Te(Mt(),1);function _ae({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,yae.useState)(""),[m,g]=(0,yae.useState)(!0),[A,y]=(0,yae.useState)(null);(0,yae.useEffect)(()=>{if(!o)return;let b=setInterval(()=>{g(S=>!S)},500);return()=>clearInterval(b)},[o]),Mn(b=>{if(b.name==="return"||b.name==="enter"){if(p.trim()){let S=p.trim().replace(/^~+|~+$/g,"");if(s&&!urt(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&&urt(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&&urt(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,jE.jsxs)(fe,{flexDirection:"column",children:[(0,jE.jsx)(fe,{children:(0,jE.jsxs)(ne,{color:Ae.Gray,children:[d," "]})}),(0,jE.jsx)(fe,{marginTop:1,children:(0,jE.jsx)(fe,{borderStyle:"round",borderColor:A?Ae.AccentRed:o?Ae.AccentBlue:Ae.Gray,paddingX:1,width:"100%",children:(0,jE.jsxs)(ne,{children:[E||(0,jE.jsx)(ne,{color:Ae.Gray,children:u}),v]})})}),A&&(0,jE.jsx)(fe,{marginTop:1,children:(0,jE.jsx)(ne,{color:Ae.AccentRed,children:A})}),(0,jE.jsx)(fe,{marginTop:1,children:(0,jE.jsx)(ne,{color:Ae.Gray,dimColor:!0,children:c("passwordInput.instructions")})})]})}vl();Gt();Ai();import{exec as Fla}from"child_process";import{promisify as Lla}from"util";var rM=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 nM=class{default;type;constructor(e){this.default=e.default,this.type=e.type}};var drt=class t{label;value;constructor(e,r){this.label=e,this.value=r}static fromModelInfo(e){return new t(e.display,e.id)}};var frt=class{repoPath;securityLevel;constructor(e){this.repoPath=e.repoPath,this.securityLevel=e.securityLevel}isC3(){return this.securityLevel==="C3"}};var Ula=Lla(Fla);async function prt(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 rM({id:n.id,display:n.display,desc:n.desc,owner:n.owner,supportType:n.supportType,multimodal:n.multimodal,internal:n.internal,defaultConfig:new nM(n.defaultConfig)}))}catch(e){return console.error("Error fetching models:",e),Qla()}}function Qla(){return[new rM({id:"ide-whale/qwen3-coder",display:"Qwen3-Coder",desc:"Qwen3-Coder",owner:"",supportType:["chat","llm","agent"],multimodal:!1,internal:!0,defaultConfig:new nM({default:!0})}),new rM({id:"ide-idealab/claude4-sonnet",display:"Claude-4-Sonnet",desc:"Claude-4-Sonnet",owner:"",supportType:["chat","llm","agent"],multimodal:!0,defaultConfig:new nM({})}),new rM({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 nM({})}),new rM({id:"ide-whale/kimi_k2",display:"Kimi-K2",desc:"Kimi-K2",owner:"",supportType:["chat","llm"],multimodal:!1,internal:!0,defaultConfig:new nM({})})]}function hrt(t){return t.map(e=>drt.fromModelInfo(e))}async function jla(t){try{let e=t?{cwd:t}:{},{stdout:r,stderr:n}=await Ula("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 Gla(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 $la(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 frt({repoPath:o[0].repo_path,securityLevel:o[0].security_level})}catch(r){return console.error("Error fetching security level:",r),null}}function mrt(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 grt(t,e){return!e||!e.isC3()?t:t.filter(r=>r.internal===!0)}async function xH(t,e){let r=await jla(e);if(!r)return console.error("Failed to get git remote URL"),null;let n=Gla(r);return n?$la(n,t):(console.error("Failed to extract repo path from git URL:",r),null)}function Art(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=Te(nr(),1);await Zr();import{spawn as Goi}from"child_process";import*as yrt from"fs/promises";import*as $oi from"path";import*as qoi from"os";var Hoi=t=>t.startsWith("@")||/\s@/.test(t),Voi=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_-]+)/)},Woi=t=>t==="/init",zoi=t=>t.startsWith("$"),Eae=async t=>{let e=(n,o,s)=>new Promise((a,c)=>{let u=s?Goi(n,o,s):Goi(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=$oi.join(qoi.tmpdir(),`iflow-clipboard-${Date.now()}.txt`);try{await yrt.writeFile(n,t,"utf8"),await e("powershell",["-NoProfile","-NonInteractive","-Command",`Get-Content -Path '${n}' -Encoding UTF8 -Raw | Set-Clipboard`])}finally{try{await yrt.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}`)}},Yoi=()=>{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};Dn();Ai();var vae=Te(Mt(),1);function Koi({text:t}){let{t:e}=fr(),[r,n]=(0,$6e.useState)(!1),[o,s]=(0,$6e.useState)(!0),a=async()=>{try{await Eae(t),n(!0),setTimeout(()=>{n(!1)},2e3)}catch{}};return Mn(c=>{o&&c.name==="c"&&(c.ctrl||c.meta)&&a()},{isActive:o}),(0,$6e.useEffect)(()=>(s(!0),()=>{s(!1)}),[]),(0,vae.jsxs)(fe,{borderStyle:"round",marginTop:1,borderColor:r?"green":"gray",flexDirection:"column",gap:1,paddingX:1,children:[(0,vae.jsx)(ne,{color:"gray",children:e("copyableUrlBox.pressCtrlCToCopy")}),(0,vae.jsx)(ne,{color:Ae.AccentBlue,children:t}),(0,vae.jsx)(ne,{color:"gray",children:r?e("copyableUrlBox.copied"):""})]})}var zn=Te(Mt(),1);function Xoi(t){return t&&Object.values(Yt).includes(t)?t:null}function Joi({onSelect:t,settings:e,initialErrorMessage:r}){let{t:n}=fr(),[o,s]=(0,V5.useState)("select"),[a,c]=(0,V5.useState)(null),[u,d]=(0,V5.useState)({baseUrl:"",apiKey:""}),[f,p]=(0,V5.useState)("baseUrl"),[h,m]=(0,V5.useState)(""),[g,A]=(0,V5.useState)(""),[y,E]=(0,V5.useState)(""),[v,b]=(0,V5.useState)([]),[S,w]=(0,V5.useState)(!1),[R,D]=(0,V5.useState)(()=>{if(r)return r;let z=Xoi(process.env.GEMINI_DEFAULT_AUTH_TYPE);return null}),P="global",I=[P==="global"&&{label:n("authDialog.loginWithIFlowRecommend"),value:Yt.LOGIN_WITH_IFLOW},P==="global"&&{label:n("authDialog.loginWithIFlowApiKey"),value:Yt.IFLOW},P==="aone"&&{label:n("authDialog.loginWithAoneRecommend"),value:Yt.LOGIN_WITH_AONE},P==="aone"&&{label:n("authDialog.loginWithAoneApiKey"),value:Yt.AONE},{label:n("authDialog.openaiCompatibleApi"),value:Yt.OPENAI_COMPATIBLE}].filter(Boolean),O=Math.max(0,I.findIndex(z=>{if(e.merged.selectedAuthType)return z.value===e.merged.selectedAuthType;let Y=Xoi(process.env.GEMINI_DEFAULT_AUTH_TYPE);return Y?z.value===Y:P==="aone"?z.value===Yt.LOGIN_WITH_AONE:z.value===Yt.LOGIN_WITH_IFLOW})),k=z=>{if(z===Yt.LOGIN_WITH_IFLOW){let Y=e.merged.isServerOAuth2==="true";if(!QR()||Y){c(z);let J=dSe();E(J),s("input-oauth-code"),D(null)}else{let J=qP(z);J?D(J):(D(null),t(z,"User"))}}else if(N_.includes(z))c(z),s("input-api-key"),D(null);else if(z===Yt.OPENAI_COMPATIBLE)c(z),s("input-openai-config"),p("baseUrl"),d({baseUrl:"",apiKey:""}),D(null);else{let Y=qP(z);Y?D(Y):(D(null),t(z,"User"))}},L=async z=>{if(a&&N_.includes(a)){if(A(z),a===Yt.AONE){w(!0);try{let Y=Buffer.from(z,"utf8").toString("base64"),J=await prt(Y),ue=mrt(J),Se=await xH(z);Se?.isC3()&&(ue=grt(ue,Se));let le=Art(ue),Ce=hrt(le);b(Ce)}catch(Y){console.error("Failed to load models:",Y),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:"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("")}},F=z=>{if(f==="baseUrl")d(Y=>({...Y,baseUrl:z})),p("apiKey");else if(f==="apiKey")d(Y=>({...Y,apiKey:z})),p("modelName");else if(f==="modelName"){d(J=>({...J,modelName:z})),m(z);let Y={...u,modelName:z};t(a,"User",Y)}},M=()=>{s("select"),c(null),D(null)},$=()=>{f==="modelName"?p("apiKey"):f==="apiKey"?p("baseUrl"):(s("select"),c(null),d({baseUrl:"",apiKey:""}),p("baseUrl"),D(null))},j=z=>{if(a&&N_.includes(a))if(m(z),a===Yt.IFLOW){let Y={baseUrl:"https://apis.iflow.cn/v1",apiKey:g,modelName:z,searchApiKey:g};t(a,"User",Y)}else if(a===Yt.AONE){let Y=Buffer.from(g,"utf8").toString("base64"),J={baseUrl:"https://ducky.code.alibaba-inc.com/v1/openai",apiKey:Y,modelName:z,searchApiKey:Y};t(a,"User",J)}else{let Y={apiKey:g,modelName:z};t(a,"User",Y)}},H=z=>{if(a&&N_.includes(a))if(m(z),a===Yt.IFLOW){let Y={baseUrl:"https://apis.iflow.cn/v1",apiKey:g,modelName:z,searchApiKey:g};t(a,"User",Y)}else if(a===Yt.AONE){let Y=Buffer.from(g,"utf8").toString("base64"),J={baseUrl:"https://ducky.code.alibaba-inc.com/v1/openai",apiKey:Y,modelName:z,searchApiKey:Y};t(a,"User",J)}else{let Y={apiKey:g,modelName:z};t(a,"User",Y)}},W=()=>{a&&N_.includes(a)?s("input-api-key"):(s("input-openai-config"),p("apiKey"))},Q=async z=>{try{let Y=await fSe(z);if(Y.apiKey){let J={baseUrl:"https://apis.iflow.cn/v1",apiKey:Y.apiKey,modelName:"qwen3-coder-plus",searchApiKey:Y.apiKey,isServerOAuth2:"true"};t(a,"User",J)}else D(n("authDialog.failedToGetApiKey"))}catch(Y){D(Y instanceof Error?Y.message:n("authDialog.authFailed"))}},X=()=>{s("select"),c(null),E(""),D(null)};return Mn(z=>{if(z.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,zn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,zn.jsx)(ne,{bold:!0,children:n("authDialog.iflowOAuthLogin")}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.oauthStep1")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(Koi,{text:y})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.oauthStep2")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.oauthStep3")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(UE,{onSubmit:Q,onCancel:X,label:n("authDialog.authCodeLabel"),placeholder:n("authDialog.authCodePlaceholder"),isFocused:!0})}),R&&(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{color:Ae.AccentRed,children:R})})]}):o==="input-api-key"?a===Yt.IFLOW?(0,zn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,zn.jsx)(ne,{bold:!0,children:n("authDialog.iflowAuth")}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.enterIFlowApiKey")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(_ae,{onSubmit:L,onCancel:M,label:n("authDialog.apiKeyLabel"),placeholder:n("authDialog.apiKeyPlaceholder"),isFocused:!0,validateApiKey:!0})})]}):(0,zn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,zn.jsx)(ne,{bold:!0,children:n("authDialog.aoneAuth")}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.enterAoneApiKey")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(_ae,{onSubmit:L,onCancel:M,label:n("authDialog.apiKeyLabel"),placeholder:n("authDialog.privateTokenPlaceholder"),isFocused:!0,validateApiKey:!0})})]}):o==="input-model-name"?a===Yt.IFLOW||a===Yt.AONE?S?(0,zn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,zn.jsx)(ne,{bold:!0,children:n("authDialog.modelConfig")}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{color:Ae.AccentBlue,children:n("modelDialog.loading")})})]}):(0,zn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,zn.jsx)(ne,{bold:!0,children:n("authDialog.modelConfig")}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.selectModel")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{color:Ae.AccentBlue,children:n("authDialog.defaultSelection")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(Uu,{items:v,initialIndex:0,onSelect:H,isFocused:!0})})]}):(0,zn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,zn.jsx)(ne,{bold:!0,children:n("authDialog.modelConfig")}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.enterModelName")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(UE,{onSubmit:j,onCancel:W,label:n("authDialog.modelNameLabel"),placeholder:n("authDialog.modelNamePlaceholder"),isFocused:!0})})]}):o==="input-openai-config"?(0,zn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,zn.jsx)(ne,{bold:!0,children:n("authDialog.openaiConfig")}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n(f==="baseUrl"?"authDialog.enterBaseUrl":f==="apiKey"?"authDialog.enterApiKey":"authDialog.enterOpenaiModelName")})}),(0,zn.jsx)(fe,{marginTop:1,children:f==="baseUrl"?(0,zn.jsx)(UE,{onSubmit:F,onCancel:$,label:n("authDialog.baseUrlLabel"),placeholder:n("authDialog.baseUrlPlaceholder"),isFocused:!0}):f==="apiKey"?(0,zn.jsx)(_ae,{onSubmit:F,onCancel:$,label:n("authDialog.apiKeyLabel"),placeholder:n("authDialog.openaiApiKeyPlaceholder"),isFocused:!0,validateApiKey:!0}):(0,zn.jsx)(UE,{onSubmit:F,onCancel:$,label:n("authDialog.modelNameLabel"),placeholder:n("authDialog.openaiModelPlaceholder"),isFocused:!0})}),f==="baseUrl"&&u.baseUrl&&(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{color:Ae.Gray,children:n("authDialog.current",{value:u.baseUrl})})})]}):(0,zn.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,zn.jsx)(ne,{bold:!0,children:n("authDialog.getStarted")}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.howToAuth")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(Uu,{items:I,initialIndex:O,onSelect:k,isFocused:!0})}),R&&(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{color:Ae.AccentRed,children:R})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{color:Ae.Gray,children:n("authDialog.useEnterToSelect")})}),(0,zn.jsx)(fe,{marginTop:1,children:(0,zn.jsx)(ne,{children:n("authDialog.termsOfService")})})]})}var Ert=Te(nr(),1);await Zr();var bae=Te(nr(),1);await Zr();var nsi=Te(rsi(),1);function Hla({type:t="dots"}){let[e,r]=(0,bae.useState)(0),n=nsi.default[t];return(0,bae.useEffect)(()=>{let o=setInterval(()=>{r(s=>s===n.frames.length-1?0:s+1)},n.interval);return()=>{clearInterval(o)}},[n]),bae.default.createElement(ne,null,n.frames[e])}var Cae=Hla;Dn();Ai();var wH=Te(Mt(),1);function isi({onTimeout:t}){let{t:e}=fr(),[r,n]=(0,Ert.useState)(!1);return Mn(o=>{o.name==="escape"&&t()},{isActive:!0}),(0,Ert.useEffect)(()=>{let o=setTimeout(()=>{n(!0),t()},18e4);return()=>clearTimeout(o)},[t]),(0,wH.jsx)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:r?(0,wH.jsx)(ne,{color:Ae.AccentRed,children:e("authInProgress.authTimeout")}):(0,wH.jsx)(fe,{children:(0,wH.jsxs)(ne,{children:[(0,wH.jsx)(Cae,{type:"dots"})," ",e("authInProgress.waitingForAuth")]})})})}await Zr();Dn();Gt();Ai();var q6e=Te(Mt(),1);var osi=({approvalMode:t})=>{let{t:e}=fr(),r="",n="",o="";switch(t){case ei.AUTO_EDIT:r=Ae.AccentGreen,n=e("input.acceptingEdits"),o=e("input.toggleHint");break;case ei.PLAN:r=Ae.AccentGreen,n=e("input.planMode"),o=e("input.toggleHint");break;case ei.YOLO:r=Ae.AccentRed,n=e("input.yoloMode"),o=e("input.toggleHint");break;case ei.DEFAULT:r=Ae.AccentGreen,n=e("input.defaultMode"),o=e("input.toggleHint");break;default:break}return(0,q6e.jsx)(fe,{children:(0,q6e.jsxs)(ne,{color:r,children:[n,o&&(0,q6e.jsx)(ne,{color:Ae.Gray,children:o})]})})};var vrt=Te(nr(),1);await Zr();Ai();Dn();var Qu=Te(Mt(),1);import*as brt from"fs/promises";function ssi({onConfirm:t,onCancel:e,config:r,projectRoot:n}){let{t:o}=fr(),[s,a]=(0,vrt.useState)({sessionCount:0,diskUsage:o("cleanupHistoryDialog.calculating"),projectPath:"",isLoading:!0});(0,vrt.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(()=>($5(),KZt)),h=p.fromPath(n),m=f.getProjectDir(h),g=0,A=0;try{let v=(await brt.readdir(m)).filter(b=>b.endsWith(".jsonl"));g=v.length;for(let b of v){let S=`${m}/${b}`,w=await brt.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]),Mn(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,Qu.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Qu.jsxs)(ne,{bold:!0,children:["\u26A0\uFE0F ",o("cleanupHistoryDialog.title")]}),(0,Qu.jsx)(fe,{marginTop:1,children:(0,Qu.jsx)(ne,{color:Ae.AccentBlue,children:o("cleanupHistoryDialog.loadingStats")})})]}):(0,Qu.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,Qu.jsxs)(ne,{bold:!0,children:["\u26A0\uFE0F ",o("cleanupHistoryDialog.title")]}),(0,Qu.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Qu.jsx)(ne,{children:o("cleanupHistoryDialog.currentStatus")}),(0,Qu.jsxs)(fe,{marginLeft:2,flexDirection:"column",children:[(0,Qu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.projectPath"),(0,Qu.jsx)(ne,{color:Ae.AccentBlue,children:s.projectPath})]}),(0,Qu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.sessions"),(0,Qu.jsxs)(ne,{color:Ae.AccentGreen,children:[s.sessionCount," ",o("cleanupHistoryDialog.sessionsUnit")]})]}),(0,Qu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.diskUsage")," ",(0,Qu.jsx)(ne,{color:Ae.AccentGreen,children:s.diskUsage})]})]})]}),(0,Qu.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,Qu.jsx)(ne,{color:Ae.AccentRed,children:o("cleanupHistoryDialog.warningTitle")}),(0,Qu.jsxs)(fe,{marginLeft:2,flexDirection:"column",children:[(0,Qu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.warningDeleteHistory")]}),(0,Qu.jsxs)(ne,{children:["\u2022 ",o("cleanupHistoryDialog.warningFreeSpace")]})]})]}),(0,Qu.jsx)(fe,{marginTop:1,children:(0,Qu.jsx)(Uu,{items:c,initialIndex:1,onSelect:u,isFocused:!0})}),(0,Qu.jsx)(fe,{marginTop:1,children:(0,Qu.jsx)(ne,{color:Ae.Gray,children:o("cleanupHistoryDialog.instructions")})})]})}var Crt=Te(nr(),1);await Zr();Ai();Dn();Gt();var bl=Te(Mt(),1);import*as asi from"path";function csi({onConfirm:t,onCancel:e,gitService:r,config:n,projectRoot:o}){let{t:s}=fr(),[a,c]=(0,Crt.useState)({checkpointCount:0,commitCount:0,diskUsage:s("cleanupCheckpointDialog.calculating"),isLoading:!0});(0,Crt.useEffect)(()=>{(async()=>{if(!r||!n){c({checkpointCount:0,commitCount:0,diskUsage:s("cleanupCheckpointDialog.unknown"),isLoading:!1});return}try{let p=n.getProjectTempDir()?asi.join(n.getProjectTempDir(),"checkpoints"):void 0;if(!p)throw new Error(s("cleanupCheckpointDialog.cannotGetCheckpointDir"));let m=await new $P(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]),Mn(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,bl.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,bl.jsxs)(ne,{bold:!0,children:["\u26A0\uFE0F ",s("cleanupCheckpointDialog.title")]}),(0,bl.jsx)(fe,{marginTop:1,children:(0,bl.jsx)(ne,{color:Ae.AccentBlue,children:s("cleanupCheckpointDialog.loadingStats")})})]}):(0,bl.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,width:"100%",children:[(0,bl.jsxs)(ne,{bold:!0,children:["\u26A0\uFE0F ",s("cleanupCheckpointDialog.title")]}),(0,bl.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,bl.jsx)(ne,{children:s("cleanupCheckpointDialog.currentStatus")}),(0,bl.jsxs)(fe,{marginLeft:2,flexDirection:"column",children:[(0,bl.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.projectPath"),(0,bl.jsx)(ne,{color:Ae.AccentBlue,children:o})]}),(0,bl.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.checkpoints"),(0,bl.jsxs)(ne,{color:Ae.AccentGreen,children:[a.checkpointCount," ",s("cleanupCheckpointDialog.checkpointsUnit")]})," ",s("cleanupCheckpointDialog.jsonFiles")]}),(0,bl.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.gitHistory"),(0,bl.jsxs)(ne,{color:Ae.AccentGreen,children:[a.commitCount," ",s("cleanupCheckpointDialog.commits")]})]}),(0,bl.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.diskUsage")," ",(0,bl.jsx)(ne,{color:Ae.AccentGreen,children:a.diskUsage})]})]})]}),(0,bl.jsxs)(fe,{marginTop:1,flexDirection:"column",children:[(0,bl.jsx)(ne,{color:Ae.AccentRed,children:s("cleanupCheckpointDialog.warningTitle")}),(0,bl.jsxs)(fe,{marginLeft:2,flexDirection:"column",children:[(0,bl.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.warningDeleteHistory")]}),(0,bl.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.warningFreeSpace")]}),(0,bl.jsxs)(ne,{children:["\u2022 ",s("cleanupCheckpointDialog.warningNoRestore")]})]})]}),(0,bl.jsx)(fe,{marginTop:1,children:(0,bl.jsx)(Uu,{items:u,initialIndex:1,onSelect:d,isFocused:!0})}),(0,bl.jsx)(fe,{marginTop:1,children:(0,bl.jsx)(ne,{color:Ae.Gray,children:s("cleanupCheckpointDialog.instructions")})})]})}var W5=Te(nr(),1);await Zr();Dn();Ai();import Ver from"fs/promises";import Wer from"path";import Vla from"os";var Pi=Te(Mt(),1);function lsi({settings:t,config:e,onExit:r,onStatusUpdate:n}){let{t:o}=fr(),[s,a]=(0,W5.useState)("loading"),[c,u]=(0,W5.useState)([]),[d,f]=(0,W5.useState)(1),[p,h]=(0,W5.useState)(0),[m,g]=(0,W5.useState)(null),[A,y]=(0,W5.useState)(null),[E,v]=(0,W5.useState)(null),[b,S]=(0,W5.useState)(0),w=10,R=Math.ceil(b/w);(0,W5.useEffect)(()=>{let F=async $=>{try{if(!t.merged.apiKey)throw new Error(o("commandsOnlineDialog.apiKeyNotFound"));let H=new URL("https://apis.iflow.cn/v1/commands/list"),W=await fetch(H.toString(),{method:"POST",headers:{"User-Agent":"iFlow-Cli","Content-Type":"application/json"},body:JSON.stringify({page:$,size:w,usePage:!0,visibility:"public",publishStatus:"published"})});if(!W.ok){let Y=o("commandsOnlineDialog.unableToLoadCommands");throw W.status===401?Y=o("commandsOnlineDialog.authenticationFailed"):W.status===403?Y=o("commandsOnlineDialog.accessDenied"):W.status===404?Y=o("commandsOnlineDialog.serviceNotFound"):W.status>=500&&(Y=o("commandsOnlineDialog.serverError")),new Error(Y)}let Q=await W.json();if(!Q.success)throw new Error(Q.message||o("commandsOnlineDialog.failedToFetchCommands"));let X=Array.isArray(Q.data?.data)?Q.data.data:[],z=Q.data?.total||X.length;return{commands:X,total:z}}catch(j){throw new Error(o("commandsOnlineDialog.failedToFetchCommandsWithError",{error:j}))}};(async()=>{try{let $=await F(d);u($.commands),S($.total),a("list"),h(0),$.commands.length===0&&y(o("commandsOnlineDialog.noCommandsFound"))}catch($){y($ instanceof Error?$.message:o("commandsOnlineDialog.failedToLoadCommands")),a("list"),h(0)}})()},[d,t,o]);let D=F=>F.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),P=F=>F==="user"?Wer.join(Vla.homedir(),".iflow","commands"):Wer.join(process.cwd(),".iflow","commands"),I=async(F,M)=>{try{let $=P(M);await Ver.mkdir($,{recursive:!0});let j=`${D(F.name)}.toml`,H=Wer.join($,j);try{return await Ver.access(H),{success:!1,message:o("commandsOnlineDialog.commandAlreadyInstalled",{name:F.name,scope:M})}}catch{}let W=`# Command: ${F.name}
@@ -4601,7 +4601,7 @@ ${N.t("textTruncation.truncatedCharactersAndLines",{characters:c,lines:a})}
4601
4601
  `)}`}break;case"todo_read":return" Reading current todo list";case"read_file":case"read":if(r?.file_path)return` ${cM(r.file_path)}`;break;case"write_file":case"write":if(r?.file_path)return` ${cM(r.file_path)}`;break;case"edit_file":case"edit":if(r?.file_path)return` ${cM(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 ${cM(r.path)}`:""}`;break;case"list_directory":case"ls":return r?.path?` ${cM(r.path)}`:" Current directory";case"glob":if(r?.pattern)return` "${r.pattern}"${r.path?` in ${cM(r.path)}`:""}`;break;case"task":if(r?.prompt){let n=r.prompt.replace(/\\n/g,`
4602
4602
  `);return` "${n.slice(0,80)}${n.length>80?"...":""}"`}if(r?.description)return` "${r.description.replace(/\\n/g,`
4603
4603
  `)}"`;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 jrt(t,e){return t.map(r=>{let n=mfa(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=`${cM(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")?cM(u):u.slice(0,200)}`:`${JSON.stringify(u).slice(0,200)}`).join(", ")}else n=String(r.request.args)}catch{n=N.t("subAgentDisplay.invalidArgs")}let o=hfa(r.request.name,e),s=gfa(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 gfa(t){switch(t){case"scheduled":return"Pending";case"executing":return"Executing";case"success":return"Success";case"error":return"Error";default:return"Pending"}}Fs();Ai();var $a=Te(Mt(),1);var Afa=X5.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,X5.useMemo)(()=>c.map(f=>{let p=jrt([f],o)[0];return(0,$a.jsx)(fe,{marginBottom:0,children:(0,$a.jsx)(Qrt,{...p,terminalWidth:n-Pae,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:Ae.Gray,wrap:"truncate",children:s("subAgentToolMessage.showingLast",{shown:5,total:t.length,hidden:u})})}),d]})}),Pae=3,Hci=({subAgentState:t,terminalWidth:e,config:r,taskToolCallId:n,taskInstanceId:o,constrainHeight:s=!0})=>{let a=(0,X5.useId)(),{t:c}=fr(),{addOverflowingId:u,removeOverflowingId:d}=Srt()||{},f=aM(),p=(0,X5.useMemo)(()=>Array.from(t.agents.values()).filter(A=>!o||!A.id?!0:A.id.includes(o)),[t.agents,o]),h=(0,X5.useMemo)(()=>p.some(A=>{let y=t.toolCalls.get(A.id)||[];return s&&y.length>5}),[p,t.toolCalls,s]);(0,X5.useEffect)(()=>(h?u?.(a):d?.(a),()=>{d?.(a)}),[a,h,u,d]);let m=(0,X5.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:Pae,children:(0,$a.jsx)(ne,{color:Ae.Gray,children:"\u{1F916}"})}),(0,$a.jsx)(fe,{children:(0,$a.jsx)(ne,{color:Ae.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=BI.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:Pae,children:(0,$a.jsx)(ne,{color:A.sessionConfig.color,children:E})}),(0,$a.jsxs)(fe,{children:[(0,$a.jsx)(ne,{color:Ae.Foreground,bold:!0,children:c("subAgentToolMessage.agentTitle",{type:A.sessionConfig.agentType})}),(0,$a.jsxs)(ne,{color:Ae.Gray,children:[" ",yfa(A.status)]}),A.currentRound>0&&(0,$a.jsxs)(ne,{color:Ae.Gray,children:[" (",c("subAgentToolMessage.round",{count:A.currentRound}),")"]}),(0,$a.jsxs)(ne,{color:Ae.Gray,children:[" - ",c("subAgentToolMessage.messageCount",{count:A.messageCount})]}),A.status==="completed"&&(0,$a.jsxs)(ne,{color:Ae.Gray,children:[" \u2022 ",I2(Date.now()-A.startTime)]})]})]}),A.sessionConfig.model&&(0,$a.jsxs)(fe,{paddingLeft:Pae,marginTop:1,flexDirection:"column",children:[(0,$a.jsxs)(ne,{color:Ae.Gray,children:[c("subAgentToolMessage.model"),": ",(0,$a.jsx)(ne,{color:Ae.Foreground,children:A.sessionConfig.model})]}),A.originalRequestedModel&&A.originalRequestedModel!==A.sessionConfig.model&&(0,$a.jsxs)(ne,{color:Ae.AccentYellow,children:["\u26A0 ",c("subAgentToolMessage.originallyRequested",{model:A.originalRequestedModel,reason:A.modelFallbackReason})]})]}),(0,$a.jsxs)(fe,{paddingLeft:Pae,marginTop:1,children:[(0,$a.jsxs)(ne,{color:Ae.Gray,children:[c("subAgentToolMessage.task"),": "]}),(0,$a.jsx)(ne,{wrap:"wrap",children:v})]}),y.length>0&&(0,$a.jsxs)(fe,{paddingLeft:Pae,marginTop:1,flexDirection:"column",children:[(0,$a.jsxs)(ne,{color:Ae.Gray,children:[c("subAgentToolMessage.tools"),":"]}),(0,$a.jsx)(Afa,{agentToolCalls:y,constrainHeight:s,streamingState:f,childWidth:g,config:r})]})]},A.id)})})};function yfa(t){switch(t){case"created":return N.t("subAgentToolMessage.status.created");case"running":return N.t("subAgentToolMessage.status.running");case"completed":return N.t("subAgentToolMessage.status.completed");case"failed":return N.t("subAgentToolMessage.status.failed");default:return N.t("subAgentToolMessage.status.unknown")}}var ec=Te(Mt(),1);var _fa=1,Efa=5,Utr=3,vfa=2,Vci=1e6,zci=({callId:t,name:e,description:r,resultDisplay:n,status:o,confirmationDetails:s,availableTerminalHeight:a,terminalWidth:c,emphasis:u="medium",renderOutputAsMarkdown:d=!0,subAgentState:f,config:p,taskTool:h,constrainHeight:m=!0})=>{let g=a?Math.max(a-_fa-Efa,vfa+1):void 0;g&&(d=!0);let A=c-3;return typeof n=="string"&&n.length>Vci&&(n="..."+n.slice(-Vci)),(0,ec.jsxs)(fe,{paddingX:1,paddingY:0,flexDirection:"column",children:[(0,ec.jsxs)(fe,{minHeight:1,children:[(0,ec.jsx)(bfa,{status:o}),(0,ec.jsx)(Cfa,{name:!1?"":e,status:o,description:r,emphasis:u}),u==="high"&&(0,ec.jsx)(Sfa,{})]}),(0,ec.jsx)(fe,{paddingLeft:Utr,marginTop:1,minHeight:2,children:f?(0,ec.jsx)(Hci,{subAgentState:f,terminalWidth:A,config:p,taskToolCallId:t,taskInstanceId:t,constrainHeight:m}):(0,ec.jsx)(fe,{})}),(0,ec.jsx)(fe,{paddingLeft:Utr,width:"100%",marginTop:1,minHeight:1,children:(0,ec.jsx)(fe,{flexDirection:"column",children:n?(0,ec.jsxs)(ec.Fragment,{children:[typeof n=="string"&&d&&(0,ec.jsx)(fe,{flexDirection:"column",children:(0,ec.jsx)($8,{text:n,isPending:!1,availableTerminalHeight:g,terminalWidth:A})}),typeof n=="string"&&!d&&(0,ec.jsx)(X0,{maxHeight:g,maxWidth:A,children:(0,ec.jsx)(fe,{children:(0,ec.jsx)(ne,{wrap:"wrap",children:n})})}),typeof n!="string"&&(0,ec.jsx)(q8,{diffContent:n.fileDiff,filename:n.fileName,availableTerminalHeight:g,terminalWidth:A})]}):null})})]})},bfa=({status:t})=>(0,ec.jsxs)(fe,{minWidth:Utr,children:[t==="Pending"&&(0,ec.jsx)(ne,{color:Ae.AccentGreen,children:"o"}),t==="Executing"&&(0,ec.jsx)(Bae,{spinnerType:"toggle",nonRespondingDisplay:"\u22B7"}),t==="Success"&&(0,ec.jsx)(ne,{color:Ae.AccentGreen,children:"\u2705"}),t==="Confirming"&&(0,ec.jsx)(ne,{color:Ae.AccentYellow,children:"?"}),t==="Canceled"&&(0,ec.jsx)(ne,{color:Ae.AccentYellow,bold:!0,children:"-"}),t==="Error"&&(0,ec.jsx)(ne,{color:Ae.AccentRed,bold:!0,children:"x"})]}),Cfa=({name:t,description:e,status:r,emphasis:n})=>{let o=Wci.default.useMemo(()=>{switch(n){case"high":return Ae.Foreground;case"medium":return Ae.Foreground;case"low":return Ae.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:Ae.Gray,children:e})]})})},Sfa=()=>(0,ec.jsxs)(ne,{color:Ae.Foreground,wrap:"truncate",children:[" ","\u2190"]});var $rt=Te(nr(),1);await Zr();Fs();Dn();Ai();var Ro=Te(Mt(),1);var xfa=1,wfa=5,Tfa=2,Grt=3,Ifa=({latestToolCall:t,config:e})=>{let{t:r}=fr(),n=$rt.default.useMemo(()=>jrt([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:Ae.Foreground,children:o()})})},Kci=({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-xfa-wfa,Tfa+1):void 0,p=u-3,h=$rt.default.useMemo(()=>o?Array.from(o.agents.values()).filter(E=>!t||!E.id?!0:E.id.includes(t)):[],[o,t]),m=$rt.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,paddingY:0,flexDirection:"column",children:[(0,Ro.jsxs)(fe,{minHeight:1,flexDirection:"row",alignItems:"center",children:[(0,Ro.jsx)(Yci,{status:r}),(0,Ro.jsx)(ne,{color:Ae.Foreground,bold:!0,children:e}),(0,Ro.jsxs)(ne,{color:Ae.Gray,children:[" - ",d("taskAbbreviationMessage.initializing")]})]}),(0,Ro.jsx)(fe,{paddingLeft:Grt,minHeight:1,children:(0,Ro.jsxs)(ne,{color:Ae.Gray,children:["(",d("taskAbbreviationMessage.expandInstructions"),")"]})})]}):(0,Ro.jsxs)(fe,{paddingX:1,paddingY:0,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)(Yci,{status:r}),(0,Ro.jsxs)(fe,{flexDirection:"row",alignItems:"center",flexShrink:1,children:[(0,Ro.jsx)(ne,{color:Ftr(E.sessionConfig.color),backgroundColor:Mtr(E.sessionConfig.color),bold:!0,children:E.sessionConfig.agentType}),S&&(0,Ro.jsx)(Ro.Fragment,{children:(0,Ro.jsxs)(ne,{color:Ae.Gray,children:[" ",S]})})]})]}),b.length>0&&(0,Ro.jsx)(fe,{paddingLeft:Grt,minHeight:1,children:E.status==="running"?(0,Ro.jsxs)(fe,{flexDirection:"column",children:[(0,Ro.jsx)(Ifa,{latestToolCall:b[b.length-1],config:void 0}),b.length>1&&(0,Ro.jsx)(fe,{paddingLeft:3,children:(0,Ro.jsx)(ne,{color:Ae.Gray,children:d("taskAbbreviationMessage.moreToolUses",{count:b.length-1,expandHint:d("taskAbbreviationMessage.expandInstructions")})})})]}):E.status==="completed"?(0,Ro.jsx)(ne,{color:Ae.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:Ae.Gray,children:d("taskAbbreviationMessage.moreToolUses",{count:b.length,expandHint:d("taskAbbreviationMessage.expandInstructions")})})})})]},E.id)}),(0,Ro.jsx)(fe,{paddingLeft:Grt,width:"100%",marginTop:1,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)($8,{text:s,isPending:!1,availableTerminalHeight:f,terminalWidth:p})}),typeof s=="string"&&!a&&(0,Ro.jsx)(X0,{maxHeight:f,maxWidth:p,children:(0,Ro.jsx)(fe,{children:(0,Ro.jsx)(ne,{wrap:"wrap",children:s})})}),typeof s!="string"&&(0,Ro.jsx)(q8,{diffContent:s.fileDiff,filename:s.fileName,availableTerminalHeight:f,terminalWidth:p})]}):null})})]})},Yci=({status:t})=>(0,Ro.jsxs)(fe,{minWidth:Grt,children:[t==="Pending"&&(0,Ro.jsx)(ne,{color:Ae.AccentGreen,children:"o"}),t==="Executing"&&(0,Ro.jsx)(ne,{color:Ae.AccentYellow,children:"\u22B7"}),t==="Success"&&(0,Ro.jsx)(ne,{color:Ae.AccentGreen,children:"\u2705"}),t==="Confirming"&&(0,Ro.jsx)(ne,{color:Ae.AccentYellow,children:"?"}),t==="Canceled"&&(0,Ro.jsx)(ne,{color:Ae.AccentYellow,bold:!0,children:"-"}),t==="Error"&&(0,Ro.jsx)(ne,{color:Ae.AccentRed,bold:!0,children:"x"})]});var qrt=Te(nr(),1);await Zr();Dn();Gt();Ai();var _d=Te(Mt(),1);var Xci=({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,qrt.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(`
4604
- `))}}catch(A){console.warn("Failed to execute notification hook:",A)}},[s,e,t,a]);(0,qrt.useEffect)(()=>{d()},[d]),Mn(A=>{r&&A.name==="escape"&&c(vn.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,_d.jsxs)(fe,{minWidth:"90%",borderStyle:"round",borderColor:Ae.Gray,justifyContent:"space-around",padding:1,overflow:"hidden",children:[(0,_d.jsxs)(ne,{children:[a("toolConfirmationMessage.modifyInProgress")," "]}),(0,_d.jsx)(ne,{color:Ae.AccentGreen,children:a("toolConfirmationMessage.saveAndCloseEditor")})]});h=a("toolConfirmationMessage.applyChangeQuestion"),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:vn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlways"),value:vn.ProceedAlways},{label:a("toolConfirmationMessage.modifyWithEditor"),value:vn.ModifyWithEditor},{label:a("toolConfirmationMessage.noSuggestChanges"),value:vn.Cancel}),p=(0,_d.jsx)(q8,{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:vn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlwaysEllipsis"),value:vn.ProceedAlways},{label:a("toolConfirmationMessage.noSuggestChanges"),value:vn.Cancel});let y=g();y!==void 0&&(y-=2),p=(0,_d.jsx)(fe,{flexDirection:"column",children:(0,_d.jsx)(fe,{paddingX:1,marginLeft:1,children:(0,_d.jsx)(X0,{maxHeight:y,maxWidth:Math.max(u-4,1),children:(0,_d.jsx)(fe,{children:(0,_d.jsx)(ne,{color:Ae.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:vn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlways"),value:vn.ProceedAlways},{label:a("toolConfirmationMessage.noSuggestChanges"),value:vn.Cancel}),p=(0,_d.jsxs)(fe,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,_d.jsx)(ne,{color:Ae.AccentCyan,children:A.prompt}),y&&A.urls&&A.urls.length>0&&(0,_d.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,_d.jsx)(ne,{children:a("toolConfirmationMessage.urlsToFetch")}),A.urls.map(E=>(0,_d.jsxs)(ne,{children:[" - ",E]},E))]})]})}else{let A=t;p=(0,_d.jsxs)(fe,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,_d.jsxs)(ne,{color:Ae.AccentCyan,children:[a("toolConfirmationMessage.mcpServer"),": ",A.serverName]}),(0,_d.jsxs)(ne,{color:Ae.AccentCyan,children:[a("toolConfirmationMessage.tool"),": ",A.toolName]})]}),h=a("toolConfirmationMessage.allowMcpToolQuestion",{toolName:A.toolName,serverName:A.serverName}),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:vn.ProceedOnce},{label:a("toolConfirmationMessage.yesAlwaysAllowTool",{toolName:A.toolName,serverName:A.serverName}),value:vn.ProceedAlwaysTool},{label:a("toolConfirmationMessage.yesAlwaysAllowAllTools",{serverName:A.serverName}),value:vn.ProceedAlwaysServer},{label:a("toolConfirmationMessage.noSuggestChanges"),value:vn.Cancel})}return(0,_d.jsxs)(fe,{flexDirection:"column",padding:1,width:u,children:[(0,_d.jsx)(fe,{flexGrow:1,flexShrink:1,overflow:"hidden",marginBottom:1,children:p}),(0,_d.jsx)(fe,{marginBottom:1,flexShrink:0,children:(0,_d.jsx)(ne,{wrap:"truncate",children:h})}),(0,_d.jsx)(fe,{flexShrink:0,children:(0,_d.jsx)(Uu,{items:m,onSelect:f,isFocused:r})})]})};Dn();var TD=Te(Mt(),1);var Ltr=({toolCalls:t,availableTerminalHeight:e,terminalWidth:r,config:n,isFocused:o=!0,subAgentState:s,taskTool:a,constrainHeight:c=!0,isTaskAbbreviated:u=!0,hookManager:d})=>{let f=!t.every(b=>b.status==="Success"),p=t.some(b=>b.name===MH),h=f||p?Ae.AccentYellow:Ae.Gray,m=3,g=r-4,A=(0,Jci.useMemo)(()=>t.find(b=>b.status==="Confirming"),[t]),y=0;for(let b of t)b.resultDisplay!==void 0&&b.resultDisplay!==""&&y++;let E=t.length-y,v=e?Math.max(Math.floor((e-m-E)/Math.max(1,y)),1):void 0;return(0,TD.jsx)(fe,{flexDirection:"column",borderStyle:"round",width:"100%",marginLeft:1,borderDimColor:f,borderColor:h,children:t.map(b=>{let S=A?.callId===b.callId;return(0,TD.jsxs)(fe,{flexDirection:"column",minHeight:1,children:[(0,TD.jsx)(fe,{flexDirection:"row",alignItems:"center",children:b.name.toLowerCase()==="task"?u?(0,TD.jsx)(Kci,{callId:b.callId,name:b.name,description:b.description,resultDisplay:b.resultDisplay,status:b.status,confirmationDetails:b.confirmationDetails,terminalWidth:g,availableTerminalHeight:v,emphasis:S?"high":A?"low":"medium",subAgentState:s,taskTool:a,renderOutputAsMarkdown:b.renderOutputAsMarkdown}):(0,TD.jsx)(zci,{callId:b.callId,name:b.name,description:b.description,resultDisplay:b.resultDisplay,status:b.status,confirmationDetails:b.confirmationDetails,availableTerminalHeight:v,terminalWidth:g,emphasis:S?"high":A?"low":"medium",renderOutputAsMarkdown:b.renderOutputAsMarkdown,subAgentState:s,config:n,taskTool:a,constrainHeight:c}):(0,TD.jsx)(Qrt,{callId:b.callId,name:b.name,description:b.description,resultDisplay:b.resultDisplay,status:b.status,confirmationDetails:b.confirmationDetails,availableTerminalHeight:v,terminalWidth:g,emphasis:S?"high":A?"low":"medium",renderOutputAsMarkdown:b.renderOutputAsMarkdown,subAgentState:s,config:n,taskTool:a,isTaskAbbreviated:u})}),b.status==="Confirming"&&S&&b.confirmationDetails&&(0,TD.jsx)(Xci,{confirmationDetails:b.confirmationDetails,config:n,isFocused:o,availableTerminalHeight:v,terminalWidth:g,hookManager:d})]},b.callId)})})};await Zr();Dn();Ai();var Qp=Te(Mt(),1);var Qtr=({compression:t,showDetails:e=!1})=>{let{t:r}=fr();return t.isPending?(0,Qp.jsxs)(fe,{flexDirection:"row",children:[(0,Qp.jsx)(fe,{marginRight:1,children:(0,Qp.jsx)(Cae,{type:"dots"})}),(0,Qp.jsx)(fe,{children:(0,Qp.jsx)(ne,{color:Ae.AccentPurple,children:r("compressionMessage.compressingHistory")})})]}):(0,Qp.jsxs)(fe,{flexDirection:"column",children:[(0,Qp.jsx)(fe,{marginY:1,children:(0,Qp.jsxs)(ne,{color:Ae.Gray,children:["==================== ",r("compressionMessage.previousConversationCompressed")," ===================="]})}),(0,Qp.jsxs)(fe,{flexDirection:"row",alignItems:"center",children:[(0,Qp.jsx)(ne,{color:Ae.AccentPurple,children:"\xB7"}),(0,Qp.jsx)(ne,{color:Ae.AccentPurple,children:r("compressionMessage.contextCompressed",{originalTokenCount:t.originalTokenCount?.toLocaleString()??"unknown",newTokenCount:t.newTokenCount?.toLocaleString()??"unknown"})}),(0,Qp.jsx)(ne,{color:Ae.Gray,children:r("compressionMessage.expandCollapseHint",{action:r(e?"compressionMessage.collapse":"compressionMessage.expand")})})]}),e&&t.summary&&(0,Qp.jsxs)(fe,{flexDirection:"column",marginTop:1,marginLeft:2,children:[(0,Qp.jsx)(fe,{marginBottom:1,children:(0,Qp.jsx)(ne,{color:Ae.Gray,children:r("compressionMessage.summaryLabel")})}),(0,Qp.jsx)(fe,{children:(0,Qp.jsx)(ne,{color:Ae.Foreground,wrap:"wrap",children:t.summary})}),(0,Qp.jsx)(fe,{marginTop:1,children:(0,Qp.jsx)(ne,{color:Ae.Gray,children:r("compressionMessage.collapseHint")})})]})]})};await Zr();Dn();var Hrt=Te(Mt(),1);var Zci=({text:t})=>(0,Hrt.jsx)(fe,{borderStyle:"round",borderColor:Ae.AccentPurple,flexDirection:"row",paddingX:2,paddingY:0,marginY:0,alignSelf:"flex-start",children:(0,Hrt.jsx)(fe,{flexGrow:1,children:(0,Hrt.jsx)(ne,{wrap:"wrap",color:Ae.Gray,children:t})})});await Zr();await Zr();var Gtr=Te(Mt(),1);await Zr();jle();import tve from"node:process";import jtr from"node:process";import Dfa from"node:os";import eli from"node:tty";function t4(t,e=globalThis.Deno?globalThis.Deno.args:jtr.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}=jtr,Vrt;t4("no-color")||t4("no-colors")||t4("color=false")||t4("color=never")?Vrt=0:(t4("color")||t4("colors")||t4("color=true")||t4("color=always"))&&(Vrt=1);function Rfa(){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 Nfa(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Ofa(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let n=Rfa();n!==void 0&&(Vrt=n);let o=r?Vrt:n;if(o===0)return 0;if(r){if(t4("color=16m")||t4("color=full")||t4("color=truecolor"))return 3;if(t4("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(jtr.platform==="win32"){let a=Dfa.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 Wrt(t,e={}){let r=Ofa(t,{streamIsTTY:t&&t.isTTY,...e});return Nfa(r)}var Kel={stdout:Wrt({isTTY:eli.isatty(1)}),stderr:Wrt({isTTY:eli.isatty(2)})};import kfa from"process";function lM(t,e=kfa.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}function tli(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 rli(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}=tve.env;if(n)return!(n.length>0&&Number.parseInt(n,10)===0);if(lM("no-hyperlink")||lM("no-hyperlinks")||lM("hyperlink=false")||lM("hyperlink=never"))return!1;if(lM("hyperlink=true")||lM("hyperlink=always")||o)return!0;if(!Wrt(t)||t&&!t.isTTY)return!1;if("WT_SESSION"in tve.env)return!0;if(tve.platform==="win32"||e||s)return!1;if(a){let f=tli(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=tli(u);return f.major>0||f.minor>=50}switch(d){case"alacritty":return!0;case"xterm-kitty":return!0}return!1}var Bfa={stdout:rli(tve.stdout),stderr:rli(tve.stderr)},zrt=Bfa;function FH(t,e,{target:r="stdout",...n}={}){return zrt[r]?Xp.link(t,e):n.fallback===!1?t:typeof n.fallback=="function"?n.fallback(t,e):`${t} ${e}`}FH.isSupported=zrt.stdout;FH.stderr=(t,e,r={})=>FH(t,e,{target:"stderr",...r});FH.stderr.isSupported=zrt.stderr;var Pfa=({children:t,url:e,fallback:r=!0})=>(0,Gtr.jsx)(lz,{transform:n=>FH(n,e,{fallback:r}),children:(0,Gtr.jsx)(ne,{children:t})}),nli=Pfa;Dn();var Mae="9e3a3cb6 (local modifications)";Ai();var No=Te(Mt(),1);var ili=({cliVersion:t,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:o,gcpProject:s})=>{let{t:a}=fr();return(0,No.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,marginY:1,width:"100%",children:[(0,No.jsx)(fe,{marginBottom:1,children:(0,No.jsx)(ne,{bold:!0,color:Ae.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:Ae.LightBlue,children:a("about.cliVersion")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:t})})]}),Mae&&!["N/A"].includes(Mae)&&(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:Ae.LightBlue,children:a("about.gitCommit")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:Mae})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:Ae.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:Ae.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:Ae.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:Ae.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:Ae.LightBlue,children:a("about.serviceAgreement")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(nli,{url:"https://terms.alicdn.com/legal-agreement/terms/common_product_agreement/20250225145154377/20250225145154377.html",children:(0,No.jsx)(ne,{color:Ae.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:Ae.LightBlue,children:a("about.gcpProject")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:s})})]})]})};await Zr();Dn();var HE=Te(nr(),1);Gt();var ali=Te(Mt(),1);var oli=(0,HE.createContext)(void 0),sli=({children:t})=>{let[e,r]=(0,HE.useState)({sessionStartTime:new Date,metrics:D_.getMetrics(),lastPromptTokenCount:0,promptCount:0});(0,HE.useEffect)(()=>{let a=({metrics:c,lastPromptTokenCount:u})=>{r(d=>({...d,metrics:c,lastPromptTokenCount:u}))};return D_.on("update",a),a({metrics:D_.getMetrics(),lastPromptTokenCount:D_.getLastPromptTokenCount()}),()=>{D_.off("update",a)}},[]);let n=(0,HE.useCallback)(()=>{r(a=>({...a,promptCount:a.promptCount+1}))},[]),o=(0,HE.useCallback)(()=>e.promptCount,[e.promptCount]),s=(0,HE.useMemo)(()=>({stats:e,startNewPrompt:n,getPromptCount:o}),[e,n,o]);return(0,ali.jsx)(oli.Provider,{value:s,children:t})},r4=()=>{let t=(0,HE.useContext)(oli);if(t===void 0)throw new Error("useSessionStats must be used within a SessionStatsProvider");return t};Dn();var Yrt=95,Krt=85,Xrt=75,Jrt=45;var Fae=(t,e,r={})=>t>=e.green?Ae.AccentGreen:t>=e.yellow?Ae.AccentYellow:r.defaultColor||Ae.AccentRed;function cli(t){return t.api.totalRequests===0?0:t.api.totalErrors/t.api.totalRequests*100}function lli(t){return t.api.totalRequests===0?0:t.api.totalLatencyMs/t.api.totalRequests}function uli(t){return t.tokens.prompt===0?0:t.tokens.cached/t.tokens.prompt*100}var dli=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}};Ai();var mi=Te(Mt(),1);var rve=({title:t,children:e})=>(0,mi.jsxs)(fe,{children:[(0,mi.jsx)(fe,{width:28,children:(0,mi.jsx)(ne,{color:Ae.LightBlue,children:t})}),e]}),fli=({title:t,children:e})=>(0,mi.jsxs)(fe,{paddingLeft:2,children:[(0,mi.jsx)(fe,{width:26,children:(0,mi.jsxs)(ne,{children:["\xBB ",t]})}),e]}),pli=({title:t,children:e})=>(0,mi.jsxs)(fe,{flexDirection:"column",width:"100%",marginBottom:1,children:[(0,mi.jsx)(ne,{bold:!0,children:t}),e]}),Mfa=({models:t,totalCachedTokens:e,cacheEfficiency:r})=>{let{t:n}=fr(),o=25,s=8,a=15,c=15;return(0,mi.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,mi.jsxs)(fe,{children:[(0,mi.jsx)(fe,{width:o,children:(0,mi.jsx)(ne,{bold:!0,children:n("statsDisplay.modelUsage")})}),(0,mi.jsx)(fe,{width:s,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{bold:!0,children:n("statsDisplay.requests")})}),(0,mi.jsx)(fe,{width:a,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{bold:!0,children:n("statsDisplay.inputTokens")})}),(0,mi.jsx)(fe,{width:c,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{bold:!0,children:n("statsDisplay.outputTokens")})})]}),(0,mi.jsx)(fe,{borderStyle:"round",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:o+s+a+c}),Object.entries(t).map(([u,d])=>(0,mi.jsxs)(fe,{children:[(0,mi.jsx)(fe,{width:o,children:(0,mi.jsx)(ne,{children:u.replace("-001","")})}),(0,mi.jsx)(fe,{width:s,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{children:d.api.totalRequests})}),(0,mi.jsx)(fe,{width:a,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{color:Ae.AccentYellow,children:d.tokens.prompt.toLocaleString()})}),(0,mi.jsx)(fe,{width:c,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{color:Ae.AccentYellow,children:d.tokens.candidates.toLocaleString()})})]},u)),r>0&&(0,mi.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,mi.jsxs)(ne,{children:[(0,mi.jsx)(ne,{color:Ae.AccentGreen,children:n("statsDisplay.savingsHighlight")})," ",e.toLocaleString()," (",r.toFixed(1),"%) ",n("statsDisplay.cacheReduction")]}),(0,mi.jsx)(fe,{height:1}),(0,mi.jsxs)(ne,{color:Ae.Gray,children:["\xBB ",n("statsDisplay.tokenBredownTip")]})]})]})},Zrt=({duration:t,title:e})=>{let{t:r}=fr(),{stats:n}=r4(),{metrics:o}=n,{models:s,tools:a}=o,c=dli(o),u={green:Yrt,yellow:Krt},d={green:Xrt,yellow:Jrt},f=Fae(c.successRate,u),p=Fae(c.agreementRate,d),h=()=>e?Ae.GradientColors&&Ae.GradientColors.length>0?(0,mi.jsx)(Sae,{colors:Ae.GradientColors,children:(0,mi.jsx)(ne,{bold:!0,children:e})}):(0,mi.jsx)(ne,{bold:!0,color:Ae.AccentPurple,children:e}):(0,mi.jsx)(ne,{bold:!0,color:Ae.AccentPurple,children:r("statsDisplay.sessionStats")});return(0,mi.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[h(),(0,mi.jsx)(fe,{height:1}),a.totalCalls>0&&(0,mi.jsxs)(pli,{title:r("statsDisplay.interactionSummary"),children:[(0,mi.jsx)(rve,{title:r("statsDisplay.toolCalls"),children:(0,mi.jsxs)(ne,{children:[a.totalCalls," ("," ",(0,mi.jsxs)(ne,{color:Ae.AccentGreen,children:["\u2705 ",a.totalSuccess]})," ",(0,mi.jsxs)(ne,{color:Ae.AccentRed,children:["\u274E ",a.totalFail]})," )"]})}),(0,mi.jsx)(rve,{title:r("statsDisplay.successRate"),children:(0,mi.jsxs)(ne,{color:f,children:[c.successRate.toFixed(1),"%"]})}),c.totalDecisions>0&&(0,mi.jsx)(rve,{title:r("statsDisplay.userAgreement"),children:(0,mi.jsxs)(ne,{color:p,children:[c.agreementRate.toFixed(1),"%"," ",(0,mi.jsxs)(ne,{color:Ae.Gray,children:["(",c.totalDecisions," ",r("statsDisplay.reviewed"),")"]})]})})]}),(0,mi.jsxs)(pli,{title:r("statsDisplay.performance"),children:[(0,mi.jsx)(rve,{title:r("statsDisplay.wallTime"),children:(0,mi.jsx)(ne,{children:t})}),(0,mi.jsx)(rve,{title:r("statsDisplay.agentActive"),children:(0,mi.jsx)(ne,{children:I2(c.agentActiveTime)})}),(0,mi.jsx)(fli,{title:r("statsDisplay.apiTime"),children:(0,mi.jsxs)(ne,{children:[I2(c.totalApiTime)," ",(0,mi.jsxs)(ne,{color:Ae.Gray,children:["(",c.apiTimePercent.toFixed(1),"%)"]})]})}),(0,mi.jsx)(fli,{title:r("statsDisplay.toolTime"),children:(0,mi.jsxs)(ne,{children:[I2(c.totalToolTime)," ",(0,mi.jsxs)(ne,{color:Ae.Gray,children:["(",c.toolTimePercent.toFixed(1),"%)"]})]})})]}),Object.keys(s).length>0&&(0,mi.jsx)(Mfa,{models:s,totalCachedTokens:c.totalCachedTokens,cacheEfficiency:c.cacheEfficiency})]})};await Zr();Dn();Ai();var tc=Te(Mt(),1);var hli=28,mli=22,J5=({title:t,values:e,isSubtle:r=!1,isSection:n=!1})=>(0,tc.jsxs)(fe,{children:[(0,tc.jsx)(fe,{width:hli,children:(0,tc.jsx)(ne,{bold:n,color:n?void 0:Ae.LightBlue,children:r?` \u21B3 ${t}`:t})}),e.map((o,s)=>(0,tc.jsx)(fe,{width:mli,children:(0,tc.jsx)(ne,{children:o})},s))]}),gli=()=>{let{t}=fr(),{stats:e}=r4(),{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:Ae.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:Ae.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[(0,tc.jsx)(ne,{bold:!0,color:Ae.AccentPurple,children:t("modelStatsDisplay.title")}),(0,tc.jsx)(fe,{height:1}),(0,tc.jsxs)(fe,{children:[(0,tc.jsx)(fe,{width:hli,children:(0,tc.jsx)(ne,{bold:!0,children:t("modelStatsDisplay.metric")})}),o.map(d=>(0,tc.jsx)(fe,{width:mli,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)(J5,{title:t("modelStatsDisplay.api"),values:[],isSection:!0}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.requests"),values:s(d=>d.api.totalRequests.toLocaleString())}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.errors"),values:s(d=>{let f=cli(d);return(0,tc.jsxs)(ne,{color:d.api.totalErrors>0?Ae.AccentRed:Ae.Foreground,children:[d.api.totalErrors.toLocaleString()," (",f.toFixed(1),"%)"]})})}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.avgLatency"),values:s(d=>{let f=lli(d);return I2(f)})}),(0,tc.jsx)(fe,{height:1}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.tokens"),values:[],isSection:!0}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.total"),values:s(d=>(0,tc.jsx)(ne,{color:Ae.AccentYellow,children:d.tokens.total.toLocaleString()}))}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.prompt"),isSubtle:!0,values:s(d=>d.tokens.prompt.toLocaleString())}),u&&(0,tc.jsx)(J5,{title:t("modelStatsDisplay.cached"),isSubtle:!0,values:s(d=>{let f=uli(d);return(0,tc.jsxs)(ne,{color:Ae.AccentGreen,children:[d.tokens.cached.toLocaleString()," (",f.toFixed(1),"%)"]})})}),a&&(0,tc.jsx)(J5,{title:t("modelStatsDisplay.thoughts"),isSubtle:!0,values:s(d=>d.tokens.thoughts.toLocaleString())}),c&&(0,tc.jsx)(J5,{title:t("modelStatsDisplay.tool"),isSubtle:!0,values:s(d=>d.tokens.tool.toLocaleString())}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.output"),isSubtle:!0,values:s(d=>d.tokens.candidates.toLocaleString())})]})};await Zr();Dn();Ai();var Gi=Te(Mt(),1);var LH=25,UH=8,QH=15,jH=15,Ffa=({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=Fae(r,{green:Yrt,yellow:Krt});return(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH,children:(0,Gi.jsx)(ne,{color:Ae.LightBlue,children:t})}),(0,Gi.jsx)(fe,{width:UH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:e.count})}),(0,Gi.jsx)(fe,{width:QH,justifyContent:"flex-end",children:(0,Gi.jsxs)(ne,{color:o,children:[r.toFixed(1),"%"]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:I2(n)})})]})},Ali=()=>{let{t}=fr(),{stats:e}=r4(),{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:Ae.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=Fae(a,{green:Xrt,yellow:Jrt});return(0,Gi.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",paddingY:1,paddingX:2,width:70,children:[(0,Gi.jsx)(ne,{bold:!0,color:Ae.AccentPurple,children:t("toolStatsDisplay.title")}),(0,Gi.jsx)(fe,{height:1}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH,children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.toolName")})}),(0,Gi.jsx)(fe,{width:UH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.calls")})}),(0,Gi.jsx)(fe,{width:QH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.successRate")})}),(0,Gi.jsx)(fe,{width:jH,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)(Ffa,{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:LH+UH+QH,children:(0,Gi.jsx)(ne,{color:Ae.LightBlue,children:t("toolStatsDisplay.totalReviewedSuggestions")})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:s})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH+UH+QH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.accepted")]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:Ae.AccentGreen,children:o.accept})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH+UH+QH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.rejected")]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:Ae.AccentRed,children:o.reject})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH+UH+QH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.modified")]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:Ae.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:LH+UH+QH,children:(0,Gi.jsxs)(ne,{children:[" ",t("toolStatsDisplay.overallAgreementRate")]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,color:s>0?c:void 0,children:s>0?`${a.toFixed(1)}%`:"--"})})]})]})};Ai();var _li=Te(Mt(),1);var yli=({duration:t})=>{let{t:e}=fr();return(0,_li.jsx)(Zrt,{title:e("session.agentPoweringDown"),duration:t})};var ent=Te(nr(),1);await Zr();Dn();Gt();var N2=Te(Mt(),1);function Lfa(t,e){if(!t)return"";let r=t.replace(/\n\s*\n\s*\n/g,`
4604
+ `))}}catch(A){console.warn("Failed to execute notification hook:",A)}},[s,e,t,a]);(0,qrt.useEffect)(()=>{d()},[d]),Mn(A=>{r&&A.name==="escape"&&c(vn.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,_d.jsxs)(fe,{minWidth:"90%",borderStyle:"round",borderColor:Ae.Gray,justifyContent:"space-around",padding:1,overflow:"hidden",children:[(0,_d.jsxs)(ne,{children:[a("toolConfirmationMessage.modifyInProgress")," "]}),(0,_d.jsx)(ne,{color:Ae.AccentGreen,children:a("toolConfirmationMessage.saveAndCloseEditor")})]});h=a("toolConfirmationMessage.applyChangeQuestion"),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:vn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlways"),value:vn.ProceedAlways},{label:a("toolConfirmationMessage.modifyWithEditor"),value:vn.ModifyWithEditor},{label:a("toolConfirmationMessage.noSuggestChanges"),value:vn.Cancel}),p=(0,_d.jsx)(q8,{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:vn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlwaysEllipsis"),value:vn.ProceedAlways},{label:a("toolConfirmationMessage.noSuggestChanges"),value:vn.Cancel});let y=g();y!==void 0&&(y-=2),p=(0,_d.jsx)(fe,{flexDirection:"column",children:(0,_d.jsx)(fe,{paddingX:1,marginLeft:1,children:(0,_d.jsx)(X0,{maxHeight:y,maxWidth:Math.max(u-4,1),children:(0,_d.jsx)(fe,{children:(0,_d.jsx)(ne,{color:Ae.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:vn.ProceedOnce},{label:a("toolConfirmationMessage.yesAllowAlways"),value:vn.ProceedAlways},{label:a("toolConfirmationMessage.noSuggestChanges"),value:vn.Cancel}),p=(0,_d.jsxs)(fe,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,_d.jsx)(ne,{color:Ae.AccentCyan,children:A.prompt}),y&&A.urls&&A.urls.length>0&&(0,_d.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,_d.jsx)(ne,{children:a("toolConfirmationMessage.urlsToFetch")}),A.urls.map(E=>(0,_d.jsxs)(ne,{children:[" - ",E]},E))]})]})}else{let A=t;p=(0,_d.jsxs)(fe,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,_d.jsxs)(ne,{color:Ae.AccentCyan,children:[a("toolConfirmationMessage.mcpServer"),": ",A.serverName]}),(0,_d.jsxs)(ne,{color:Ae.AccentCyan,children:[a("toolConfirmationMessage.tool"),": ",A.toolName]})]}),h=a("toolConfirmationMessage.allowMcpToolQuestion",{toolName:A.toolName,serverName:A.serverName}),m.push({label:a("toolConfirmationMessage.yesAllowOnce"),value:vn.ProceedOnce},{label:a("toolConfirmationMessage.yesAlwaysAllowTool",{toolName:A.toolName,serverName:A.serverName}),value:vn.ProceedAlwaysTool},{label:a("toolConfirmationMessage.yesAlwaysAllowAllTools",{serverName:A.serverName}),value:vn.ProceedAlwaysServer},{label:a("toolConfirmationMessage.noSuggestChanges"),value:vn.Cancel})}return(0,_d.jsxs)(fe,{flexDirection:"column",padding:1,width:u,children:[(0,_d.jsx)(fe,{flexGrow:1,flexShrink:1,overflow:"hidden",marginBottom:1,children:p}),(0,_d.jsx)(fe,{marginBottom:1,flexShrink:0,children:(0,_d.jsx)(ne,{wrap:"truncate",children:h})}),(0,_d.jsx)(fe,{flexShrink:0,children:(0,_d.jsx)(Uu,{items:m,onSelect:f,isFocused:r})})]})};Dn();var TD=Te(Mt(),1);var Ltr=({toolCalls:t,availableTerminalHeight:e,terminalWidth:r,config:n,isFocused:o=!0,subAgentState:s,taskTool:a,constrainHeight:c=!0,isTaskAbbreviated:u=!0,hookManager:d})=>{let f=!t.every(b=>b.status==="Success"),p=t.some(b=>b.name===MH),h=f||p?Ae.AccentYellow:Ae.Gray,m=3,g=r-4,A=(0,Jci.useMemo)(()=>t.find(b=>b.status==="Confirming"),[t]),y=0;for(let b of t)b.resultDisplay!==void 0&&b.resultDisplay!==""&&y++;let E=t.length-y,v=e?Math.max(Math.floor((e-m-E)/Math.max(1,y)),1):void 0;return(0,TD.jsx)(fe,{flexDirection:"column",borderStyle:"round",width:"100%",marginLeft:1,borderDimColor:f,borderColor:h,children:t.map(b=>{let S=A?.callId===b.callId;return(0,TD.jsxs)(fe,{flexDirection:"column",minHeight:1,children:[(0,TD.jsx)(fe,{flexDirection:"row",alignItems:"center",children:b.name.toLowerCase()==="task"?u?(0,TD.jsx)(Kci,{callId:b.callId,name:b.name,description:b.description,resultDisplay:b.resultDisplay,status:b.status,confirmationDetails:b.confirmationDetails,terminalWidth:g,availableTerminalHeight:v,emphasis:S?"high":A?"low":"medium",subAgentState:s,taskTool:a,renderOutputAsMarkdown:b.renderOutputAsMarkdown}):(0,TD.jsx)(zci,{callId:b.callId,name:b.name,description:b.description,resultDisplay:b.resultDisplay,status:b.status,confirmationDetails:b.confirmationDetails,availableTerminalHeight:v,terminalWidth:g,emphasis:S?"high":A?"low":"medium",renderOutputAsMarkdown:b.renderOutputAsMarkdown,subAgentState:s,config:n,taskTool:a,constrainHeight:c}):(0,TD.jsx)(Qrt,{callId:b.callId,name:b.name,description:b.description,resultDisplay:b.resultDisplay,status:b.status,confirmationDetails:b.confirmationDetails,availableTerminalHeight:v,terminalWidth:g,emphasis:S?"high":A?"low":"medium",renderOutputAsMarkdown:b.renderOutputAsMarkdown,subAgentState:s,config:n,taskTool:a,isTaskAbbreviated:u})}),b.status==="Confirming"&&S&&b.confirmationDetails&&(0,TD.jsx)(Xci,{confirmationDetails:b.confirmationDetails,config:n,isFocused:o,availableTerminalHeight:v,terminalWidth:g,hookManager:d})]},b.callId)})})};await Zr();Dn();Ai();var Qp=Te(Mt(),1);var Qtr=({compression:t,showDetails:e=!1})=>{let{t:r}=fr();return t.isPending?(0,Qp.jsxs)(fe,{flexDirection:"row",children:[(0,Qp.jsx)(fe,{marginRight:1,children:(0,Qp.jsx)(Cae,{type:"dots"})}),(0,Qp.jsx)(fe,{children:(0,Qp.jsx)(ne,{color:Ae.AccentPurple,children:r("compressionMessage.compressingHistory")})})]}):(0,Qp.jsxs)(fe,{flexDirection:"column",children:[(0,Qp.jsx)(fe,{marginY:1,children:(0,Qp.jsxs)(ne,{color:Ae.Gray,children:["==================== ",r("compressionMessage.previousConversationCompressed")," ===================="]})}),(0,Qp.jsxs)(fe,{flexDirection:"row",alignItems:"center",children:[(0,Qp.jsx)(ne,{color:Ae.AccentPurple,children:"\xB7"}),(0,Qp.jsx)(ne,{color:Ae.AccentPurple,children:r("compressionMessage.contextCompressed",{originalTokenCount:t.originalTokenCount?.toLocaleString()??"unknown",newTokenCount:t.newTokenCount?.toLocaleString()??"unknown"})}),(0,Qp.jsx)(ne,{color:Ae.Gray,children:r("compressionMessage.expandCollapseHint",{action:r(e?"compressionMessage.collapse":"compressionMessage.expand")})})]}),e&&t.summary&&(0,Qp.jsxs)(fe,{flexDirection:"column",marginTop:1,marginLeft:2,children:[(0,Qp.jsx)(fe,{marginBottom:1,children:(0,Qp.jsx)(ne,{color:Ae.Gray,children:r("compressionMessage.summaryLabel")})}),(0,Qp.jsx)(fe,{children:(0,Qp.jsx)(ne,{color:Ae.Foreground,wrap:"wrap",children:t.summary})}),(0,Qp.jsx)(fe,{marginTop:1,children:(0,Qp.jsx)(ne,{color:Ae.Gray,children:r("compressionMessage.collapseHint")})})]})]})};await Zr();Dn();var Hrt=Te(Mt(),1);var Zci=({text:t})=>(0,Hrt.jsx)(fe,{borderStyle:"round",borderColor:Ae.AccentPurple,flexDirection:"row",paddingX:2,paddingY:0,marginY:0,alignSelf:"flex-start",children:(0,Hrt.jsx)(fe,{flexGrow:1,children:(0,Hrt.jsx)(ne,{wrap:"wrap",color:Ae.Gray,children:t})})});await Zr();await Zr();var Gtr=Te(Mt(),1);await Zr();jle();import tve from"node:process";import jtr from"node:process";import Dfa from"node:os";import eli from"node:tty";function t4(t,e=globalThis.Deno?globalThis.Deno.args:jtr.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}=jtr,Vrt;t4("no-color")||t4("no-colors")||t4("color=false")||t4("color=never")?Vrt=0:(t4("color")||t4("colors")||t4("color=true")||t4("color=always"))&&(Vrt=1);function Rfa(){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 Nfa(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Ofa(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let n=Rfa();n!==void 0&&(Vrt=n);let o=r?Vrt:n;if(o===0)return 0;if(r){if(t4("color=16m")||t4("color=full")||t4("color=truecolor"))return 3;if(t4("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(jtr.platform==="win32"){let a=Dfa.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 Wrt(t,e={}){let r=Ofa(t,{streamIsTTY:t&&t.isTTY,...e});return Nfa(r)}var Kel={stdout:Wrt({isTTY:eli.isatty(1)}),stderr:Wrt({isTTY:eli.isatty(2)})};import kfa from"process";function lM(t,e=kfa.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}function tli(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 rli(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}=tve.env;if(n)return!(n.length>0&&Number.parseInt(n,10)===0);if(lM("no-hyperlink")||lM("no-hyperlinks")||lM("hyperlink=false")||lM("hyperlink=never"))return!1;if(lM("hyperlink=true")||lM("hyperlink=always")||o)return!0;if(!Wrt(t)||t&&!t.isTTY)return!1;if("WT_SESSION"in tve.env)return!0;if(tve.platform==="win32"||e||s)return!1;if(a){let f=tli(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=tli(u);return f.major>0||f.minor>=50}switch(d){case"alacritty":return!0;case"xterm-kitty":return!0}return!1}var Bfa={stdout:rli(tve.stdout),stderr:rli(tve.stderr)},zrt=Bfa;function FH(t,e,{target:r="stdout",...n}={}){return zrt[r]?Xp.link(t,e):n.fallback===!1?t:typeof n.fallback=="function"?n.fallback(t,e):`${t} ${e}`}FH.isSupported=zrt.stdout;FH.stderr=(t,e,r={})=>FH(t,e,{target:"stderr",...r});FH.stderr.isSupported=zrt.stderr;var Pfa=({children:t,url:e,fallback:r=!0})=>(0,Gtr.jsx)(lz,{transform:n=>FH(n,e,{fallback:r}),children:(0,Gtr.jsx)(ne,{children:t})}),nli=Pfa;Dn();var Mae="a49b88f (local modifications)";Ai();var No=Te(Mt(),1);var ili=({cliVersion:t,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:o,gcpProject:s})=>{let{t:a}=fr();return(0,No.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",padding:1,marginY:1,width:"100%",children:[(0,No.jsx)(fe,{marginBottom:1,children:(0,No.jsx)(ne,{bold:!0,color:Ae.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:Ae.LightBlue,children:a("about.cliVersion")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:t})})]}),Mae&&!["N/A"].includes(Mae)&&(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:Ae.LightBlue,children:a("about.gitCommit")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:Mae})})]}),(0,No.jsxs)(fe,{flexDirection:"row",children:[(0,No.jsx)(fe,{width:"35%",children:(0,No.jsx)(ne,{bold:!0,color:Ae.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:Ae.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:Ae.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:Ae.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:Ae.LightBlue,children:a("about.serviceAgreement")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(nli,{url:"https://terms.alicdn.com/legal-agreement/terms/common_product_agreement/20250225145154377/20250225145154377.html",children:(0,No.jsx)(ne,{color:Ae.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:Ae.LightBlue,children:a("about.gcpProject")})}),(0,No.jsx)(fe,{children:(0,No.jsx)(ne,{children:s})})]})]})};await Zr();Dn();var HE=Te(nr(),1);Gt();var ali=Te(Mt(),1);var oli=(0,HE.createContext)(void 0),sli=({children:t})=>{let[e,r]=(0,HE.useState)({sessionStartTime:new Date,metrics:D_.getMetrics(),lastPromptTokenCount:0,promptCount:0});(0,HE.useEffect)(()=>{let a=({metrics:c,lastPromptTokenCount:u})=>{r(d=>({...d,metrics:c,lastPromptTokenCount:u}))};return D_.on("update",a),a({metrics:D_.getMetrics(),lastPromptTokenCount:D_.getLastPromptTokenCount()}),()=>{D_.off("update",a)}},[]);let n=(0,HE.useCallback)(()=>{r(a=>({...a,promptCount:a.promptCount+1}))},[]),o=(0,HE.useCallback)(()=>e.promptCount,[e.promptCount]),s=(0,HE.useMemo)(()=>({stats:e,startNewPrompt:n,getPromptCount:o}),[e,n,o]);return(0,ali.jsx)(oli.Provider,{value:s,children:t})},r4=()=>{let t=(0,HE.useContext)(oli);if(t===void 0)throw new Error("useSessionStats must be used within a SessionStatsProvider");return t};Dn();var Yrt=95,Krt=85,Xrt=75,Jrt=45;var Fae=(t,e,r={})=>t>=e.green?Ae.AccentGreen:t>=e.yellow?Ae.AccentYellow:r.defaultColor||Ae.AccentRed;function cli(t){return t.api.totalRequests===0?0:t.api.totalErrors/t.api.totalRequests*100}function lli(t){return t.api.totalRequests===0?0:t.api.totalLatencyMs/t.api.totalRequests}function uli(t){return t.tokens.prompt===0?0:t.tokens.cached/t.tokens.prompt*100}var dli=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}};Ai();var mi=Te(Mt(),1);var rve=({title:t,children:e})=>(0,mi.jsxs)(fe,{children:[(0,mi.jsx)(fe,{width:28,children:(0,mi.jsx)(ne,{color:Ae.LightBlue,children:t})}),e]}),fli=({title:t,children:e})=>(0,mi.jsxs)(fe,{paddingLeft:2,children:[(0,mi.jsx)(fe,{width:26,children:(0,mi.jsxs)(ne,{children:["\xBB ",t]})}),e]}),pli=({title:t,children:e})=>(0,mi.jsxs)(fe,{flexDirection:"column",width:"100%",marginBottom:1,children:[(0,mi.jsx)(ne,{bold:!0,children:t}),e]}),Mfa=({models:t,totalCachedTokens:e,cacheEfficiency:r})=>{let{t:n}=fr(),o=25,s=8,a=15,c=15;return(0,mi.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,mi.jsxs)(fe,{children:[(0,mi.jsx)(fe,{width:o,children:(0,mi.jsx)(ne,{bold:!0,children:n("statsDisplay.modelUsage")})}),(0,mi.jsx)(fe,{width:s,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{bold:!0,children:n("statsDisplay.requests")})}),(0,mi.jsx)(fe,{width:a,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{bold:!0,children:n("statsDisplay.inputTokens")})}),(0,mi.jsx)(fe,{width:c,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{bold:!0,children:n("statsDisplay.outputTokens")})})]}),(0,mi.jsx)(fe,{borderStyle:"round",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:o+s+a+c}),Object.entries(t).map(([u,d])=>(0,mi.jsxs)(fe,{children:[(0,mi.jsx)(fe,{width:o,children:(0,mi.jsx)(ne,{children:u.replace("-001","")})}),(0,mi.jsx)(fe,{width:s,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{children:d.api.totalRequests})}),(0,mi.jsx)(fe,{width:a,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{color:Ae.AccentYellow,children:d.tokens.prompt.toLocaleString()})}),(0,mi.jsx)(fe,{width:c,justifyContent:"flex-end",children:(0,mi.jsx)(ne,{color:Ae.AccentYellow,children:d.tokens.candidates.toLocaleString()})})]},u)),r>0&&(0,mi.jsxs)(fe,{flexDirection:"column",marginTop:1,children:[(0,mi.jsxs)(ne,{children:[(0,mi.jsx)(ne,{color:Ae.AccentGreen,children:n("statsDisplay.savingsHighlight")})," ",e.toLocaleString()," (",r.toFixed(1),"%) ",n("statsDisplay.cacheReduction")]}),(0,mi.jsx)(fe,{height:1}),(0,mi.jsxs)(ne,{color:Ae.Gray,children:["\xBB ",n("statsDisplay.tokenBredownTip")]})]})]})},Zrt=({duration:t,title:e})=>{let{t:r}=fr(),{stats:n}=r4(),{metrics:o}=n,{models:s,tools:a}=o,c=dli(o),u={green:Yrt,yellow:Krt},d={green:Xrt,yellow:Jrt},f=Fae(c.successRate,u),p=Fae(c.agreementRate,d),h=()=>e?Ae.GradientColors&&Ae.GradientColors.length>0?(0,mi.jsx)(Sae,{colors:Ae.GradientColors,children:(0,mi.jsx)(ne,{bold:!0,children:e})}):(0,mi.jsx)(ne,{bold:!0,color:Ae.AccentPurple,children:e}):(0,mi.jsx)(ne,{bold:!0,color:Ae.AccentPurple,children:r("statsDisplay.sessionStats")});return(0,mi.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[h(),(0,mi.jsx)(fe,{height:1}),a.totalCalls>0&&(0,mi.jsxs)(pli,{title:r("statsDisplay.interactionSummary"),children:[(0,mi.jsx)(rve,{title:r("statsDisplay.toolCalls"),children:(0,mi.jsxs)(ne,{children:[a.totalCalls," ("," ",(0,mi.jsxs)(ne,{color:Ae.AccentGreen,children:["\u2705 ",a.totalSuccess]})," ",(0,mi.jsxs)(ne,{color:Ae.AccentRed,children:["\u274E ",a.totalFail]})," )"]})}),(0,mi.jsx)(rve,{title:r("statsDisplay.successRate"),children:(0,mi.jsxs)(ne,{color:f,children:[c.successRate.toFixed(1),"%"]})}),c.totalDecisions>0&&(0,mi.jsx)(rve,{title:r("statsDisplay.userAgreement"),children:(0,mi.jsxs)(ne,{color:p,children:[c.agreementRate.toFixed(1),"%"," ",(0,mi.jsxs)(ne,{color:Ae.Gray,children:["(",c.totalDecisions," ",r("statsDisplay.reviewed"),")"]})]})})]}),(0,mi.jsxs)(pli,{title:r("statsDisplay.performance"),children:[(0,mi.jsx)(rve,{title:r("statsDisplay.wallTime"),children:(0,mi.jsx)(ne,{children:t})}),(0,mi.jsx)(rve,{title:r("statsDisplay.agentActive"),children:(0,mi.jsx)(ne,{children:I2(c.agentActiveTime)})}),(0,mi.jsx)(fli,{title:r("statsDisplay.apiTime"),children:(0,mi.jsxs)(ne,{children:[I2(c.totalApiTime)," ",(0,mi.jsxs)(ne,{color:Ae.Gray,children:["(",c.apiTimePercent.toFixed(1),"%)"]})]})}),(0,mi.jsx)(fli,{title:r("statsDisplay.toolTime"),children:(0,mi.jsxs)(ne,{children:[I2(c.totalToolTime)," ",(0,mi.jsxs)(ne,{color:Ae.Gray,children:["(",c.toolTimePercent.toFixed(1),"%)"]})]})})]}),Object.keys(s).length>0&&(0,mi.jsx)(Mfa,{models:s,totalCachedTokens:c.totalCachedTokens,cacheEfficiency:c.cacheEfficiency})]})};await Zr();Dn();Ai();var tc=Te(Mt(),1);var hli=28,mli=22,J5=({title:t,values:e,isSubtle:r=!1,isSection:n=!1})=>(0,tc.jsxs)(fe,{children:[(0,tc.jsx)(fe,{width:hli,children:(0,tc.jsx)(ne,{bold:n,color:n?void 0:Ae.LightBlue,children:r?` \u21B3 ${t}`:t})}),e.map((o,s)=>(0,tc.jsx)(fe,{width:mli,children:(0,tc.jsx)(ne,{children:o})},s))]}),gli=()=>{let{t}=fr(),{stats:e}=r4(),{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:Ae.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:Ae.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[(0,tc.jsx)(ne,{bold:!0,color:Ae.AccentPurple,children:t("modelStatsDisplay.title")}),(0,tc.jsx)(fe,{height:1}),(0,tc.jsxs)(fe,{children:[(0,tc.jsx)(fe,{width:hli,children:(0,tc.jsx)(ne,{bold:!0,children:t("modelStatsDisplay.metric")})}),o.map(d=>(0,tc.jsx)(fe,{width:mli,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)(J5,{title:t("modelStatsDisplay.api"),values:[],isSection:!0}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.requests"),values:s(d=>d.api.totalRequests.toLocaleString())}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.errors"),values:s(d=>{let f=cli(d);return(0,tc.jsxs)(ne,{color:d.api.totalErrors>0?Ae.AccentRed:Ae.Foreground,children:[d.api.totalErrors.toLocaleString()," (",f.toFixed(1),"%)"]})})}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.avgLatency"),values:s(d=>{let f=lli(d);return I2(f)})}),(0,tc.jsx)(fe,{height:1}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.tokens"),values:[],isSection:!0}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.total"),values:s(d=>(0,tc.jsx)(ne,{color:Ae.AccentYellow,children:d.tokens.total.toLocaleString()}))}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.prompt"),isSubtle:!0,values:s(d=>d.tokens.prompt.toLocaleString())}),u&&(0,tc.jsx)(J5,{title:t("modelStatsDisplay.cached"),isSubtle:!0,values:s(d=>{let f=uli(d);return(0,tc.jsxs)(ne,{color:Ae.AccentGreen,children:[d.tokens.cached.toLocaleString()," (",f.toFixed(1),"%)"]})})}),a&&(0,tc.jsx)(J5,{title:t("modelStatsDisplay.thoughts"),isSubtle:!0,values:s(d=>d.tokens.thoughts.toLocaleString())}),c&&(0,tc.jsx)(J5,{title:t("modelStatsDisplay.tool"),isSubtle:!0,values:s(d=>d.tokens.tool.toLocaleString())}),(0,tc.jsx)(J5,{title:t("modelStatsDisplay.output"),isSubtle:!0,values:s(d=>d.tokens.candidates.toLocaleString())})]})};await Zr();Dn();Ai();var Gi=Te(Mt(),1);var LH=25,UH=8,QH=15,jH=15,Ffa=({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=Fae(r,{green:Yrt,yellow:Krt});return(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH,children:(0,Gi.jsx)(ne,{color:Ae.LightBlue,children:t})}),(0,Gi.jsx)(fe,{width:UH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:e.count})}),(0,Gi.jsx)(fe,{width:QH,justifyContent:"flex-end",children:(0,Gi.jsxs)(ne,{color:o,children:[r.toFixed(1),"%"]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:I2(n)})})]})},Ali=()=>{let{t}=fr(),{stats:e}=r4(),{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:Ae.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=Fae(a,{green:Xrt,yellow:Jrt});return(0,Gi.jsxs)(fe,{borderStyle:"round",borderColor:Ae.Gray,flexDirection:"column",paddingY:1,paddingX:2,width:70,children:[(0,Gi.jsx)(ne,{bold:!0,color:Ae.AccentPurple,children:t("toolStatsDisplay.title")}),(0,Gi.jsx)(fe,{height:1}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH,children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.toolName")})}),(0,Gi.jsx)(fe,{width:UH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.calls")})}),(0,Gi.jsx)(fe,{width:QH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,children:t("toolStatsDisplay.successRate")})}),(0,Gi.jsx)(fe,{width:jH,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)(Ffa,{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:LH+UH+QH,children:(0,Gi.jsx)(ne,{color:Ae.LightBlue,children:t("toolStatsDisplay.totalReviewedSuggestions")})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{children:s})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH+UH+QH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.accepted")]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:Ae.AccentGreen,children:o.accept})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH+UH+QH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.rejected")]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:Ae.AccentRed,children:o.reject})})]}),(0,Gi.jsxs)(fe,{children:[(0,Gi.jsx)(fe,{width:LH+UH+QH,children:(0,Gi.jsxs)(ne,{children:[" \xBB ",t("toolStatsDisplay.modified")]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{color:Ae.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:LH+UH+QH,children:(0,Gi.jsxs)(ne,{children:[" ",t("toolStatsDisplay.overallAgreementRate")]})}),(0,Gi.jsx)(fe,{width:jH,justifyContent:"flex-end",children:(0,Gi.jsx)(ne,{bold:!0,color:s>0?c:void 0,children:s>0?`${a.toFixed(1)}%`:"--"})})]})]})};Ai();var _li=Te(Mt(),1);var yli=({duration:t})=>{let{t:e}=fr();return(0,_li.jsx)(Zrt,{title:e("session.agentPoweringDown"),duration:t})};var ent=Te(nr(),1);await Zr();Dn();Gt();var N2=Te(Mt(),1);function Lfa(t,e){if(!t)return"";let r=t.replace(/\n\s*\n\s*\n/g,`
4605
4605
 
4606
4606
  `);if(e&&e>20){let n=r.split(`
4607
4607
  `),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(`
@@ -5718,7 +5718,7 @@ ${N.t("gemini.errors.criticalUnhandledRejection")}
5718
5718
  =========================================
5719
5719
  ${N.t("gemini.errors.reason",{reason:e})}${e instanceof Error&&e.stack?`
5720
5720
  ${N.t("gemini.errors.stackTrace")}
5721
- ${e.stack}`:""}`;Hs.emit("log-error",n),t||(t=!0,Hs.emit("open-debug-console"))})}function Sya(){console.log(N.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.3.29-beta.2"}},r=`crash-${Date.now()}-${process.pid}.json`,n=mya.join(process.cwd(),r);try{_ya.writeFileSync(n,JSON.stringify(e,null,2)),console.error(N.t("gemini.crashDetected",{crashFilePath:n})),console.error(N.t("gemini.coreDumpWillBeGenerated"))}catch(o){console.error(N.t("gemini.failedToWriteCrashFile"),o)}process.abort()}),process.on("warning",t=>{console.warn(N.t("gemini.debug.nodejsWarning"),{name:t.name,message:t.message,stack:t.stack})}),process.on("unhandledRejection",(t,e)=>{console.error(N.t("gemini.debug.unhandledPromiseRejectionDetected"),{reason:t,promise:e.toString()})})}async function D2i(){if(Cya(),I2i.platform()==="win32")try{let{execSync:g}=await import("node:child_process");g("chcp 65001",{stdio:"ignore"})}catch{}let t=process.cwd(),e=El(t);if(!e.user.settings.cna){let g=await wOe();g&&e.setValue("User","cna",g)}if(await eoi(),e.errors.length>0){for(let g of e.errors){let A=N.t("gemini.errorInFile",{path:g.path,message:g.message});process.env.NO_COLOR||(A=`\x1B[31m${A}\x1B[0m`),console.error(A),console.error(N.t("gemini.pleaseFixFileAndTryAgain",{path:g.path}))}process.exit(1)}let r=await trt(),n=typeof r.resume=="string";(!!r.prompt&&!r.promptInteractive&&!r.continue&&(!r.resume||n)||r.experimentalAcp)&&(process.env.IFLOW_NON_INTERACTIVE="true");let s=YP(t),a=n&&typeof r.resume=="string"?r.resume:kg.generateSessionId(),c=await SH(e.merged,s,a,r);if(N.changeLanguage(c.getLanguage()),c.getDebugMode()&&Sya(),Aya.setDefaultResultOrder(Eya(e.merged.dnsResolutionOrder)),r.promptInteractive&&!process.stdin.isTTY&&(console.error(N.t("gemini.errors.promptInteractiveFlagNotSupported")),process.exit(1)),c.getListExtensions()){console.debug(N.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(()=>(Uer(),Yii)),A=(await Promise.resolve().then(()=>(jir(),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(()=>(Fer(),Pii)),A=(await Promise.resolve().then(()=>(jir(),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),msi(c.getDebugMode()),await c.initialize(),c.getExperimentalAcp()?c.setUsageMode("sdk"):c.setUsageMode("interactive"),ea.loadCustomThemes(e.merged.customThemes),e.merged.theme&&(ea.setActiveTheme(e.merged.theme)||console.warn(N.t("gemini.themeNotFound",{theme:e.merged.theme}))),!process.env.SANDBOX){let g=e.merged.autoConfigureMaxOldSpaceSize?vya(c):[],A=c.getSandbox();if(A){if(e.merged.selectedAuthType&&!e.merged.useExternalAuth)try{let y=qP(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(N.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(N.t("gemini.errorAuthenticating"),y),process.exit(1)}await gAi(A,g,c),process.exit(0)}else g.length>0&&(await bya(g),process.exit(0))}if(e.merged.selectedAuthType===Yt.LOGIN_WITH_IFLOW&&c.isBrowserLaunchSuppressed())try{await jF(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 UAi(c,e,s,r,c.getAcpPort()):OAi(c,e,s,r);let u=c.getQuestion(),d=[...await AAi(),...await _Ai(t)];if(!!r.promptInteractive||!!r.continue||!!r.resume&&!n||process.stdin.isTTY&&u?.length===0){console.clear();let g=await eM();T2i(w2i(t),e);try{await Fli()}catch(S){c.getDebugMode()&&console.warn("Failed to detect/enable Kitty protocol:",S)}try{await c.setIdeModeAndSyncConnection(!0)}catch(S){console.error(N.t("gemini.failedToConnectToIdeServer"),S)}let A,y=async()=>{try{if(console.clear(),T2i(w2i(t),e),A)try{A.unmount(),await new Promise(R=>process.nextTick(R))}catch(R){console.error(N.t("gemini.errorDuringUnmount"),R)}let{executeSessionStartHooks:S}=await Promise.resolve().then(()=>(VH(),HH)),w=await S(c,"resume");A=xCe((0,Kve.jsx)(Gir.default.StrictMode,{children:(0,Kve.jsx)(Xnr,{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:arr(),maxFps:20})}catch(S){console.error(N.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(()=>(VH(),HH)),b=await v(c,E);A=xCe((0,Kve.jsx)(Gir.default.StrictMode,{children:(0,Kve.jsx)(Xnr,{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:arr()}),e.merged.disableAutoUpdate||_it().then(S=>{toi(S,e,c.getProjectRoot())}).catch(S=>{c.getDebugMode()&&console.error(N.t("gemini.updateCheckFailed"),S)}),j6e(()=>A.unmount());return}!process.stdin.isTTY&&!u&&(u+=await fAi()),u||(console.error(N.t("gemini.noInputProvidedViaStdin")),process.exit(1));let p=Math.random().toString(16).slice(2);rJ(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 xya(c,s,e,r),m=r.outputFile||r.output_file;await bAi(h,u,p,m),process.exit(0)}function T2i(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 xya(t,e,r,n){let o=t;if(t.getApprovalMode()!==ei.YOLO){let s=r.merged.excludeTools||[],a=[zd.Name,_h.Name,zf.Name],c=[...new Set([...s,...a])],u={...r.merged,excludeTools:c},d={...n};o=await SH(u,e,t.getSessionId(),d),await o.initialize()}return await wya(r.merged.selectedAuthType,o,r)}async function wya(t,e,r){!t&&!process.env.IFLOW_API_KEY&&!JOe()&&(console.error(N.t("gemini.pleaseSetAuthMethod",{userSettingsPath:aH})),process.exit(1)),t||(JOe()?t=Yt.IFLOW:t=Yt.IFLOW);let n=qP(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}D2i().catch(t=>{console.error("An unexpected critical error occurred:"),t instanceof Error?console.error(t.stack):console.error(String(t)),process.exit(1)});
5721
+ ${e.stack}`:""}`;Hs.emit("log-error",n),t||(t=!0,Hs.emit("open-debug-console"))})}function Sya(){console.log(N.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.3.30"}},r=`crash-${Date.now()}-${process.pid}.json`,n=mya.join(process.cwd(),r);try{_ya.writeFileSync(n,JSON.stringify(e,null,2)),console.error(N.t("gemini.crashDetected",{crashFilePath:n})),console.error(N.t("gemini.coreDumpWillBeGenerated"))}catch(o){console.error(N.t("gemini.failedToWriteCrashFile"),o)}process.abort()}),process.on("warning",t=>{console.warn(N.t("gemini.debug.nodejsWarning"),{name:t.name,message:t.message,stack:t.stack})}),process.on("unhandledRejection",(t,e)=>{console.error(N.t("gemini.debug.unhandledPromiseRejectionDetected"),{reason:t,promise:e.toString()})})}async function D2i(){if(Cya(),I2i.platform()==="win32")try{let{execSync:g}=await import("node:child_process");g("chcp 65001",{stdio:"ignore"})}catch{}let t=process.cwd(),e=El(t);if(!e.user.settings.cna){let g=await wOe();g&&e.setValue("User","cna",g)}if(await eoi(),e.errors.length>0){for(let g of e.errors){let A=N.t("gemini.errorInFile",{path:g.path,message:g.message});process.env.NO_COLOR||(A=`\x1B[31m${A}\x1B[0m`),console.error(A),console.error(N.t("gemini.pleaseFixFileAndTryAgain",{path:g.path}))}process.exit(1)}let r=await trt(),n=typeof r.resume=="string";(!!r.prompt&&!r.promptInteractive&&!r.continue&&(!r.resume||n)||r.experimentalAcp)&&(process.env.IFLOW_NON_INTERACTIVE="true");let s=YP(t),a=n&&typeof r.resume=="string"?r.resume:kg.generateSessionId(),c=await SH(e.merged,s,a,r);if(N.changeLanguage(c.getLanguage()),c.getDebugMode()&&Sya(),Aya.setDefaultResultOrder(Eya(e.merged.dnsResolutionOrder)),r.promptInteractive&&!process.stdin.isTTY&&(console.error(N.t("gemini.errors.promptInteractiveFlagNotSupported")),process.exit(1)),c.getListExtensions()){console.debug(N.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(()=>(Uer(),Yii)),A=(await Promise.resolve().then(()=>(jir(),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(()=>(Fer(),Pii)),A=(await Promise.resolve().then(()=>(jir(),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),msi(c.getDebugMode()),await c.initialize(),c.getExperimentalAcp()?c.setUsageMode("sdk"):c.setUsageMode("interactive"),ea.loadCustomThemes(e.merged.customThemes),e.merged.theme&&(ea.setActiveTheme(e.merged.theme)||console.warn(N.t("gemini.themeNotFound",{theme:e.merged.theme}))),!process.env.SANDBOX){let g=e.merged.autoConfigureMaxOldSpaceSize?vya(c):[],A=c.getSandbox();if(A){if(e.merged.selectedAuthType&&!e.merged.useExternalAuth)try{let y=qP(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(N.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(N.t("gemini.errorAuthenticating"),y),process.exit(1)}await gAi(A,g,c),process.exit(0)}else g.length>0&&(await bya(g),process.exit(0))}if(e.merged.selectedAuthType===Yt.LOGIN_WITH_IFLOW&&c.isBrowserLaunchSuppressed())try{await jF(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 UAi(c,e,s,r,c.getAcpPort()):OAi(c,e,s,r);let u=c.getQuestion(),d=[...await AAi(),...await _Ai(t)];if(!!r.promptInteractive||!!r.continue||!!r.resume&&!n||process.stdin.isTTY&&u?.length===0){console.clear();let g=await eM();T2i(w2i(t),e);try{await Fli()}catch(S){c.getDebugMode()&&console.warn("Failed to detect/enable Kitty protocol:",S)}try{await c.setIdeModeAndSyncConnection(!0)}catch(S){console.error(N.t("gemini.failedToConnectToIdeServer"),S)}let A,y=async()=>{try{if(console.clear(),T2i(w2i(t),e),A)try{A.unmount(),await new Promise(R=>process.nextTick(R))}catch(R){console.error(N.t("gemini.errorDuringUnmount"),R)}let{executeSessionStartHooks:S}=await Promise.resolve().then(()=>(VH(),HH)),w=await S(c,"resume");A=xCe((0,Kve.jsx)(Gir.default.StrictMode,{children:(0,Kve.jsx)(Xnr,{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:arr(),maxFps:20})}catch(S){console.error(N.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(()=>(VH(),HH)),b=await v(c,E);A=xCe((0,Kve.jsx)(Gir.default.StrictMode,{children:(0,Kve.jsx)(Xnr,{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:arr()}),e.merged.disableAutoUpdate||_it().then(S=>{toi(S,e,c.getProjectRoot())}).catch(S=>{c.getDebugMode()&&console.error(N.t("gemini.updateCheckFailed"),S)}),j6e(()=>A.unmount());return}!process.stdin.isTTY&&!u&&(u+=await fAi()),u||(console.error(N.t("gemini.noInputProvidedViaStdin")),process.exit(1));let p=Math.random().toString(16).slice(2);rJ(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 xya(c,s,e,r),m=r.outputFile||r.output_file;await bAi(h,u,p,m),process.exit(0)}function T2i(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 xya(t,e,r,n){let o=t;if(t.getApprovalMode()!==ei.YOLO){let s=r.merged.excludeTools||[],a=[zd.Name,_h.Name,zf.Name],c=[...new Set([...s,...a])],u={...r.merged,excludeTools:c},d={...n};o=await SH(u,e,t.getSessionId(),d),await o.initialize()}return await wya(r.merged.selectedAuthType,o,r)}async function wya(t,e,r){!t&&!process.env.IFLOW_API_KEY&&!JOe()&&(console.error(N.t("gemini.pleaseSetAuthMethod",{userSettingsPath:aH})),process.exit(1)),t||(JOe()?t=Yt.IFLOW:t=Yt.IFLOW);let n=qP(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}D2i().catch(t=>{console.error("An unexpected critical error occurred:"),t instanceof Error?console.error(t.stack):console.error(String(t)),process.exit(1)});
5722
5722
  /**
5723
5723
  * @license
5724
5724
  * Copyright 2025 Google LLC