@naarang/ccc 3.2.0-beta.2 → 3.3.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -51,7 +51,7 @@ Event: ${N7(Z)}`),!0}return!1}function yP1(Z,J){if(!J?.length)return!1;return Vz
51
51
  `;let K=$i(X);X.write(`${W}\r
52
52
  `);let{connect:z,buffered:G}=await K;if(Z.emit("proxyConnect",z),this.emit("proxyConnect",z,Z),z.statusCode===200){if(Z.once("socket",Ah1),J.secureEndpoint){n3("Upgrading socket connection to TLS");let V=J.servername||J.host;return RD.connect({...Xi(J,"host","path","port"),socket:X,servername:N9.isIP(V)?void 0:V})}return X}X.destroy();let H=new N9.Socket({writable:!1});return H.readable=!0,Z.once("socket",(V)=>{n3("Replaying proxy buffer for failed request"),V.push(G),V.push(null)}),H}}QG.__initStatic();function Ah1(Z){Z.resume()}function Xi(Z,...J){let $={},X;for(X in Z)if(!J.includes(X))$[X]=Z[X];return $}var Rh1=32768;function Ch1(Z){return new jh1({read(){this.push(Z),this.push(null)}})}function CD(Z){let J;try{J=new URL(Z.url)}catch(z){return o0(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),WJ(Z,()=>Promise.resolve({}))}let $=J.protocol==="https:",X=qh1(J,Z.proxy||($?process.env.https_proxy:void 0)||process.env.http_proxy),Y=$?Mh1:Th1,Q=Z.keepAlive===void 0?!1:Z.keepAlive,W=X?new QG(X):new Y.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),K=Eh1(Z,Z.httpModule??Y,W);return WJ(Z,K)}function qh1(Z,J){let{no_proxy:$}=process.env;if($?.split(",").some((Y)=>Z.host.endsWith(Y)||Z.hostname.endsWith(Y)))return;else return J}function Eh1(Z,J,$){let{hostname:X,pathname:Y,port:Q,protocol:W,search:K}=new URL(Z.url);return function(G){return new Promise((H,V)=>{S7(()=>{let F=Ch1(G.body),B={...Z.headers};if(G.body.length>Rh1)B["content-encoding"]="gzip",F=F.pipe(Nh1());let U=X.startsWith("["),L=J.request({method:"POST",agent:$,headers:B,hostname:U?X.slice(1,-1):X,path:`${Y}${K}`,port:Q,protocol:W,ca:Z.caCerts},(O)=>{O.on("data",()=>{}),O.on("end",()=>{}),O.setEncoding("utf8");let _=O.headers["retry-after"]??null,w=O.headers["x-sentry-rate-limits"]??null;H({statusCode:O.statusCode,headers:{"retry-after":_,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});L.on("error",V),F.pipe(L)})})}}var Ph1=new Set(["false","f","n","no","off","0"]),Ih1=new Set(["true","t","y","yes","on","1"]);function WG(Z,J){let $=String(Z).toLowerCase();if(Ph1.has($))return!1;if(Ih1.has($))return!0;return J?.strict?null:Boolean(Z)}import{posix as Sh1,sep as yh1}from"path";function Yi(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function qD(Z=process.argv[1]?Z2(process.argv[1]):process.cwd(),J=yh1==="\\"){let $=J?Yi(Z):Z;return(X)=>{if(!X)return;let Y=J?Yi(X):X,{dir:Q,base:W,ext:K}=Sh1.parse(Y);if(K===".js"||K===".mjs"||K===".cjs")W=W.slice(0,K.length*-1);let z=decodeURIComponent(W);if(!Q)Q=".";let G=Q.lastIndexOf("/node_modules");if(G>-1)return`${Q.slice(G+14).replace(/\//g,".")}:${z}`;if(Q.startsWith($)){let H=Q.slice($.length+1).replace(/\//g,".");return H?`${H}:${z}`:z}return z}}function ED(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(G1.SENTRY_RELEASE?.id)return G1.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,$=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,X=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||$||X||Z}var PD=lK(N2(qD()));var Wi=v(u(),1),Ki=v(D1(),1);import*as Qi from"os";import{threadId as kh1,isMainThread as xh1}from"worker_threads";var vh1=60000;class KG extends Uz{constructor(Z){let J=Z.includeServerName===!1?void 0:Z.serverName||global.process.env.SENTRY_NAME||Qi.hostname(),$={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)Ki.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});_9($,"node"),R.log(`Initializing Sentry: process: ${process.pid}, thread: ${xh1?"main":`worker-${kh1}`}.`);super($);if(this.getOptions().enableLogs){if(this._logOnExitFlushListener=()=>{B3(this)},J)this.on("beforeCaptureLog",(X)=>{X.attributes={...X.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=u1,$=Wi.trace.getTracer(Z,J);return this._tracer=$,$}async flush(Z){if(await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}async close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);let J=await super.close(Z);if(this.traceProvider)await this.traceProvider.shutdown();return J}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{E1&&R.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??vh1).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_setupIntegrations(){nL(),super._setupIntegrations()}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return sl(this,Z)}}var zi=v(kU(),1);import*as Gi from"module";function ID(){if(!kp())return;if(!G1._sentryEsmLoaderHookRegistered){G1._sentryEsmLoaderHookRegistered=!0;try{let{addHookMessagePort:Z}=zi.createAddHookMessageChannel();Gi.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:Z,include:[]},transferList:[Z]})}catch(Z){R.warn("Failed to register 'import-in-the-middle' hook",Z)}}}function zG(){return[f$(),h$(),b$(),g$(),OD(),m$(),ep(),Zi(),HX(),VX(),zX(),BD(),KX(),wD(),Ji(),GX()]}function SD(Z={}){return hh1(Z,zG)}function hh1(Z={},J){let $=fh1(Z,J);if($.debug===!0)if(E1)R.enable();else o0(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if($.registerEsmLoaderHooks!==!1)ID();if(Zp(),e1().update($.initialScope),$.spotlight&&!$.integrations.some(({name:Q})=>Q===LD))$.integrations.push(DD({sidecarUrl:typeof $.spotlight==="string"?$.spotlight:void 0}));_9($,"node-core");let Y=new KG($);if(e1().setClient(Y),Y.init(),G1._sentryInjectLoaderHookRegister?.(),R.log(`SDK initialized from ${d3()?"CommonJS":"ESM"}`),Y.startClientReportTracking(),mh1(),bl(Y),el(Y),process.env.VERCEL)process.on("SIGTERM",async()=>{await Y.flush(200)});return Y}function GG(){if(!E1)return;let Z=dl(),J=["SentryContextManager","SentryPropagator"];if(P0())J.push("SentrySpanProcessor");for(let $ of J)if(!Z.includes($))R.error(`You have to set up the ${$}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))R.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function fh1(Z,J){let $=bh1(Z.release),X;if(Z.spotlight===!1)X=!1;else if(typeof Z.spotlight==="string")X=Z.spotlight;else{let z=WG(process.env.SENTRY_SPOTLIGHT,{strict:!0}),G=z===null&&process.env.SENTRY_SPOTLIGHT?process.env.SENTRY_SPOTLIGHT:void 0;X=Z.spotlight===!0?G??!0:z??G}let Y=gh1(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??CD,stackParser:QL(Z.stackParser||PD),release:$,tracesSampleRate:Y,spotlight:X,debug:WG(Z.debug??process.env.SENTRY_DEBUG)},W=Z.integrations,K=Z.defaultIntegrations??J(Q);return{...Q,integrations:vL({defaultIntegrations:K,integrations:W})}}function bh1(Z){if(Z!==void 0)return Z;let J=ED();if(J!==void 0)return J;return}function gh1(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let $=parseFloat(J);return isFinite($)?$:void 0}function mh1(){if(WG(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,$=ZJ(Z,J);e1().setPropagationContext($)}}function Y0(Z,J){Z.setAttribute(W1,J)}var yD="Http",Hi="@opentelemetry_sentry-patched/instrumentation-http",uh1=s(`${yD}.sentry`,(Z)=>{return new YX(Z)}),dh1=s(yD,(Z)=>{let J=new Fi.HttpInstrumentation({...Z,disableIncomingRequestInstrumentation:!0});try{J._diag=Vi.diag.createComponentLogger({namespace:Hi}),J.instrumentationName=Hi}catch{}return J});function ch1(Z,J={}){if(typeof Z.spans==="boolean")return Z.spans;if(J.skipOpenTelemetrySetup)return!1;if(!P0(J)&&o7.major>=22)return!1;return!0}var a3=k((Z={})=>{let J=Z.spans??!0,$=Z.disableIncomingRequestSpans,X={sessions:Z.trackIncomingRequestsAsSessions,sessionFlushingDelayMS:Z.sessionFlushingDelayMS,ignoreRequestBody:Z.ignoreIncomingRequestBody,maxRequestBodySize:Z.maxIncomingRequestBodySize},Y={ignoreIncomingRequests:Z.ignoreIncomingRequests,ignoreStaticAssets:Z.ignoreStaticAssets,ignoreStatusCodes:Z.dropSpansForIncomingRequestStatusCodes,instrumentation:Z.instrumentation,onSpanCreated:Z.incomingRequestSpanHook},Q=a$(X),W=o$(Y),K=J&&!$;return{name:yD,setup(z){let G=z.getOptions();if(K&&P0(G))W.setup(z)},setupOnce(){let z=p()?.getOptions()||{},G=ch1(Z,z);Q.setupOnce();let H={breadcrumbs:Z.breadcrumbs,propagateTraceInOutgoingRequests:!G,ignoreOutgoingRequests:Z.ignoreOutgoingRequests};if(uh1(H),G){let V=lh1(Z);dh1(V)}},processEvent(z){return W.processEvent(z)}}});function lh1(Z={}){return{ignoreOutgoingRequestHook:($)=>{let X=S3($);if(!X)return!1;let Y=Z.ignoreOutgoingRequests;if(Y?.(X,$))return!0;return!1},requireParentforOutgoingSpans:!1,requestHook:($,X)=>{Y0($,"auto.http.otel.http"),Z.instrumentation?.requestHook?.($,X)},responseHook:($,X)=>{Z.instrumentation?.responseHook?.($,X)},applyCustomAttributesOnSpan:($,X,Y)=>{Z.instrumentation?.applyCustomAttributesOnSpan?.($,X,Y)}}}var Mi=v(Ti(),1);var ji="NodeFetch",oh1=s(ji,Mi.UndiciInstrumentation,(Z)=>{return Zf1(Z)}),rh1=s(`${ji}.sentry`,WX,(Z)=>{return Z}),sh1=(Z={})=>{return{name:"NodeFetch",setupOnce(){if(eh1(Z,p()?.getOptions()))oh1(Z);rh1(Z)}}},r3=k(sh1);function th1(Z,J="/"){let $=`${Z}`;if($.endsWith("/")&&J.startsWith("/"))return`${$}${J.slice(1)}`;if(!$.endsWith("/")&&!J.startsWith("/"))return`${$}/${J.slice(1)}`;return`${$}${J}`}function eh1(Z,J={}){return typeof Z.spans==="boolean"?Z.spans:!J.skipOpenTelemetrySetup&&P0(J)}function Zf1(Z={}){return{requireParentforSpans:!1,ignoreRequestHook:($)=>{let X=th1($.origin,$.path),Y=Z.ignoreOutgoingRequests;return!!(Y&&X&&Y(X))},startSpanHook:()=>{return{[W1]:"auto.http.otel.node_fetch"}},requestHook:Z.requestHook,responseHook:Z.responseHook}}var pi=v(li(),1);var u0=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var ii="Express";function Rf1(Z){Y0(Z,"auto.http.otel.express");let J=X1(Z).data,$=J["express.type"];if($)Z.setAttribute(U1,`${$}.express`);let X=J["express.name"];if(typeof X==="string")Z.updateName(X)}function Cf1(Z,J){if(d1()===y6())return u0&&R.warn("Isolation scope is still default isolation scope - skipping setting transactionName"),J;if(Z.layerType==="request_handler"){let $=Z.request,X=$.method?$.method.toUpperCase():"GET";d1().setTransactionName(`${X} ${Z.route}`)}return J}var ni=s(ii,()=>new pi.ExpressInstrumentation({requestHook:(Z)=>Rf1(Z),spanNameHook:(Z,J)=>Cf1(Z,J)})),qf1=()=>{return{name:ii,setupOnce(){ni()}}},ai=k(qf1);import*as nD from"diagnostics_channel";var s0=v(u(),1),OG=v(N0(),1),Rn=v(D1(),1),Y4=v(X0(),1);import An from"diagnostics_channel";var Ln=v(Kn(),1);var e3=(Z)=>{if(typeof Z!=="string")throw TypeError("invalid pattern");if(Z.length>65536)throw TypeError("pattern is too long")};var vf1={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},ZQ=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),hf1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zn=(Z)=>Z.join(""),Gn=(Z,J)=>{let $=J;if(Z.charAt($)!=="[")throw Error("not in a brace expression");let X=[],Y=[],Q=$+1,W=!1,K=!1,z=!1,G=!1,H=$,V="";Z:while(Q<Z.length){let L=Z.charAt(Q);if((L==="!"||L==="^")&&Q===$+1){G=!0,Q++;continue}if(L==="]"&&W&&!z){H=Q+1;break}if(W=!0,L==="\\"){if(!z){z=!0,Q++;continue}}if(L==="["&&!z){for(let[O,[_,w,A]]of Object.entries(vf1))if(Z.startsWith(O,Q)){if(V)return["$.",!1,Z.length-$,!0];if(Q+=O.length,A)Y.push(_);else X.push(_);K=K||w;continue Z}}if(z=!1,V){if(L>V)X.push(ZQ(V)+"-"+ZQ(L));else if(L===V)X.push(ZQ(L));V="",Q++;continue}if(Z.startsWith("-]",Q+1)){X.push(ZQ(L+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){V=L,Q+=2;continue}X.push(ZQ(L)),Q++}if(H<Q)return["",!1,0,!1];if(!X.length&&!Y.length)return["$.",!1,Z.length-$,!0];if(Y.length===0&&X.length===1&&/^\\?.$/.test(X[0])&&!G){let L=X[0].length===2?X[0].slice(-1):X[0];return[hf1(L),!1,H-$,!1]}let F="["+(G?"^":"")+zn(X)+"]",B="["+(G?"":"^")+zn(Y)+"]";return[X.length&&Y.length?"("+F+"|"+B+")":X.length?F:B,K,H-$,!0]};var r7=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var ff1=new Set(["!","?","+","*","@"]),Hn=(Z)=>ff1.has(Z),bf1="(?!(?:^|/)\\.\\.?(?:$|/))",LG="(?!\\.)",gf1=new Set(["[","."]),mf1=new Set(["..","."]),uf1=new Set("().*{}+?[]^$\\!"),df1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),dD="[^/]",Vn=dD+"*?",Fn=dD+"+?";class S4{type;#Z;#J;#Y=!1;#X=[];#Q;#B;#W;#H=!1;#z;#K;#$=!1;constructor(Z,J,$={}){if(this.type=Z,Z)this.#J=!0;if(this.#Q=J,this.#Z=this.#Q?this.#Q.#Z:this,this.#z=this.#Z===this?$:this.#Z.#z,this.#W=this.#Z===this?[]:this.#Z.#W,Z==="!"&&!this.#Z.#H)this.#W.push(this);this.#B=this.#Q?this.#Q.#X.length:0}get hasMagic(){if(this.#J!==void 0)return this.#J;for(let Z of this.#X){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#J=!0}return this.#J}toString(){if(this.#K!==void 0)return this.#K;if(!this.type)return this.#K=this.#X.map((Z)=>String(Z)).join("");else return this.#K=this.type+"("+this.#X.map((Z)=>String(Z)).join("|")+")"}#L(){if(this!==this.#Z)throw Error("should only call on root");if(this.#H)return this;this.toString(),this.#H=!0;let Z;while(Z=this.#W.pop()){if(Z.type!=="!")continue;let J=Z,$=J.#Q;while($){for(let X=J.#B+1;!$.type&&X<$.#X.length;X++)for(let Y of Z.#X){if(typeof Y==="string")throw Error("string part in extglob AST??");Y.copyIn($.#X[X])}J=$,$=J.#Q}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof S4&&J.#Q===this))throw Error("invalid part: "+J);this.#X.push(J)}}toJSON(){let Z=this.type===null?this.#X.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#X.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#Z||this.#Z.#H&&this.#Q?.type==="!"))Z.push({});return Z}isStart(){if(this.#Z===this)return!0;if(!this.#Q?.isStart())return!1;if(this.#B===0)return!0;let Z=this.#Q;for(let J=0;J<this.#B;J++){let $=Z.#X[J];if(!($ instanceof S4&&$.type==="!"))return!1}return!0}isEnd(){if(this.#Z===this)return!0;if(this.#Q?.type==="!")return!0;if(!this.#Q?.isEnd())return!1;if(!this.type)return this.#Q?.isEnd();let Z=this.#Q?this.#Q.#X.length:0;return this.#B===Z-1}copyIn(Z){if(typeof Z==="string")this.push(Z);else this.push(Z.clone(this))}clone(Z){let J=new S4(this.type,Z);for(let $ of this.#X)J.copyIn($);return J}static#D(Z,J,$,X){let Y=!1,Q=!1,W=-1,K=!1;if(J.type===null){let F=$,B="";while(F<Z.length){let U=Z.charAt(F++);if(Y||U==="\\"){Y=!Y,B+=U;continue}if(Q){if(F===W+1){if(U==="^"||U==="!")K=!0}else if(U==="]"&&!(F===W+2&&K))Q=!1;B+=U;continue}else if(U==="["){Q=!0,W=F,K=!1,B+=U;continue}if(!X.noext&&Hn(U)&&Z.charAt(F)==="("){J.push(B),B="";let L=new S4(U,J);F=S4.#D(Z,L,F,X),J.push(L);continue}B+=U}return J.push(B),F}let z=$+1,G=new S4(null,J),H=[],V="";while(z<Z.length){let F=Z.charAt(z++);if(Y||F==="\\"){Y=!Y,V+=F;continue}if(Q){if(z===W+1){if(F==="^"||F==="!")K=!0}else if(F==="]"&&!(z===W+2&&K))Q=!1;V+=F;continue}else if(F==="["){Q=!0,W=z,K=!1,V+=F;continue}if(Hn(F)&&Z.charAt(z)==="("){G.push(V),V="";let B=new S4(F,G);G.push(B),z=S4.#D(Z,B,z,X);continue}if(F==="|"){G.push(V),V="",H.push(G),G=new S4(null,J);continue}if(F===")"){if(V===""&&J.#X.length===0)J.#$=!0;return G.push(V),V="",J.push(...H,G),z}V+=F}return J.type=null,J.#J=void 0,J.#X=[Z.substring($-1)],z}static fromGlob(Z,J={}){let $=new S4(null,void 0,J);return S4.#D(Z,$,0,J),$}toMMPattern(){if(this!==this.#Z)return this.#Z.toMMPattern();let Z=this.toString(),[J,$,X,Y]=this.toRegExpSource();if(!(X||this.#J||this.#z.nocase&&!this.#z.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return $;let W=(this.#z.nocase?"i":"")+(Y?"u":"");return Object.assign(new RegExp(`^${J}$`,W),{_src:J,_glob:Z})}get options(){return this.#z}toRegExpSource(Z){let J=Z??!!this.#z.dot;if(this.#Z===this)this.#L();if(!this.type){let K=this.isStart()&&this.isEnd(),z=this.#X.map((F)=>{let[B,U,L,O]=typeof F==="string"?S4.#V(F,this.#J,K):F.toRegExpSource(Z);return this.#J=this.#J||L,this.#Y=this.#Y||O,B}).join(""),G="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&mf1.has(this.#X[0]))){let B=gf1,U=J&&B.has(z.charAt(0))||z.startsWith("\\.")&&B.has(z.charAt(2))||z.startsWith("\\.\\.")&&B.has(z.charAt(4)),L=!J&&!Z&&B.has(z.charAt(0));G=U?bf1:L?LG:""}}}let H="";if(this.isEnd()&&this.#Z.#H&&this.#Q?.type==="!")H="(?:$|\\/)";return[G+z+H,r7(z),this.#J=!!this.#J,this.#Y]}let $=this.type==="*"||this.type==="+",X=this.type==="!"?"(?:(?!(?:":"(?:",Y=this.#F(J);if(this.isStart()&&this.isEnd()&&!Y&&this.type!=="!"){let K=this.toString();return this.#X=[K],this.type=null,this.#J=void 0,[K,r7(this.toString()),!1,!1]}let Q=!$||Z||J||!LG?"":this.#F(!0);if(Q===Y)Q="";if(Q)Y=`(?:${Y})(?:${Q})*?`;let W="";if(this.type==="!"&&this.#$)W=(this.isStart()&&!J?LG:"")+Fn;else{let K=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?LG:"")+Vn+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;W=X+Y+K}return[W,r7(Y),this.#J=!!this.#J,this.#Y]}#F(Z){return this.#X.map((J)=>{if(typeof J==="string")throw Error("string type in extglob ast??");let[$,X,Y,Q]=J.toRegExpSource(Z);return this.#Y=this.#Y||Q,$}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#V(Z,J,$=!1){let X=!1,Y="",Q=!1;for(let W=0;W<Z.length;W++){let K=Z.charAt(W);if(X){X=!1,Y+=(uf1.has(K)?"\\":"")+K;continue}if(K==="\\"){if(W===Z.length-1)Y+="\\\\";else X=!0;continue}if(K==="["){let[z,G,H,V]=Gn(Z,W);if(H){Y+=z,Q=Q||G,W+=H-1,J=J||V;continue}}if(K==="*"){if($&&Z==="*")Y+=Fn;else Y+=Vn;J=!0;continue}if(K==="?"){Y+=dD,J=!0;continue}Y+=df1(K)}return[Y,r7(Z),!!J,Q]}}var cD=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var y4=(Z,J,$={})=>{if(e3(J),!$.nocomment&&J.charAt(0)==="#")return!1;return new JQ(J,$).match(Z)},cf1=/^\*+([^+@!?\*\[\(]*)$/,lf1=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),pf1=(Z)=>(J)=>J.endsWith(Z),if1=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},nf1=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},af1=/^\*+\.\*+$/,of1=(Z)=>!Z.startsWith(".")&&Z.includes("."),rf1=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),sf1=/^\.\*+$/,tf1=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),ef1=/^\*+$/,Zb1=(Z)=>Z.length!==0&&!Z.startsWith("."),Jb1=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",$b1=/^\?+([^+@!?\*\[\(]*)?$/,Xb1=([Z,J=""])=>{let $=Dn([Z]);if(!J)return $;return J=J.toLowerCase(),(X)=>$(X)&&X.toLowerCase().endsWith(J)},Yb1=([Z,J=""])=>{let $=On([Z]);if(!J)return $;return J=J.toLowerCase(),(X)=>$(X)&&X.toLowerCase().endsWith(J)},Qb1=([Z,J=""])=>{let $=On([Z]);return!J?$:(X)=>$(X)&&X.endsWith(J)},Wb1=([Z,J=""])=>{let $=Dn([Z]);return!J?$:(X)=>$(X)&&X.endsWith(J)},Dn=([Z])=>{let J=Z.length;return($)=>$.length===J&&!$.startsWith(".")},On=([Z])=>{let J=Z.length;return($)=>$.length===J&&$!=="."&&$!==".."},_n=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Bn={win32:{sep:"\\"},posix:{sep:"/"}},Kb1=_n==="win32"?Bn.win32.sep:Bn.posix.sep;y4.sep=Kb1;var V8=Symbol("globstar **");y4.GLOBSTAR=V8;var zb1="[^/]",Gb1=zb1+"*?",Hb1="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Vb1="(?:(?!(?:\\/|^)\\.).)*?",Fb1=(Z,J={})=>($)=>y4($,Z,J);y4.filter=Fb1;var H8=(Z,J={})=>Object.assign({},Z,J),Bb1=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return y4;let J=y4;return Object.assign((X,Y,Q={})=>J(X,Y,H8(Z,Q)),{Minimatch:class extends J.Minimatch{constructor(Y,Q={}){super(Y,H8(Z,Q))}static defaults(Y){return J.defaults(H8(Z,Y)).Minimatch}},AST:class extends J.AST{constructor(Y,Q,W={}){super(Y,Q,H8(Z,W))}static fromGlob(Y,Q={}){return J.AST.fromGlob(Y,H8(Z,Q))}},unescape:(X,Y={})=>J.unescape(X,H8(Z,Y)),escape:(X,Y={})=>J.escape(X,H8(Z,Y)),filter:(X,Y={})=>J.filter(X,H8(Z,Y)),defaults:(X)=>J.defaults(H8(Z,X)),makeRe:(X,Y={})=>J.makeRe(X,H8(Z,Y)),braceExpand:(X,Y={})=>J.braceExpand(X,H8(Z,Y)),match:(X,Y,Q={})=>J.match(X,Y,H8(Z,Q)),sep:J.sep,GLOBSTAR:V8})};y4.defaults=Bb1;var wn=(Z,J={})=>{if(e3(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return Ln.default(Z)};y4.braceExpand=wn;var Ub1=(Z,J={})=>new JQ(Z,J).makeRe();y4.makeRe=Ub1;var Lb1=(Z,J,$={})=>{let X=new JQ(J,$);if(Z=Z.filter((Y)=>X.match(Y)),X.options.nonull&&!Z.length)Z.push(J);return Z};y4.match=Lb1;var Un=/[?*]|[+@!]\(.*?\)|\[|\]/,Db1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class JQ{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(e3(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||_n,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)this.pattern=this.pattern.replace(/\\/g,"/");this.preserveMultipleSlashes=!!J.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!J.nonegate,this.comment=!1,this.empty=!1,this.partial=!!J.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=J.windowsNoMagicRoot!==void 0?J.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let Z of this.set)for(let J of Z)if(typeof J!=="string")return!0;return!1}debug(...Z){}make(){let Z=this.pattern,J=this.options;if(!J.nocomment&&Z.charAt(0)==="#"){this.comment=!0;return}if(!Z){this.empty=!0;return}if(this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],J.debug)this.debug=(...Y)=>console.error(...Y);this.debug(this.pattern,this.globSet);let $=this.globSet.map((Y)=>this.slashSplit(Y));this.globParts=this.preprocess($),this.debug(this.pattern,this.globParts);let X=this.globParts.map((Y,Q,W)=>{if(this.isWindows&&this.windowsNoMagicRoot){let K=Y[0]===""&&Y[1]===""&&(Y[2]==="?"||!Un.test(Y[2]))&&!Un.test(Y[3]),z=/^[a-z]:/i.test(Y[0]);if(K)return[...Y.slice(0,4),...Y.slice(4).map((G)=>this.parse(G))];else if(z)return[Y[0],...Y.slice(1).map((G)=>this.parse(G))]}return Y.map((K)=>this.parse(K))});if(this.debug(this.pattern,X),this.set=X.filter((Y)=>Y.indexOf(!1)===-1),this.isWindows)for(let Y=0;Y<this.set.length;Y++){let Q=this.set[Y];if(Q[0]===""&&Q[1]===""&&this.globParts[Y][2]==="?"&&typeof Q[3]==="string"&&/^[a-z]:$/i.test(Q[3]))Q[2]="?"}this.debug(this.pattern,this.set)}preprocess(Z){if(this.options.noglobstar){for(let $=0;$<Z.length;$++)for(let X=0;X<Z[$].length;X++)if(Z[$][X]==="**")Z[$][X]="*"}let{optimizationLevel:J=1}=this.options;if(J>=2)Z=this.firstPhasePreProcess(Z),Z=this.secondPhasePreProcess(Z);else if(J>=1)Z=this.levelOneOptimize(Z);else Z=this.adjascentGlobstarOptimize(Z);return Z}adjascentGlobstarOptimize(Z){return Z.map((J)=>{let $=-1;while(($=J.indexOf("**",$+1))!==-1){let X=$;while(J[X+1]==="**")X++;if(X!==$)J.splice($,X-$)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce(($,X)=>{let Y=$[$.length-1];if(X==="**"&&Y==="**")return $;if(X===".."){if(Y&&Y!==".."&&Y!=="."&&Y!=="**")return $.pop(),$}return $.push(X),$},[]),J.length===0?[""]:J})}levelTwoFileOptimize(Z){if(!Array.isArray(Z))Z=this.slashSplit(Z);let J=!1;do{if(J=!1,!this.preserveMultipleSlashes){for(let X=1;X<Z.length-1;X++){let Y=Z[X];if(X===1&&Y===""&&Z[0]==="")continue;if(Y==="."||Y==="")J=!0,Z.splice(X,1),X--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))J=!0,Z.pop()}let $=0;while(($=Z.indexOf("..",$+1))!==-1){let X=Z[$-1];if(X&&X!=="."&&X!==".."&&X!=="**")J=!0,Z.splice($-1,2),$-=2}}while(J);return Z.length===0?[""]:Z}firstPhasePreProcess(Z){let J=!1;do{J=!1;for(let $ of Z){let X=-1;while((X=$.indexOf("**",X+1))!==-1){let Q=X;while($[Q+1]==="**")Q++;if(Q>X)$.splice(X+1,Q-X);let W=$[X+1],K=$[X+2],z=$[X+3];if(W!=="..")continue;if(!K||K==="."||K===".."||!z||z==="."||z==="..")continue;J=!0,$.splice(X,1);let G=$.slice(0);G[X]="**",Z.push(G),X--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<$.length-1;Q++){let W=$[Q];if(Q===1&&W===""&&$[0]==="")continue;if(W==="."||W==="")J=!0,$.splice(Q,1),Q--}if($[0]==="."&&$.length===2&&($[1]==="."||$[1]===""))J=!0,$.pop()}let Y=0;while((Y=$.indexOf("..",Y+1))!==-1){let Q=$[Y-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let K=Y===1&&$[Y+1]==="**"?["."]:[];if($.splice(Y-1,2,...K),$.length===0)$.push("");Y-=2}}}}while(J);return Z}secondPhasePreProcess(Z){for(let J=0;J<Z.length-1;J++)for(let $=J+1;$<Z.length;$++){let X=this.partsMatch(Z[J],Z[$],!this.preserveMultipleSlashes);if(X){Z[J]=[],Z[$]=X;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,$=!1){let X=0,Y=0,Q=[],W="";while(X<Z.length&&Y<J.length)if(Z[X]===J[Y])Q.push(W==="b"?J[Y]:Z[X]),X++,Y++;else if($&&Z[X]==="**"&&J[Y]===Z[X+1])Q.push(Z[X]),X++;else if($&&J[Y]==="**"&&Z[X]===J[Y+1])Q.push(J[Y]),Y++;else if(Z[X]==="*"&&J[Y]&&(this.options.dot||!J[Y].startsWith("."))&&J[Y]!=="**"){if(W==="b")return!1;W="a",Q.push(Z[X]),X++,Y++}else if(J[Y]==="*"&&Z[X]&&(this.options.dot||!Z[X].startsWith("."))&&Z[X]!=="**"){if(W==="a")return!1;W="b",Q.push(J[Y]),X++,Y++}else return!1;return Z.length===J.length&&Q}parseNegate(){if(this.nonegate)return;let Z=this.pattern,J=!1,$=0;for(let X=0;X<Z.length&&Z.charAt(X)==="!";X++)J=!J,$++;if($)this.pattern=Z.slice($);this.negate=J}matchOne(Z,J,$=!1){let X=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),L=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),O=typeof J[0]==="string"&&/^[a-z]:$/i.test(J[0]),_=!O&&J[0]===""&&J[1]===""&&J[2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]),w=L?3:U?0:void 0,A=_?3:O?0:void 0;if(typeof w==="number"&&typeof A==="number"){let[j,T]=[Z[w],J[A]];if(j.toLowerCase()===T.toLowerCase()){if(J[A]=j,A>w)J=J.slice(A);else if(w>A)Z=Z.slice(w)}}}let{optimizationLevel:Y=1}=this.options;if(Y>=2)Z=this.levelTwoFileOptimize(Z);this.debug("matchOne",this,{file:Z,pattern:J}),this.debug("matchOne",Z.length,J.length);for(var Q=0,W=0,K=Z.length,z=J.length;Q<K&&W<z;Q++,W++){this.debug("matchOne loop");var G=J[W],H=Z[Q];if(this.debug(J,G,H),G===!1)return!1;if(G===V8){this.debug("GLOBSTAR",[J,G,H]);var V=Q,F=W+1;if(F===z){this.debug("** at the end");for(;Q<K;Q++)if(Z[Q]==="."||Z[Q]===".."||!X.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(V<K){var B=Z[V];if(this.debug(`
53
53
  globstar while`,Z,V,J,F,B),this.matchOne(Z.slice(V),J.slice(F),$))return this.debug("globstar found match!",V,K,B),!0;else{if(B==="."||B===".."||!X.dot&&B.charAt(0)==="."){this.debug("dot detected!",Z,V,J,F);break}this.debug("globstar swallow a segment, and continue"),V++}}if($){if(this.debug(`
54
- >>> no match, partial?`,Z,V,J,F),V===K)return!0}return!1}let U;if(typeof G==="string")U=H===G,this.debug("string match",G,H,U);else U=G.test(H),this.debug("pattern match",G,H,U);if(!U)return!1}if(Q===K&&W===z)return!0;else if(Q===K)return $;else if(W===z)return Q===K-1&&Z[Q]==="";else throw Error("wtf?")}braceExpand(){return wn(this.pattern,this.options)}parse(Z){e3(Z);let J=this.options;if(Z==="**")return V8;if(Z==="")return"";let $,X=null;if($=Z.match(ef1))X=J.dot?Jb1:Zb1;else if($=Z.match(cf1))X=(J.nocase?J.dot?nf1:if1:J.dot?pf1:lf1)($[1]);else if($=Z.match($b1))X=(J.nocase?J.dot?Yb1:Xb1:J.dot?Qb1:Wb1)($);else if($=Z.match(af1))X=J.dot?rf1:of1;else if($=Z.match(sf1))X=tf1;let Y=S4.fromGlob(Z,this.options).toMMPattern();if(X&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:X});return Y}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,$=J.noglobstar?Gb1:J.dot?Hb1:Vb1,X=new Set(J.nocase?["i"]:[]),Y=Z.map((K)=>{let z=K.map((G)=>{if(G instanceof RegExp)for(let H of G.flags.split(""))X.add(H);return typeof G==="string"?Db1(G):G===V8?V8:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==V8||F===V8)return;if(F===void 0)if(V!==void 0&&V!==V8)z[H+1]="(?:\\/|"+$+"\\/)?"+V;else z[H]=$;else if(V===void 0)z[H-1]=F+"(?:\\/|"+$+")?";else if(V!==V8)z[H-1]=F+"(?:\\/|\\/"+$+"\\/)"+V,z[H+1]=V8}),z.filter((G)=>G!==V8).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...X].join(""))}catch(K){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let $=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let X=this.slashSplit(Z);this.debug(this.pattern,"split",X);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=X[X.length-1];if(!Q)for(let W=X.length-2;!Q&&W>=0;W--)Q=X[W];for(let W=0;W<Y.length;W++){let K=Y[W],z=X;if($.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,J)){if($.flipNegate)return!0;return!this.negate}}if($.flipNegate)return!1;return this.negate}static defaults(Z){return y4.defaults(Z).Minimatch}}y4.AST=S4;y4.Minimatch=JQ;y4.escape=cD;y4.unescape=r7;var Tn="@fastify/otel",_b1="0.8.0",wb1=">=4.0.0 <6",Mn=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],L0={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},s7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},R9="anonymous",$6=Symbol("fastify otel instance"),t7=Symbol("fastify otel request spans"),$Q=Symbol("fastify otel request context"),jn=Symbol("fastify otel addhook original"),Nn=Symbol("fastify otel setnotfound original"),DG=Symbol("fastify otel ignore path");class lD extends Rn.InstrumentationBase{constructor(Z){super(Tn,_b1,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[DG]=null,this._logger=s0.diag.createComponentLogger({namespace:Tn}),Z?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let J=Z?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof J!=="string"||J.length===0)&&typeof J!=="function")throw TypeError("ignorePaths must be a string or a function");let $=y4;this[DG]=(X)=>{if(typeof J==="function")return J(X);else return $(X.url,J)}}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let Z=this.plugin();this._handleInitialization=(J)=>{J.fastify.register(Z)},An.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)An.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0;return super.disable()}init(){return[]}plugin(){let Z=this;return J[Symbol.for("skip-override")]=!0,J[Symbol.for("fastify.display-name")]="@fastify/otel",J[Symbol.for("plugin-meta")]={fastify:wb1,name:"@fastify/otel"},J;function J($,X,Y){$.decorate($6,Z),$.decorate(jn,$.addHook),$.decorate(Nn,$.setNotFoundHandler),$.decorateRequest("opentelemetry",function(){let V=this[$Q];return{span:this[t7],tracer:Z.tracer,context:V,inject:(B,U)=>{return s0.propagation.inject(V,B,U)},extract:(B,U)=>{return s0.propagation.extract(V,B,U)}}}),$.decorateRequest(t7,null),$.decorateRequest($Q,null),$.addHook("onRoute",function(H){if(Z[DG]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of Mn)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[L0.FASTIFY_TYPE]:s7.ROUTE,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:R9});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[L0.FASTIFY_TYPE]:s7.ROUTE,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:R9}));H[V]=B}}if(H.onSend!=null)H.onSend=Array.isArray(H.onSend)?[...H.onSend,Q]:[H.onSend,Q];else H.onSend=Q;if(H.onError!=null)H.onError=Array.isArray(H.onError)?[...H.onError,W]:[H.onError,W];else H.onError=W;H.handler=G(H.handler,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route-handler`,[L0.FASTIFY_TYPE]:s7.HANDLER,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:R9})}),$.addHook("onRequest",function(H,V,F){if(this[$6].isEnabled()===!1)return F();else if(this[$6][DG]?.({url:H.url,method:H.method})===!0)return this[$6]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=s0.context.active();if(s0.trace.getSpan(B)==null)B=s0.propagation.extract(B,H.headers);let U=OG.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===OG.RPCType.HTTP)U.route=H.routeOptions.url;let L=this[$6].tracer.startSpan("request",{attributes:{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.ROOT]:"@fastify/otel",[Y4.ATTR_HTTP_ROUTE]:H.url,[Y4.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[$Q]=s0.trace.setSpan(B,L),H[t7]=L,s0.context.with(H[$Q],()=>{F()})}),$.addHook("onResponse",function(H,V,F){let B=H[t7];if(B!=null)B.setStatus({code:s0.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[Y4.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[t7]=null,F()}),$.addHook=K,$.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[t7];if(U!=null){if(V.statusCode<500)U.setStatus({code:s0.SpanStatusCode.OK,message:"OK"});U.setAttributes({[Y4.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[t7]=null,B(null,F)}function W(H,V,F,B){let U=H[t7];if(U!=null)U.setStatus({code:s0.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[jn];if(Mn.includes(H))return F.call(this,H,G(V,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - ${H}`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:R9}));else return F.call(this,H,V)}function z(H,V){let F=this[Nn];if(typeof H==="function")V=G(H,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:R9}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:R9});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:R9});V=G(V,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:R9}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[$6],[L]=B;if(U.isEnabled()===!1)return H.call(this,...B);let O=L[$Q]??s0.context.active(),_=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??R9}`,{attributes:V},O);return s0.context.with(s0.trace.setSpan(O,_),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((A)=>{return _.end(),A},(A)=>{return _.setStatus({code:s0.SpanStatusCode.ERROR,message:A.message}),_.recordException(A),_.end(),Promise.reject(A)});return _.end(),w}catch(w){throw _.setStatus({code:s0.SpanStatusCode.ERROR,message:w.message}),_.recordException(w),_.end(),w}},this)}}}}}var Z5=v(u(),1),wG=v(N0(),1),AJ=v(D1(),1),In=v(X0(),1);var C9;(function(Z){Z.FASTIFY_NAME="fastify.name";let $="fastify.type";Z.FASTIFY_TYPE=$;let X="hook.name";Z.HOOK_NAME=X;let Y="plugin.name";Z.PLUGIN_NAME=Y})(C9||(C9={}));var XQ;(function(Z){Z.MIDDLEWARE="middleware";let $="request_handler";Z.REQUEST_HANDLER=$})(XQ||(XQ={}));var YQ;(function(Z){Z.MIDDLEWARE="middleware";let $="request handler";Z.REQUEST_HANDLER=$})(YQ||(YQ={}));var qn=v(u(),1);var QQ=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function pD(Z,J,$,X={}){let Y=J.startSpan($,{attributes:X}),Q=Z[QQ]||[];return Q.push(Y),Object.defineProperty(Z,QQ,{enumerable:!1,configurable:!0,value:Q}),Y}function _G(Z,J){let $=Z[QQ]||[];if(!$.length)return;$.forEach((X)=>{if(J)X.setStatus({code:qn.SpanStatusCode.ERROR,message:J.message}),X.recordException(J);X.end()}),delete Z[QQ]}function En(Z,J,$){let X,Y=void 0;try{if(Y=Z(),Cn(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){X=Q}finally{if(!Cn(Y)){if(J(X,Y),X)throw X}return Y}}function Cn(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var Ab1="0.1.0",Tb1="@sentry/instrumentation-fastify-v3",Pn="anonymous",Mb1=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class iD extends AJ.InstrumentationBase{constructor(Z={}){super(Tb1,Ab1,Z)}init(){return[new AJ.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_hookOnRequest(){let Z=this;return function($,X,Y){if(!Z.isEnabled())return Y();Z._wrap(X,"send",Z._patchSend());let Q=$,W=wG.getRPCMetadata(Z5.context.active()),K=Q.routeOptions?Q.routeOptions.url:$.routerPath;if(K&&W?.type===wG.RPCType.HTTP)W.route=K;let z=$.method||"GET";d1().setTransactionName(`${z} ${K}`),Y()}}_wrapHandler(Z,J,$,X){let Y=this;return this._diag.debug("Patching fastify route.handler function"),function(...Q){if(!Y.isEnabled())return $.apply(this,Q);let W=$.name||Z||Pn,K=`${YQ.MIDDLEWARE} - ${W}`,z=Q[1],G=pD(z,Y.tracer,K,{[C9.FASTIFY_TYPE]:XQ.MIDDLEWARE,[C9.PLUGIN_NAME]:Z,[C9.HOOK_NAME]:J}),H=X&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){_G(z),H.apply(this,V)};return Z5.context.with(Z5.trace.setSpan(Z5.context.active(),G),()=>{return En(()=>{return $.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:Z5.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!X)_G(z)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function(...X){let Y=X[0],Q=X[1],W=this.pluginName;if(!Mb1.has(Y))return J.apply(this,X);let K=typeof X[X.length-1]==="function"&&Q.constructor.name!=="AsyncFunction";return J.apply(this,[Y,Z._wrapHandler(W,Y,Q,K)])}}}_patchConstructor(Z){let J=this;function $(...X){let Y=Z.fastify.apply(this,X);return Y.addHook("onRequest",J._hookOnRequest()),Y.addHook("preHandler",J._hookPreHandler()),jb1(),J._wrap(Y,"addHook",J._wrapAddHook()),Y}if(Z.errorCodes!==void 0)$.errorCodes=Z.errorCodes;return $.fastify=$,$.default=$,$}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function($){return function(...Y){let Q=Y[0];if(!Z.isEnabled())return $.apply(this,Y);return AJ.safeExecuteInTheMiddle(()=>{return $.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;_G(this,W)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function($,X,Y){if(!Z.isEnabled())return Y();let Q=$,W=Q.routeOptions?.handler||Q.context?.handler,K=W?.name.startsWith("bound ")?W.name.substring(6):W?.name,z=`${YQ.REQUEST_HANDLER} - ${K||this.pluginName||Pn}`,G={[C9.PLUGIN_NAME]:this.pluginName,[C9.FASTIFY_TYPE]:XQ.REQUEST_HANDLER,[In.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:$.routerPath};if(K)G[C9.FASTIFY_NAME]=K;let H=pD(X,Z.tracer,z,G);Sn(H);let{requestHook:V}=Z.getConfig();if(V)AJ.safeExecuteInTheMiddle(()=>V(H,{request:$}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return Z5.context.with(Z5.trace.setSpan(Z5.context.active(),H),()=>{Y()})}}}function jb1(){let Z=p();if(Z)Z.on("spanStart",(J)=>{Sn(J)})}function Sn(Z){let J=X1(Z).data,$=J["fastify.type"];if(J[U1]||!$)return;Z.setAttributes({[W1]:"auto.http.otel.fastify",[U1]:`${$}.fastify`});let X=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof X==="string"){let Y=X.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(Y)}}var AG="Fastify",kn=s(`${AG}.v3`,()=>new iD);function Nb1(){let Z=p();if(!Z)return;else return Z.getIntegrationByName(AG)}function yn(Z,J,$,X){let Y=Nb1()?.getShouldHandleError()||hn;if(X==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&X==="onError-hook"){u0&&R.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}if(Y(Z,J,$))O1(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var xn=s(`${AG}.v5`,()=>{let Z=new lD,J=Z.plugin();return nD.subscribe("fastify.initialization",($)=>{let X=$.fastify;X?.register(J).after((Y)=>{if(Y)u0&&R.error("Failed to setup Fastify instrumentation",Y);else if(Cb1(),X)qb1(X)})}),nD.subscribe("tracing:fastify.request.handler:error",($)=>{let{error:X,request:Y,reply:Q}=$;yn.call(yn,X,Y,Q,"diagnostics-channel")}),Z}),Rb1=({shouldHandleError:Z})=>{let J;return{name:AG,setupOnce(){J=Z||hn,kn(),xn()},getShouldHandleError(){return J},setShouldHandleError($){J=$}}},vn=k((Z={})=>Rb1(Z));function hn(Z,J,$){let X=$.statusCode;return X>=500||X<=299}function fn(Z){let J=X1(Z),$=J.description,X=J.data,Y=X["fastify.type"],Q=Y==="hook",W=Y===$?.startsWith("handler -"),K=$==="request"||Y==="request-handler";if(X[U1]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[W1]:"auto.http.otel.fastify",[U1]:`${z}.fastify`});let G=X["fastify.name"]||X["plugin.name"]||X["hook.name"];if(typeof G==="string"){let H=G.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(H)}}function Cb1(){let Z=p();if(Z)Z.on("spanStart",(J)=>{fn(J)})}function qb1(Z){Z.addHook("onRequest",async(J,$)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)fn(Q)}let X=J.routeOptions?.url,Y=J.method||"GET";d1().setTransactionName(`${Y} ${X}`)})}var Ta=v(u(),1),Ma=v(Aa(),1);var ja="Graphql",Na=s(ja,Ma.GraphQLInstrumentation,(Z)=>{let J=Ca(Z);return{...J,responseHook($,X){if(Y0($,"auto.graphql.otel.graphql"),X.errors?.length&&!X1($).status)$.setStatus({code:Ta.SpanStatusCode.ERROR});let Q=X1($).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=g0($),H=X1(z).data[$X]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute($X,H);else if(typeof H==="string")z.setAttribute($X,[H,V]);else z.setAttribute($X,V);if(!X1(z).data["original-description"])z.setAttribute("original-description",X1(z).description);z.updateName(`${X1(z).data["original-description"]} (${Xg1(H)})`)}}}}),$g1=(Z={})=>{return{name:ja,setupOnce(){Na(Ca(Z))}}},Ra=k($g1);function Ca(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function Xg1(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}var oa=v(aa(),1);var ra="Kafka",sa=s(ra,()=>new oa.KafkaJsInstrumentation({consumerHook(Z){Y0(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){Y0(Z,"auto.kafkajs.otel.producer")}})),jg1=()=>{return{name:ra,setupOnce(){sa()}}},ta=k(jg1);var Ho=v(Go(),1);var Vo="LruMemoizer",Fo=s(Vo,()=>new Ho.LruMemoizerInstrumentation),qg1=()=>{return{name:Vo,setupOnce(){Fo()}}},Bo=k(qg1);var Io=v(Po(),1);var So="Mongo",yo=s(So,()=>new Io.MongoDBInstrumentation({dbStatementSerializer:cg1,responseHook(Z){Y0(Z,"auto.db.otel.mongo")}}));function cg1(Z){let J=WO(Z);return JSON.stringify(J)}function WO(Z){if(Array.isArray(Z))return Z.map((J)=>WO(J));if(lg1(Z)){let J={};return Object.entries(Z).map(([$,X])=>[$,WO(X)]).reduce(($,X)=>{if(ig1(X))$[X[0]]=X[1];return $},J)}return"?"}function lg1(Z){return typeof Z==="object"&&Z!==null&&!pg1(Z)}function pg1(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function ig1(Z){return Array.isArray(Z)}var ng1=()=>{return{name:So,setupOnce(){yo()}}},ko=k(ng1);var Zr=v(eo(),1);var Jr="Mongoose",$r=s(Jr,()=>new Zr.MongooseInstrumentation({responseHook(Z){Y0(Z,"auto.db.otel.mongoose")}})),Um1=()=>{return{name:Jr,setupOnce(){$r()}}},Xr=k(Um1);var Ar=v(wr(),1);var Tr="Mysql",Mr=s(Tr,()=>new Ar.MySQLInstrumentation({})),gm1=()=>{return{name:Tr,setupOnce(){Mr()}}},jr=k(gm1);var dr=v(ur(),1);var cr="Mysql2",lr=s(cr,()=>new dr.MySQL2Instrumentation({responseHook(Z){Y0(Z,"auto.db.otel.mysql2")}})),Bu1=()=>{return{name:cr,setupOnce(){lr()}}},pr=k(Bu1);var ls=v(Hs(),1),ps=v(gs(),1);var ou1=["get","set","setex"],EO=["get","mget"],ru1=["set","setex"];function LQ(Z,J){return Z.includes(J.toLowerCase())}function PO(Z){if(LQ(EO,Z))return"cache.get";else if(LQ(ru1,Z))return"cache.put";else return}function su1(Z,J){return J.some(($)=>Z.startsWith($))}function us(Z,J){try{if(J.length===0)return;let $=(Y)=>{if(typeof Y==="string"||typeof Y==="number"||Buffer.isBuffer(Y))return[Y.toString()];else if(Array.isArray(Y))return ms(Y.map((Q)=>$(Q)));else return["<unknown>"]},X=J[0];if(LQ(ou1,Z)&&X!=null)return $(X);return ms(J.map((Y)=>$(Y)))}catch{return}}function ds(Z,J,$){if(!PO(Z))return!1;for(let X of J)if(su1(X,$))return!0;return!1}function cs(Z){let J=($)=>{try{if(Buffer.isBuffer($))return $.byteLength;else if(typeof $==="string")return $.length;else if(typeof $==="number")return $.toString().length;else if($===null||$===void 0)return 0;return JSON.stringify($).length}catch{return}};return Array.isArray(Z)?Z.reduce(($,X)=>{let Y=J(X);return typeof Y==="number"?$!==void 0?$+Y:Y:$},0):J(Z)}function ms(Z){let J=[],$=(X)=>{X.forEach((Y)=>{if(Array.isArray(Y))$(Y);else J.push(Y)})};return $(Z),J}var vG="Redis",DQ={},is=(Z,J,$,X)=>{Z.setAttribute(W1,"auto.db.otel.redis");let Y=us(J,$),Q=PO(J);if(!Y||!Q||!DQ.cachePrefixes||!ds(J,Y,DQ.cachePrefixes))return;let W=X1(Z).data["net.peer.name"],K=X1(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=cs(X);if(z)Z.setAttribute(wL,z);if(LQ(EO,J)&&z!==void 0)Z.setAttribute(OL,z>0);Z.setAttributes({[U1]:Q,[_L]:Y});let G=Y.join(", ");Z.updateName(DQ.maxCacheKeyLength?M7(G,DQ.maxCacheKeyLength):G)},tu1=s(`${vG}.IORedis`,()=>{return new ls.IORedisInstrumentation({responseHook:is})}),eu1=s(`${vG}.Redis`,()=>{return new ps.RedisInstrumentation({responseHook:is})}),ns=Object.assign(()=>{tu1(),eu1()},{id:vG}),Zd1=(Z={})=>{return{name:vG,setupOnce(){DQ=Z,ns()}}},as=k(Zd1);var Nt=v(jt(),1);var Rt="Postgres",Ct=s(Rt,()=>new Nt.PgInstrumentation({requireParentSpan:!0,requestHook(Z){Y0(Z,"auto.db.otel.postgres")}})),id1=()=>{return{name:Rt,setupOnce(){Ct()}}},qt=k(id1);var jX=v(u(),1),I9=v(D1(),1),t0=v(X0(),1);var dG="PostgresJs",Et=[">=3.0.0 <4"],nd1=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,uG=Symbol("sentryPostgresConnectionContext"),hO=Symbol.for("sentry.instrumented.postgresjs"),Pt=Symbol.for("sentry.query.from.instrumented.sql"),It=s(dG,(Z)=>new St({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class St extends I9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",u1,Z)}init(){let Z=new I9.InstrumentationNodeModuleDefinition("postgres",Et,(J)=>{try{return this._patchPostgres(J)}catch($){return u0&&R.error("Failed to patch postgres module:",$),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new I9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,Et,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",$=J?Z:Z.default;if(typeof $!=="function")return u0&&R.warn("postgres module does not export a function. Skipping instrumentation."),Z;let X=this,Y=function(...Q){let W=Reflect.construct($,Q);if(!W||typeof W!=="function")return u0&&R.warn("postgres() did not return a valid instance"),W;return X._instrumentSqlInstance(W)};Object.setPrototypeOf(Y,$),Object.setPrototypeOf(Y.prototype,$.prototype);for(let Q of Object.getOwnPropertyNames($))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor($,Q);if(W)Object.defineProperty(Y,Q,W)}if(J)return Y;else return q3(Z,"default",Y),Z}_wrapQueryMethod(Z,J,$){let X=this;return function(...Y){let Q=Reflect.apply(Z,J,Y);if(Q&&typeof Q==="object"&&"handle"in Q)X._wrapSingleQueryHandle(Q,$);return Q}}_wrapCallbackMethod(Z,J,$){let X=this;return function(...Y){let Q=$[uG];if(typeof Y[Y.length-1]!=="function"){let H=Reflect.apply(Z,J,Y);if(H&&typeof H.then==="function")return H.then((V)=>{return X._instrumentSqlInstance(V,Q)});return H}let K=Y.length===1?Y[0]:Y[1],z=function(H){let V=X._instrumentSqlInstance(H,Q);return K(V)},G=Y.length===1?[z]:[Y[0],z];return Reflect.apply(Z,J,G)}}_setConnectionAttributes(Z,J){if(!J)return;if(J.ATTR_DB_NAMESPACE)Z.setAttribute(t0.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(t0.ATTR_SERVER_ADDRESS,J.ATTR_SERVER_ADDRESS);if(J.ATTR_SERVER_PORT!==void 0){let $=parseInt(J.ATTR_SERVER_PORT,10);if(!isNaN($))Z.setAttribute(t0.ATTR_SERVER_PORT,$)}}_setOperationName(Z,J,$){if($){Z.setAttribute(t0.ATTR_DB_OPERATION_NAME,$);return}let X=J?.match(nd1);if(X?.[1])Z.setAttribute(t0.ATTR_DB_OPERATION_NAME,X[1].toUpperCase())}_attachConnectionContext(Z,J){let $=Z;if(!$.options||typeof $.options!=="object")return;let X=$.options,Y=X.host?.[0]||"localhost",Q=X.port?.[0]||5432,W={ATTR_DB_NAMESPACE:typeof X.database==="string"&&X.database!==""?X.database:void 0,ATTR_SERVER_ADDRESS:Y,ATTR_SERVER_PORT:String(Q)};J[uG]=W}_instrumentSqlInstance(Z,J){if(Z[hO])return Z;let $=this,X=new Proxy(Z,{apply(Y,Q,W){let K=Reflect.apply(Y,Q,W);if(K&&typeof K==="object"&&"handle"in K)$._wrapSingleQueryHandle(K,X);return K},get(Y,Q){let W=Y[Q];if(typeof Q!=="string"||typeof W!=="function")return W;if(Q==="unsafe"||Q==="file")return $._wrapQueryMethod(W,Y,X);if(Q==="begin"||Q==="reserve")return $._wrapCallbackMethod(W,Y,X);return W}});if(J)X[uG]=J;else this._attachConnectionContext(Z,X);return Z[hO]=!0,X[hO]=!0,X}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Pt]=!0;let $=Z.handle,X=this,Y=async function(...Q){if(!X._shouldCreateSpans())return $.apply(this,Q);let W=X._reconstructQuery(Z.strings),K=X._sanitizeSqlQuery(W);return P4({name:K||"postgresjs.query",op:"db"},(z)=>{Y0(z,"auto.db.postgresjs"),z.setAttributes({[t0.ATTR_DB_SYSTEM_NAME]:"postgres",[t0.ATTR_DB_QUERY_TEXT]:K});let G=J?J[uG]:void 0;X._setConnectionAttributes(z,G);let H=X.getConfig(),{requestHook:V}=H;if(V)I9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),u0&&R.error(`Error in requestHook for ${dG} integration:`,B)},!0);let F=this;F.resolve=new Proxy(F.resolve,{apply:(B,U,L)=>{try{X._setOperationName(z,K,L?.[0]?.command),z.end()}catch(O){u0&&R.error("Error ending span in resolve callback:",O)}return Reflect.apply(B,U,L)}}),F.reject=new Proxy(F.reject,{apply:(B,U,L)=>{try{z.setStatus({code:v1,message:L?.[0]?.message||"unknown_error"}),z.setAttribute(t0.ATTR_DB_RESPONSE_STATUS_CODE,L?.[0]?.code||"unknown"),z.setAttribute(t0.ATTR_ERROR_TYPE,L?.[0]?.name||"unknown"),X._setOperationName(z,K),z.end()}catch(O){u0&&R.error("Error ending span in reject callback:",O)}return Reflect.apply(B,U,L)}});try{return $.apply(this,Q)}catch(B){throw z.setStatus({code:v1,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return jX.trace.getSpan(jX.context.active())!==void 0||!Z.requireParentSpan}_reconstructQuery(Z){if(!Z?.length)return;if(Z.length===1)return Z[0]||void 0;return Z.reduce((J,$,X)=>X===0?$:`${J}$${X}${$}`,"")}_sanitizeSqlQuery(Z){if(!Z)return"Unknown SQL Query";return Z.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\s+/g," ").trim().replace(/\bX'[0-9A-Fa-f]*'/gi,"?").replace(/\bB'[01]*'/gi,"?").replace(/'(?:[^']|'')*'/g,"?").replace(/\b0x[0-9A-Fa-f]+/gi,"?").replace(/\b(?:TRUE|FALSE)\b/gi,"?").replace(/-?\b\d+\.?\d*[eE][+-]?\d+\b/g,"?").replace(/-?\b\d+\.\d+\b/g,"?").replace(/-?\.\d+\b/g,"?").replace(/(?<!\$)-?\b\d+\b/g,"?").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/gi,"IN (?)").replace(/\bIN\b\s*\(\s*\$\d+(?:\s*,\s*\$\d+)*\s*\)/gi,"IN ($?)")}_patchQueryPrototype(Z){let J=this,$=Z.Query.prototype.handle;return Z.Query.prototype.handle=async function(...X){if(this[Pt])return $.apply(this,X);if(!J._shouldCreateSpans())return $.apply(this,X);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return P4({name:Q||"postgresjs.query",op:"db"},(W)=>{Y0(W,"auto.db.postgresjs"),W.setAttributes({[t0.ATTR_DB_SYSTEM_NAME]:"postgres",[t0.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)I9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),u0&&R.error(`Error in requestHook for ${dG} integration:`,V)},!0);let G=this.resolve;this.resolve=new Proxy(G,{apply:(V,F,B)=>{try{J._setOperationName(W,Q,B?.[0]?.command),W.end()}catch(U){u0&&R.error("Error ending span in resolve callback:",U)}return Reflect.apply(V,F,B)}});let H=this.reject;this.reject=new Proxy(H,{apply:(V,F,B)=>{try{W.setStatus({code:v1,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(t0.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(t0.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){u0&&R.error("Error ending span in reject callback:",U)}return Reflect.apply(V,F,B)}});try{return $.apply(this,X)}catch(V){throw W.setStatus({code:v1,message:V instanceof Error?V.message:"unknown_error"}),W.end(),V}})},Z.Query.prototype.handle.__sentry_original__=$,Z}_unpatchQueryPrototype(Z){if(Z.Query.prototype.handle.__sentry_original__)Z.Query.prototype.handle=Z.Query.prototype.handle.__sentry_original__;return Z}}var ad1=(Z)=>{return{name:dG,setupOnce(){It(Z)}}},yt=k(ad1);var O8=v(u(),1);var vt=v(u(),1),cG=v(D1(),1),XZ=v(u(),1);var od1=process.env.PRISMA_SHOW_ALL_TRACES==="true",rd1="00-10-10-00";function sd1(Z){switch(Z){case"client":return XZ.SpanKind.CLIENT;case"internal":default:return XZ.SpanKind.INTERNAL}}var td1=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=XZ.trace.getSpanContext(Z??XZ.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return rd1}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),$=new Map,X=Z.filter((Y)=>Y.parentId===null);for(let Y of X)ht(J,Y,Z,$,this.ignoreSpanTypes)}getActiveContext(){return XZ.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!od1)return J();let $=this.tracerProvider.getTracer("prisma"),X=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(ft(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=$.startSpan(Y,Z,X);return kt(Q,J(Q,X))}return $.startActiveSpan(Y,Z,(Q)=>kt(Q,J(Q,X)))}};function ht(Z,J,$,X,Y){if(ft(J.name,Y))return;let Q={attributes:J.attributes,kind:sd1(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(W)=>{if(X.set(J.id,W.spanContext().spanId),J.links)W.addLinks(J.links.flatMap((z)=>{let G=X.get(z);if(!G)return[];return{context:{spanId:G,traceId:W.spanContext().traceId,traceFlags:W.spanContext().traceFlags}}}));let K=$.filter((z)=>z.parentId===J.id);for(let z of K)ht(Z,z,$,X,Y);W.end(J.endTime)})}function kt(Z,J){if(ed1(J))return J.then(($)=>{return Z.end(),$},($)=>{throw Z.end(),$});return Z.end(),J}function ed1(Z){return Z!=null&&typeof Z.then==="function"}function ft(Z,J){return J.some(($)=>typeof $==="string"?$===Z:$.test(Z))}var bt={name:"@prisma/instrumentation",version:"6.19.0",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":">=0.52.0 <1"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"vitest run"},sideEffects:!1},bO=bt.version,Zc1=bO.split(".")[0],xt="PRISMA_INSTRUMENTATION",fO=`V${Zc1}_PRISMA_INSTRUMENTATION`,Jc1=bt.name,$c1="@prisma/client",gt=class extends cG.InstrumentationBase{tracerProvider;constructor(Z={}){super(Jc1,bO,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new cG.InstrumentationNodeModuleDefinition($c1,[bO])]}enable(){let Z=this._config,J={helper:new td1({tracerProvider:this.tracerProvider??vt.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[xt]=J,global[fO]=J}disable(){delete global[xt],delete global[fO]}isEnabled(){return Boolean(global[fO])}};var mt="Prisma";function Xc1(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function ut(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class dt extends gt{constructor(){super()}enable(){super.enable();let Z=ut();if(Xc1(Z))Z.createEngineSpan=(J)=>{let $=O8.trace.getTracer("prismaV5Compatibility"),X=$._idGenerator;if(!X){o0(()=>{console.warn("[Sentry] Could not find _idGenerator on tracer, skipping Prisma v5 compatibility - some Prisma spans may be missing!")});return}try{J.spans.forEach((Y)=>{let Q=Yc1(Y.kind),W=Y.parent_span_id,K=Y.span_id,z=Y.trace_id,G=Y.links?.map((V)=>{return{context:{traceId:V.trace_id,spanId:V.span_id,traceFlags:O8.TraceFlags.SAMPLED}}}),H=O8.trace.setSpanContext(O8.context.active(),{traceId:z,spanId:W,traceFlags:O8.TraceFlags.SAMPLED});O8.context.with(H,()=>{let V={generateTraceId:()=>{return z},generateSpanId:()=>{return K}};$._idGenerator=V,$.startSpan(Y.name,{kind:Q,links:G,startTime:Y.start_time,attributes:Y.attributes}).end(Y.end_time),$._idGenerator=X})})}finally{$._idGenerator=X}}}}function Yc1(Z){switch(Z){case"client":return O8.SpanKind.CLIENT;case"internal":default:return O8.SpanKind.INTERNAL}}var Qc1=s(mt,(Z)=>{return new dt}),ct=k((Z)=>{return{name:mt,setupOnce(){Qc1()},setup(J){if(!ut())return;J.on("spanStart",($)=>{let X=X1($);if(X.description?.startsWith("prisma:"))$.setAttribute(W1,"auto.db.otel.prisma");if(X.description==="prisma:engine:db_query"&&X.data["db.query.text"])$.updateName(X.data["db.query.text"]);if(X.description==="prisma:engine:db_query"&&!X.data["db.system"])$.setAttribute("db.system","prisma")})}}});var Ve=v(He(),1);var Fe="Hapi",Be=s(Fe,()=>new Ve.HapiInstrumentation),Pc1=()=>{return{name:Fe,setupOnce(){Be()}}},Ue=k(Pc1);var iG=v(X0(),1);var QZ={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},TQ={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var jJ=v(u(),1),pG=v(D1(),1);var Ic1="@sentry/instrumentation-hono",Sc1="0.0.1";class cO extends pG.InstrumentationBase{constructor(Z={}){super(Ic1,Sc1,Z)}init(){return[new pG.InstrumentationNodeModuleDefinition("hono",[">=4.0.0 <5"],(Z)=>this._patch(Z))]}_patch(Z){let J=this;class $ extends Z.Hono{constructor(...X){super(...X);J._wrap(this,"get",J._patchHandler()),J._wrap(this,"post",J._patchHandler()),J._wrap(this,"put",J._patchHandler()),J._wrap(this,"delete",J._patchHandler()),J._wrap(this,"options",J._patchHandler()),J._wrap(this,"patch",J._patchHandler()),J._wrap(this,"all",J._patchHandler()),J._wrap(this,"on",J._patchOnHandler()),J._wrap(this,"use",J._patchMiddlewareHandler())}}try{Z.Hono=$}catch{return{...Z,Hono:$}}return Z}_patchHandler(){let Z=this;return function(J){return function(...X){if(typeof X[0]==="string"){let Y=X[0];if(X.length===1)return J.apply(this,[Y]);let Q=X.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,X.map((Y)=>Z._wrapHandler(Y)))}}}_patchOnHandler(){let Z=this;return function(J){return function(...X){let Y=X.slice(2);return J.apply(this,[...X.slice(0,2),...Y.map((Q)=>Z._wrapHandler(Q))])}}}_patchMiddlewareHandler(){let Z=this;return function(J){return function(...X){if(typeof X[0]==="string"){let Y=X[0];if(X.length===1)return J.apply(this,[Y]);let Q=X.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,X.map((Y)=>Z._wrapHandler(Y)))}}}_wrapHandler(Z){let J=this;return function($,X){if(!J.isEnabled())return Z.apply(this,[$,X]);let Y=$.req.path,Q=J.tracer.startSpan(Y);return jJ.context.with(jJ.trace.setSpan(jJ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[$,X]);if(t4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[QZ.HONO_TYPE]:z,[QZ.HONO_NAME]:z===TQ.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[QZ.HONO_TYPE]:K,[QZ.HONO_NAME]:K===TQ.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),W}},()=>Q.end(),(W)=>{J._handleError(Q,W),Q.end()})})}}_safeExecute(Z,J,$){try{let X=Z();if(t4(X))X.then(()=>J(),(Y)=>$(Y));else J();return X}catch(X){throw $(X),X}}_determineHandlerType(Z){return Z===void 0?TQ.MIDDLEWARE:TQ.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:jJ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var Le="Hono";function yc1(Z){let J=X1(Z).data,$=J[QZ.HONO_TYPE];if(J[U1]||!$)return;Z.setAttributes({[W1]:"auto.http.otel.hono",[U1]:`${$}.hono`});let X=J[QZ.HONO_NAME];if(typeof X==="string")Z.updateName(X);if(d1()===y6()){u0&&R.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[iG.ATTR_HTTP_ROUTE],Q=J[iG.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")d1().setTransactionName(`${Q} ${Y}`)}var De=s(Le,()=>new cO({responseHook:(Z)=>{yc1(Z)}})),kc1=()=>{return{name:Le,setupOnce(){De()}}},Oe=k(kc1);var me=v(ge(),1),ue=v(X0(),1);var de="Koa",ce=s(de,me.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,$){Y0(J,"auto.http.otel.koa");let X=X1(J).data,Y=X["koa.type"];if(Y)J.setAttribute(U1,`${Y}.koa`);let Q=X["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(d1()===y6()){u0&&R.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=X[ue.ATTR_HTTP_ROUTE],K=$.context?.request?.method?.toUpperCase()||"GET";if(W)d1().setTransactionName(`${K} ${W}`)}}}),pc1=(Z={})=>{return{name:de,setupOnce(){ce(Z)}}},le=k(pc1);var V11=v(H11(),1);var F11="Connect",B11=s(F11,()=>new V11.ConnectInstrumentation),Ql1=()=>{return{name:F11,setupOnce(){B11()}}},U11=k(Ql1);var y11=v(S11(),1);var Al1=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),k11="Tedious",x11=s(k11,()=>new y11.TediousInstrumentation({})),Tl1=()=>{let Z;return{name:k11,setupOnce(){let J=x11();Z=i3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let{description:X,data:Y}=X1($);if(!X||Y["db.system"]!=="mssql")return;let Q=X.split(" ")[0]||"";if(Al1.has(Q))$.setAttribute(W1,"auto.db.otel.tedious")}))}}},v11=k(Tl1);var p11=v(l11(),1);var i11="GenericPool",n11=s(i11,()=>new p11.GenericPoolInstrumentation({})),Rl1=()=>{let Z;return{name:i11,setupOnce(){let J=n11();Z=i3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let Y=X1($).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")$.setAttribute(W1,"auto.db.otel.generic_pool")}))}}},a11=k(Rl1);var _01=v(O01(),1);var w01="Amqplib",Qp1={consumeEndHook:(Z)=>{Y0(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{Y0(Z,"auto.amqplib.otel.publisher")}},A01=s(w01,()=>new _01.AmqplibInstrumentation(Qp1)),Wp1=()=>{return{name:w01,setupOnce(){A01()}}},T01=k(Wp1);var CQ="VercelAI";var JH=v(D1(),1);var Kp1=[">=3.0.0 <7"],M01=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function zp1(Z){if(typeof Z!=="object"||Z===null)return!1;let J=Z;return"type"in J&&"error"in J&&"toolName"in J&&"toolCallId"in J&&J.type==="tool-error"&&J.error instanceof Error}function Gp1(Z){if(typeof Z!=="object"||Z===null||!("content"in Z))return;let J=Z;if(!Array.isArray(J.content))return;for(let $ of J.content)if(zp1($)){let X=F2($.toolCallId);if(X){let Y=X.spanContext();D6((Q)=>{Q.setContext("trace",{trace_id:Y.traceId,span_id:Y.spanId}),Q.setTag("vercel.ai.tool.name",$.toolName),Q.setTag("vercel.ai.tool.callId",$.toolCallId),Q.setLevel("error"),O1($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),B2($.toolCallId)}else D6((Y)=>{Y.setTag("vercel.ai.tool.name",$.toolName),Y.setTag("vercel.ai.tool.callId",$.toolCallId),Y.setLevel("error"),O1($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function Hp1(Z,J,$,X){let Y=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:$===!0?!0:X,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:$===!0?!0:X;return{recordInputs:Y,recordOutputs:Q}}class qQ extends JH.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",u1,Z);qQ.prototype.__init.call(this),qQ.prototype.__init2.call(this)}init(){return new JH.InstrumentationNodeModuleDefinition("ai",Kp1,this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach(($)=>$()),this._callbacks=[];let J=($)=>{return new Proxy($,{apply:(X,Y,Q)=>{let W=Q[0].experimental_telemetry||{},K=W.isEnabled,z=p(),G=z?.getIntegrationByName(CQ),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=Hp1(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},k6(()=>Reflect.apply(X,Y,Q),(U)=>{if(U&&typeof U==="object")Z4(U,"_sentry_active_span",M5())},()=>{},(U)=>{Gp1(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let $ of M01)Z[$]=J(Z[$]);return Z}else{let $=M01.reduce((X,Y)=>{return X[Y]=J(Z[Y]),X},{});return{...Z,...$}}}}var j01=s(CQ,()=>new qQ({}));function Vp1(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var Fp1=(Z={})=>{let J;return{name:CQ,options:Z,setupOnce(){J=j01()},afterAllSetup($){if(Z.force??Vp1($))jz($);else J?.callWhenPatched(()=>jz($))}}},N01=k(Fp1);var $H=v(D1(),1);var Bp1=[">=4.0.0 <7"];class z_ extends $H.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",u1,Z)}init(){return new $H.InstrumentationNodeModuleDefinition("openai",Bp1,this._patch.bind(this))}_patch(Z){let J=Z;return J=this._patchClient(J,"OpenAI"),J=this._patchClient(J,"AzureOpenAI"),J}_patchClient(Z,J){let $=Z[J];if(!$)return Z;let X=this.getConfig(),Y=function(...Q){if(KJ(c7))return Reflect.construct($,Q);let W=Reflect.construct($,Q),K=p(),z=Boolean(K?.getOptions().sendDefaultPii),G=X.recordInputs??z,H=X.recordOutputs??z;return Cz(W,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(Y,$),Object.setPrototypeOf(Y.prototype,$.prototype);for(let Q of Object.getOwnPropertyNames($))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor($,Q);if(W)Object.defineProperty(Y,Q,W)}try{Z[J]=Y}catch(Q){Object.defineProperty(Z,J,{value:Y,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===$)try{Z.default=Y}catch(Q){Object.defineProperty(Z,"default",{value:Y,writable:!0,configurable:!0,enumerable:!0})}return Z}}var R01=s(c7,(Z)=>new z_(Z)),Up1=(Z={})=>{return{name:c7,setupOnce(){R01(Z)}}},C01=k(Up1);var XH=v(D1(),1);var Lp1=[">=0.19.2 <1.0.0"];class G_ extends XH.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",u1,Z)}init(){return new XH.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",Lp1,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,$=this.getConfig(),X=function(...Y){if(KJ(l7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=p(),K=Boolean(W?.getOptions().sendDefaultPii),z=$.recordInputs??K,G=$.recordOutputs??K;return D2(Q,{recordInputs:z,recordOutputs:G})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let Q=Object.getOwnPropertyDescriptor(J,Y);if(Q)Object.defineProperty(X,Y,Q)}try{Z.Anthropic=X}catch(Y){Object.defineProperty(Z,"Anthropic",{value:X,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===J)try{Z.default=X}catch(Y){Object.defineProperty(Z,"default",{value:X,writable:!0,configurable:!0,enumerable:!0})}return Z}}var q01=s(l7,(Z)=>new G_(Z)),Dp1=(Z={})=>{return{name:l7,options:Z,setupOnce(){q01(Z)}}},E01=k(Dp1);var EX=v(D1(),1);var P01=[">=0.10.0 <2"];class H_ extends EX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",u1,Z)}init(){return new EX.InstrumentationNodeModuleDefinition("@google/genai",P01,(J)=>this._patch(J),(J)=>J,[new EX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",P01,(J)=>this._patch(J),(J)=>J)])}_patch(Z){let J=Z.GoogleGenAI,$=this.getConfig();if(typeof J!=="function")return Z;let X=function(...Y){if(KJ(p7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=p(),K=Boolean(W?.getOptions().sendDefaultPii),z=$,G=z?.recordInputs??K,H=z?.recordOutputs??K;return A2(Q,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let Q=Object.getOwnPropertyDescriptor(J,Y);if(Q)Object.defineProperty(X,Y,Q)}return q3(Z,"GoogleGenAI",X),Z}}var I01=s(p7,(Z)=>new H_(Z)),Op1=(Z={})=>{return{name:p7,setupOnce(){I01(Z)}}},S01=k(Op1);var zZ=v(D1(),1);var YH=[">=0.1.0 <2.0.0"];function _p1(Z,J){if(!Z)return[J];if(Array.isArray(Z)){if(Z.includes(J))return Z;return[...Z,J]}if(typeof Z==="object")return[Z,J];return Z}function wp1(Z,J,$){return new Proxy(Z,{apply(X,Y,Q){let K=Q[1];if(!K||typeof K!=="object"||Array.isArray(K))K={},Q[1]=K;let z=K.callbacks,G=_p1(z,J);return K.callbacks=G,Reflect.apply(X,Y,Q)}})}class V_ extends zZ.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",u1,Z)}init(){let Z=[],J=["@langchain/anthropic","@langchain/openai","@langchain/google-genai","@langchain/mistralai","@langchain/google-vertexai","@langchain/groq"];for(let $ of J)Z.push(new zZ.InstrumentationNodeModuleDefinition($,YH,this._patch.bind(this),(X)=>X,[new zZ.InstrumentationNodeModuleFile(`${$}/dist/index.cjs`,YH,this._patch.bind(this),(X)=>X)]));return Z.push(new zZ.InstrumentationNodeModuleDefinition("langchain",YH,this._patch.bind(this),($)=>$,[new zZ.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",YH,this._patch.bind(this),($)=>$)])),Z}_patch(Z){iL([c7,l7,p7]);let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X?.recordInputs??$,Q=X?.recordOutputs??$,W=Ez({recordInputs:Y,recordOutputs:Q});return this._patchRunnableMethods(Z,W),Z}_patchRunnableMethods(Z,J){let $=["ChatAnthropic","ChatOpenAI","ChatGoogleGenerativeAI","ChatMistralAI","ChatVertexAI","ChatGroq","ConfigurableModel"],X=Z.universal_exports??Z,Y=Object.values(X).find((K)=>{return typeof K==="function"&&$.includes(K.name)});if(!Y)return;let Q=Y.prototype,W=["invoke","stream","batch"];for(let K of W){let z=Q[K];if(typeof z==="function")Q[K]=wp1(z,J)}}}var y01=s(qz,(Z)=>new V_(Z)),Ap1=(Z={})=>{return{name:qz,setupOnce(){y01(Z)}}},k01=k(Ap1);var PX=v(D1(),1);var x01=[">=0.0.0 <2.0.0"];class F_ extends PX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",u1,Z)}init(){return new PX.InstrumentationNodeModuleDefinition("@langchain/langgraph",x01,this._patch.bind(this),(J)=>J,[new PX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",x01,this._patch.bind(this),(J)=>J)])}_patch(Z){let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X.recordInputs??$,Q=X.recordOutputs??$,W={recordInputs:Y,recordOutputs:Q};if(Z.StateGraph&&typeof Z.StateGraph==="function"){let K=Z.StateGraph;K.prototype.compile=j2(K.prototype.compile,W)}return Z}}var v01=s(Pz,(Z)=>new F_(Z)),Tp1=(Z={})=>{return{name:Pz,setupOnce(){v01(Z)}}},h01=k(Tp1);var l01=v(D1(),1);var y9=v(u(),1),k9=v(D1(),1),_8=v(X0(),1);import*as b01 from"net";function g01(Z,J,$,X,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{k9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;y9.diag.error(V?.message)},!0)};let z=new k9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>f01(H,$,X,Z,W)),G=["@firebase/firestore/dist/lite/index.node.cjs.js","@firebase/firestore/dist/lite/index.node.mjs.js","@firebase/firestore/dist/lite/index.rn.esm2017.js","@firebase/firestore/dist/lite/index.cjs.js"];for(let H of G)z.files.push(new k9.InstrumentationNodeModuleFile(H,J,(V)=>f01(V,$,X,Z,W),(V)=>m01(V,X)));return z}function f01(Z,J,$,X,Y){return m01(Z,$),J(Z,"addDoc",Mp1(X,Y)),J(Z,"getDocs",Np1(X,Y)),J(Z,"setDoc",Rp1(X,Y)),J(Z,"deleteDoc",jp1(X,Y)),Z}function m01(Z,J){for(let $ of["addDoc","getDocs","setDoc","deleteDoc"])if(k9.isWrapped(Z[$]))J(Z,$);return Z}function Mp1(Z,J){return function(X){return function(Y,Q){let W=WH(Z,"addDoc",Y);return J(W),QH(W,()=>{return X(Y,Q)})}}}function jp1(Z,J){return function(X){return function(Y){let Q=WH(Z,"deleteDoc",Y.parent||Y);return J(Q),QH(Q,()=>{return X(Y)})}}}function Np1(Z,J){return function(X){return function(Y){let Q=WH(Z,"getDocs",Y);return J(Q),QH(Q,()=>{return X(Y)})}}}function Rp1(Z,J){return function(X){return function(Y,Q,W){let K=WH(Z,"setDoc",Y.parent||Y);return J(K),QH(K,()=>{return typeof W<"u"?X(Y,Q,W):X(Y,Q)})}}}function QH(Z,J){return y9.context.with(y9.trace.setSpan(y9.context.active(),Z),()=>{return k9.safeExecuteInTheMiddle(()=>{return J()},($)=>{if($)Z.recordException($);Z.end()},!0)})}function WH(Z,J,$){let X=Z.startSpan(`${J} ${$.path}`,{kind:y9.SpanKind.CLIENT});return qp1(X,$),X.setAttribute(_8.ATTR_DB_OPERATION_NAME,J),X}function Cp1(Z){let J,$;if(typeof Z.host==="string")if(Z.host.startsWith("[")){if(Z.host.endsWith("]"))J=Z.host.replace(/^\[|\]$/g,"");else if(Z.host.includes("]:")){let X=Z.host.lastIndexOf(":");if(X!==-1)J=Z.host.slice(1,X).replace(/^\[|\]$/g,""),$=Z.host.slice(X+1)}}else if(b01.isIPv6(Z.host))J=Z.host;else{let X=Z.host.lastIndexOf(":");if(X!==-1)J=Z.host.slice(0,X),$=Z.host.slice(X+1);else J=Z.host}return{address:J,port:$?parseInt($,10):void 0}}function qp1(Z,J){let $=J.firestore.app,X=$.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[_8.ATTR_DB_COLLECTION_NAME]:J.path,[_8.ATTR_DB_NAMESPACE]:$.name,[_8.ATTR_DB_SYSTEM_NAME]:"firebase.firestore","firebase.firestore.type":J.type,"firebase.firestore.options.projectId":X.projectId,"firebase.firestore.options.appId":X.appId,"firebase.firestore.options.messagingSenderId":X.messagingSenderId,"firebase.firestore.options.storageBucket":X.storageBucket},{address:K,port:z}=Cp1(Q);if(K)W[_8.ATTR_SERVER_ADDRESS]=K;if(z)W[_8.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var k5=v(u(),1),x9=v(D1(),1);function u01(Z,J,$,X,Y){let Q=()=>{},W=()=>{},K=Y.functions?.errorHook,z=Y.functions?.requestHook,G=Y.functions?.responseHook;if(typeof G==="function")W=(F,B)=>{x9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;k5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{x9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;k5.diag.error(B?.message)},!0)};let H=new x9.InstrumentationNodeModuleDefinition("firebase-functions",J);return[{name:"firebase-functions/lib/v2/providers/https.js",triggerType:"function"},{name:"firebase-functions/lib/v2/providers/firestore.js",triggerType:"firestore"},{name:"firebase-functions/lib/v2/providers/scheduler.js",triggerType:"scheduler"},{name:"firebase-functions/lib/v2/storage.js",triggerType:"storage"}].forEach(({name:F,triggerType:B})=>{H.files.push(new x9.InstrumentationNodeModuleFile(F,J,(U)=>Ep1(U,$,X,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>d01(U,X)))}),H}function Q6(Z,J,$){return function(Y){return function(...Q){let W=typeof Q[0]==="function"?Q[0]:Q[1],K=typeof Q[0]==="function"?void 0:Q[0];if(!W)return Y.call(this,...Q);let z=async function(...G){let H=process.env.FUNCTION_TARGET||process.env.K_SERVICE||"unknown",V=Z.startSpan(`firebase.function.${$}`,{kind:k5.SpanKind.SERVER}),F={"faas.name":H,"faas.trigger":$,"faas.provider":"firebase"};if(process.env.GCLOUD_PROJECT)F["cloud.project_id"]=process.env.GCLOUD_PROJECT;if(process.env.EVENTARC_CLOUD_EVENT_SOURCE)F["cloud.event_source"]=process.env.EVENTARC_CLOUD_EVENT_SOURCE;return V.setAttributes(F),J?.requestHook?.(V),k5.context.with(k5.trace.setSpan(k5.context.active(),V),async()=>{let B,U;try{U=await W.apply(this,G)}catch(L){B=L}if(J?.responseHook?.(V,B),B)V.recordException(B);if(V.end(),B)throw await J?.errorHook?.(V,B),B;return U})};if(K)return Y.call(this,K,z);else return Y.call(this,z)}}}function Ep1(Z,J,$,X,Y,Q){switch(d01(Z,$),Q){case"function":J(Z,"onRequest",Q6(X,Y,"http.request")),J(Z,"onCall",Q6(X,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",Q6(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",Q6(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",Q6(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",Q6(X,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",Q6(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",Q6(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",Q6(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",Q6(X,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",Q6(X,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",Q6(X,Y,"storage.object.finalized")),J(Z,"onObjectArchived",Q6(X,Y,"storage.object.archived")),J(Z,"onObjectDeleted",Q6(X,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",Q6(X,Y,"storage.object.metadataUpdated"));break}return Z}function d01(Z,J){let $=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let X of $)if(x9.isWrapped(Z[X]))J(Z,X);return Z}var c01={},Pp1=[">=3.0.0 <5"],Ip1=[">=6.0.0 <7"];class B_ extends l01.InstrumentationBase{constructor(Z=c01){super("@sentry/instrumentation-firebase",u1,Z)}setConfig(Z={}){super.setConfig({...c01,...Z})}init(){let Z=[];return Z.push(g01(this.tracer,Pp1,this._wrap,this._unwrap,this.getConfig())),Z.push(u01(this.tracer,Ip1,this._wrap,this._unwrap,this.getConfig())),Z}}var p01="Firebase",Sp1={firestoreSpanCreationHook:(Z)=>{Y0(Z,"auto.firebase.otel.firestore"),Z.setAttribute(U1,"db.query")},functions:{requestHook:(Z)=>{Y0(Z,"auto.firebase.otel.functions"),Z.setAttribute(U1,"http.request")},errorHook:async(Z,J)=>{if(J)O1(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await Kz(2000)}}},i01=s(p01,()=>new B_(Sp1)),yp1=()=>{return{name:p01,setupOnce(){i01()}}},n01=k(yp1);function EQ(){return[ai(),vn(),Ra(),Oe(),ko(),Xr(),jr(),pr(),as(),qt(),ct(),Ue(),le(),U11(),v11(),a11(),ta(),T01(),Bo(),k01(),h01(),N01(),C01(),E01(),S01(),yt(),n01()]}var IX=v(u(),1);var SX=v(X0(),1);var U_=1e6;function a01(Z,J={}){if(Z.getOptions().debug)TD();let[$,X]=kp1(Z,J);Z.traceProvider=$,Z.asyncLocalStorageLookup=X}function kp1(Z,J={}){let $=new rz({sampler:new WD(Z),resource:y3().merge(lz({[SX.ATTR_SERVICE_NAME]:"node",[SX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[SX.ATTR_SERVICE_VERSION]:u1})),forceFlushTimeoutMillis:500,spanProcessors:[new QD({timeout:xp1(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});IX.trace.setGlobalTracerProvider($),IX.propagation.setGlobalPropagator(new YD);let X=new XG;return IX.context.setGlobalContextManager(X),[$,X.getAsyncLocalStorageLookup()]}function xp1(Z){if(Z==null)return;if(Z>U_)return u0&&R.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${U_}`),U_;else if(Z<=0||Number.isNaN(Z)){u0&&R.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function o01(){return zG().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(a3(),r3())}function r01(Z){return[...o01(),...P0(Z)?EQ():[]]}function L_(Z={}){return vp1(Z,r01)}function vp1(Z={},J){_9(Z,"node");let $=SD({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if($&&!Z.skipOpenTelemetrySetup)a01($,{spanProcessors:Z.openTelemetrySpanProcessors}),GG();return $}import*as J41 from"os";var hp1="BunServer",fp1=()=>{return{name:hp1,setupOnce(){bp1()}}},e01=k(fp1),s01=!1;function bp1(){if(s01)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,$){t01($[0]);let X=Z.apply(J,$),Y=X.reload.bind(X);return X.reload=(Q)=>{return t01(Q),Y(Q)},X}}),s01=!0}function t01(Z){gp1(Z),mp1(Z)}function gp1(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,$,X){return D_(J,$,X)}})}function mp1(Z){if(!Z.routes)return;if(typeof Z.routes!=="object")return;Object.keys(Z.routes).forEach((J)=>{let $=Z.routes[J];if(typeof $==="function")Z.routes[J]=new Proxy($,{apply:(X,Y,Q)=>{return D_(X,Y,Q,J)}});if($ instanceof Response)return;if(typeof $==="object")Object.entries($).forEach(([X,Y])=>{if(typeof Y==="function")Z.routes[J][X]=new Proxy(Y,{apply:(Q,W,K)=>{return D_(Q,W,K,J)}})})})}function D_(Z,J,$,X){return rZ((Y)=>{let Q=$[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,$);let K=L3(Q.url),z=up1(K,Q),G=K?.pathname||"/";if(Q.params){if(Object.keys(Q.params).forEach((H)=>{z[`url.path.parameter.${H}`]=Q.params[H]}),X)z[E0]="route",z["url.template"]=X,G=X}if(X?.endsWith("/*"))z[E0]="route",z["url.template"]=X,G=X;return Object.assign(z,v$(Q.headers.toJSON(),p()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),Yz({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>h6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,$);if(V?.status)dK(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw O1(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function up1(Z,J){let $={[W1]:"auto.http.bun.serve",[AL]:J.method||"GET",[E0]:"url"};if(Z){if(Z.search)$["url.query"]=Z.search;if(Z.hash)$["url.fragment"]=Z.hash;if(Z.pathname)$["url.path"]=Z.pathname;if(!aL(Z)){if($["url.full"]=Z.href,Z.port)$["url.port"]=Z.port;if(Z.protocol)$["url.scheme"]=Z.protocol;if(Z.hostname)$["url.domain"]=Z.hostname}}return $}function Z41(Z){function J($){let X={body:$.body,method:"POST",headers:Z.headers};try{return S7(()=>{return fetch(Z.url,X).then((Y)=>{return{statusCode:Y.status,headers:{"x-sentry-rate-limits":Y.headers.get("X-Sentry-Rate-Limits"),"retry-after":Y.headers.get("Retry-After")}}})})}catch(Y){return Promise.reject(Y)}}return WJ(Z,J)}function $41(Z){return[f$(),h$(),b$(),g$(),m$(),a3(),r3(),HX(),VX(),zX(),KX(),GX(),e01(),...P0(Z)?EQ():[]]}function O_(Z={}){_9(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||J41.hostname()};if(J.transport=J.transport||Z41,J.defaultIntegrations===void 0)J.defaultIntegrations=$41(J);return L_(J)}O_({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as X41}from"fs";import{join as Y41}from"path";function O0(){return"3.2.0-beta.2"}function __(Z){let[J,$]=Z.split("-"),X=(J||"0.0.0").split(".").map(Number),Y=null,Q=0;if($){let W=$.match(/^([a-z]+)\.?(\d+)?$/i);if(W)Y=W[1]||null,Q=parseInt(W[2]||"0",10);else Y=$}return{major:X[0]||0,minor:X[1]||0,patch:X[2]||0,preRelease:Y,preReleaseNum:Q}}function v9(Z){let J=__(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function PQ(Z,J){try{let $=__(Z),X=__(J);if($.major>X.major)return!1;if($.major<X.major)return!1;if(X.preRelease&&!$.preRelease)return!1;if(!X.preRelease&&$.preRelease)return!1;if(X.preRelease&&$.preRelease){if($.minor<X.minor)return!1;if($.minor>X.minor)return!0;if($.patch>X.patch)return!0;if($.patch<X.patch)return!1;return $.preReleaseNum>X.preReleaseNum}if($.minor>X.minor)return!0;if($.minor<X.minor)return!1;if($.patch>X.patch)return!0;return!1}catch($){return!1}}import{parseArgs as cp1}from"util";var lp1={debug:{type:"boolean",short:"d",default:!1,description:"Enable debug logging"},"mqtt-port":{type:"string",default:"8884",description:"MQTT broker port"},"terminal-port":{type:"string",default:"3001",description:"Terminal server port"},"router-port":{type:"string",default:"8883",description:"Router port"},username:{type:"string",short:"u",description:"MQTT broker username (required)"},password:{type:"string",short:"p",description:"MQTT broker password (required)"},"ngrok-token":{type:"string",description:"ngrok authentication token (optional)"},"ngrok-domain":{type:"string",description:"ngrok static domain (optional, paid plan)"},"no-auto-update":{type:"boolean",default:!1,description:"Disable auto-update checking"},"terminal-audit":{type:"boolean",default:!1,description:"Enable terminal input audit logging (logs commands, not output)"},"auto-update-check-interval":{type:"string",default:"60",description:"Auto-update check interval in minutes (default: 60)"},help:{type:"boolean",short:"h",default:!1,description:"Show help message"},version:{type:"boolean",short:"v",default:!1,description:"Show version"}};function Q41(){let Z=cp1({options:lp1,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${O0()}`),process.exit(0);if(Z.values.help)pp1(),process.exit(0);let J=process.env.CCC_USERNAME||Z.values.username,$=process.env.CCC_PASSWORD||Z.values.password,X=process.env.CCC_NGROK_TOKEN||Z.values["ngrok-token"],Y=process.env.CCC_NGROK_DOMAIN||Z.values["ngrok-domain"];if(!J||!$)console.error("\x1B[31mError: Authentication credentials are required.\x1B[0m"),console.error(""),console.error("These credentials secure the MQTT communication between the app and backend."),console.error(""),console.error("You can provide them via:"),console.error(""),console.error(" Environment variables (recommended for security):"),console.error(" export CCC_USERNAME=myuser"),console.error(" export CCC_PASSWORD=mypassword"),console.error(" export CCC_NGROK_TOKEN=your_token # optional"),console.error(" export CCC_NGROK_DOMAIN=your_domain # optional"),console.error(" ccc"),console.error(""),console.error(" Or CLI arguments:"),console.error(" ccc --username myuser --password mypassword"),console.error(" ccc -u myuser -p mypassword"),console.error(""),process.exit(1);return{debug:Z.values.debug,mqttPort:parseInt(Z.values["mqtt-port"],10),terminalPort:parseInt(Z.values["terminal-port"],10),routerPort:parseInt(Z.values["router-port"],10),username:J,password:$,ngrokToken:X,ngrokDomain:Y,autoUpdate:!Z.values["no-auto-update"],autoUpdateCheckInterval:parseInt(Z.values["auto-update-check-interval"],10),terminalAudit:Z.values["terminal-audit"]}}function pp1(){console.log(`
54
+ >>> no match, partial?`,Z,V,J,F),V===K)return!0}return!1}let U;if(typeof G==="string")U=H===G,this.debug("string match",G,H,U);else U=G.test(H),this.debug("pattern match",G,H,U);if(!U)return!1}if(Q===K&&W===z)return!0;else if(Q===K)return $;else if(W===z)return Q===K-1&&Z[Q]==="";else throw Error("wtf?")}braceExpand(){return wn(this.pattern,this.options)}parse(Z){e3(Z);let J=this.options;if(Z==="**")return V8;if(Z==="")return"";let $,X=null;if($=Z.match(ef1))X=J.dot?Jb1:Zb1;else if($=Z.match(cf1))X=(J.nocase?J.dot?nf1:if1:J.dot?pf1:lf1)($[1]);else if($=Z.match($b1))X=(J.nocase?J.dot?Yb1:Xb1:J.dot?Qb1:Wb1)($);else if($=Z.match(af1))X=J.dot?rf1:of1;else if($=Z.match(sf1))X=tf1;let Y=S4.fromGlob(Z,this.options).toMMPattern();if(X&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:X});return Y}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,$=J.noglobstar?Gb1:J.dot?Hb1:Vb1,X=new Set(J.nocase?["i"]:[]),Y=Z.map((K)=>{let z=K.map((G)=>{if(G instanceof RegExp)for(let H of G.flags.split(""))X.add(H);return typeof G==="string"?Db1(G):G===V8?V8:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==V8||F===V8)return;if(F===void 0)if(V!==void 0&&V!==V8)z[H+1]="(?:\\/|"+$+"\\/)?"+V;else z[H]=$;else if(V===void 0)z[H-1]=F+"(?:\\/|"+$+")?";else if(V!==V8)z[H-1]=F+"(?:\\/|\\/"+$+"\\/)"+V,z[H+1]=V8}),z.filter((G)=>G!==V8).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...X].join(""))}catch(K){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let $=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let X=this.slashSplit(Z);this.debug(this.pattern,"split",X);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=X[X.length-1];if(!Q)for(let W=X.length-2;!Q&&W>=0;W--)Q=X[W];for(let W=0;W<Y.length;W++){let K=Y[W],z=X;if($.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,J)){if($.flipNegate)return!0;return!this.negate}}if($.flipNegate)return!1;return this.negate}static defaults(Z){return y4.defaults(Z).Minimatch}}y4.AST=S4;y4.Minimatch=JQ;y4.escape=cD;y4.unescape=r7;var Tn="@fastify/otel",_b1="0.8.0",wb1=">=4.0.0 <6",Mn=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],L0={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},s7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},R9="anonymous",$6=Symbol("fastify otel instance"),t7=Symbol("fastify otel request spans"),$Q=Symbol("fastify otel request context"),jn=Symbol("fastify otel addhook original"),Nn=Symbol("fastify otel setnotfound original"),DG=Symbol("fastify otel ignore path");class lD extends Rn.InstrumentationBase{constructor(Z){super(Tn,_b1,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[DG]=null,this._logger=s0.diag.createComponentLogger({namespace:Tn}),Z?.ignorePaths!=null||process.env.OTEL_FASTIFY_IGNORE_PATHS!=null){let J=Z?.ignorePaths??process.env.OTEL_FASTIFY_IGNORE_PATHS;if((typeof J!=="string"||J.length===0)&&typeof J!=="function")throw TypeError("ignorePaths must be a string or a function");let $=y4;this[DG]=(X)=>{if(typeof J==="function")return J(X);else return $(X.url,J)}}}enable(){if(this._handleInitialization===void 0&&this.getConfig().registerOnInitialization){let Z=this.plugin();this._handleInitialization=(J)=>{J.fastify.register(Z)},An.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)An.unsubscribe("fastify.initialization",this._handleInitialization),this._handleInitialization=void 0;return super.disable()}init(){return[]}plugin(){let Z=this;return J[Symbol.for("skip-override")]=!0,J[Symbol.for("fastify.display-name")]="@fastify/otel",J[Symbol.for("plugin-meta")]={fastify:wb1,name:"@fastify/otel"},J;function J($,X,Y){$.decorate($6,Z),$.decorate(jn,$.addHook),$.decorate(Nn,$.setNotFoundHandler),$.decorateRequest("opentelemetry",function(){let V=this[$Q];return{span:this[t7],tracer:Z.tracer,context:V,inject:(B,U)=>{return s0.propagation.inject(V,B,U)},extract:(B,U)=>{return s0.propagation.extract(V,B,U)}}}),$.decorateRequest(t7,null),$.decorateRequest($Q,null),$.addHook("onRoute",function(H){if(Z[DG]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of Mn)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[L0.FASTIFY_TYPE]:s7.ROUTE,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:R9});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[L0.FASTIFY_TYPE]:s7.ROUTE,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:R9}));H[V]=B}}if(H.onSend!=null)H.onSend=Array.isArray(H.onSend)?[...H.onSend,Q]:[H.onSend,Q];else H.onSend=Q;if(H.onError!=null)H.onError=Array.isArray(H.onError)?[...H.onError,W]:[H.onError,W];else H.onError=W;H.handler=G(H.handler,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - route-handler`,[L0.FASTIFY_TYPE]:s7.HANDLER,[Y4.ATTR_HTTP_ROUTE]:H.url,[L0.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:R9})}),$.addHook("onRequest",function(H,V,F){if(this[$6].isEnabled()===!1)return F();else if(this[$6][DG]?.({url:H.url,method:H.method})===!0)return this[$6]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=s0.context.active();if(s0.trace.getSpan(B)==null)B=s0.propagation.extract(B,H.headers);let U=OG.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===OG.RPCType.HTTP)U.route=H.routeOptions.url;let L=this[$6].tracer.startSpan("request",{attributes:{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.ROOT]:"@fastify/otel",[Y4.ATTR_HTTP_ROUTE]:H.url,[Y4.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[$Q]=s0.trace.setSpan(B,L),H[t7]=L,s0.context.with(H[$Q],()=>{F()})}),$.addHook("onResponse",function(H,V,F){let B=H[t7];if(B!=null)B.setStatus({code:s0.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[Y4.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[t7]=null,F()}),$.addHook=K,$.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[t7];if(U!=null){if(V.statusCode<500)U.setStatus({code:s0.SpanStatusCode.OK,message:"OK"});U.setAttributes({[Y4.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[t7]=null,B(null,F)}function W(H,V,F,B){let U=H[t7];if(U!=null)U.setStatus({code:s0.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[jn];if(Mn.includes(H))return F.call(this,H,G(V,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - ${H}`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:R9}));else return F.call(this,H,V)}function z(H,V){let F=this[Nn];if(typeof H==="function")V=G(H,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:R9}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:R9});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:R9});V=G(V,{[Y4.ATTR_SERVICE_NAME]:$[$6].servername,[L0.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[L0.FASTIFY_TYPE]:s7.INSTANCE,[L0.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:R9}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[$6],[L]=B;if(U.isEnabled()===!1)return H.call(this,...B);let O=L[$Q]??s0.context.active(),_=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??R9}`,{attributes:V},O);return s0.context.with(s0.trace.setSpan(O,_),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((A)=>{return _.end(),A},(A)=>{return _.setStatus({code:s0.SpanStatusCode.ERROR,message:A.message}),_.recordException(A),_.end(),Promise.reject(A)});return _.end(),w}catch(w){throw _.setStatus({code:s0.SpanStatusCode.ERROR,message:w.message}),_.recordException(w),_.end(),w}},this)}}}}}var Z5=v(u(),1),wG=v(N0(),1),AJ=v(D1(),1),In=v(X0(),1);var C9;(function(Z){Z.FASTIFY_NAME="fastify.name";let $="fastify.type";Z.FASTIFY_TYPE=$;let X="hook.name";Z.HOOK_NAME=X;let Y="plugin.name";Z.PLUGIN_NAME=Y})(C9||(C9={}));var XQ;(function(Z){Z.MIDDLEWARE="middleware";let $="request_handler";Z.REQUEST_HANDLER=$})(XQ||(XQ={}));var YQ;(function(Z){Z.MIDDLEWARE="middleware";let $="request handler";Z.REQUEST_HANDLER=$})(YQ||(YQ={}));var qn=v(u(),1);var QQ=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function pD(Z,J,$,X={}){let Y=J.startSpan($,{attributes:X}),Q=Z[QQ]||[];return Q.push(Y),Object.defineProperty(Z,QQ,{enumerable:!1,configurable:!0,value:Q}),Y}function _G(Z,J){let $=Z[QQ]||[];if(!$.length)return;$.forEach((X)=>{if(J)X.setStatus({code:qn.SpanStatusCode.ERROR,message:J.message}),X.recordException(J);X.end()}),delete Z[QQ]}function En(Z,J,$){let X,Y=void 0;try{if(Y=Z(),Cn(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){X=Q}finally{if(!Cn(Y)){if(J(X,Y),X)throw X}return Y}}function Cn(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var Ab1="0.1.0",Tb1="@sentry/instrumentation-fastify-v3",Pn="anonymous",Mb1=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class iD extends AJ.InstrumentationBase{constructor(Z={}){super(Tb1,Ab1,Z)}init(){return[new AJ.InstrumentationNodeModuleDefinition("fastify",[">=3.0.0 <4"],(Z)=>{return this._patchConstructor(Z)})]}_hookOnRequest(){let Z=this;return function($,X,Y){if(!Z.isEnabled())return Y();Z._wrap(X,"send",Z._patchSend());let Q=$,W=wG.getRPCMetadata(Z5.context.active()),K=Q.routeOptions?Q.routeOptions.url:$.routerPath;if(K&&W?.type===wG.RPCType.HTTP)W.route=K;let z=$.method||"GET";d1().setTransactionName(`${z} ${K}`),Y()}}_wrapHandler(Z,J,$,X){let Y=this;return this._diag.debug("Patching fastify route.handler function"),function(...Q){if(!Y.isEnabled())return $.apply(this,Q);let W=$.name||Z||Pn,K=`${YQ.MIDDLEWARE} - ${W}`,z=Q[1],G=pD(z,Y.tracer,K,{[C9.FASTIFY_TYPE]:XQ.MIDDLEWARE,[C9.PLUGIN_NAME]:Z,[C9.HOOK_NAME]:J}),H=X&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){_G(z),H.apply(this,V)};return Z5.context.with(Z5.trace.setSpan(Z5.context.active(),G),()=>{return En(()=>{return $.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:Z5.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!X)_G(z)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function(...X){let Y=X[0],Q=X[1],W=this.pluginName;if(!Mb1.has(Y))return J.apply(this,X);let K=typeof X[X.length-1]==="function"&&Q.constructor.name!=="AsyncFunction";return J.apply(this,[Y,Z._wrapHandler(W,Y,Q,K)])}}}_patchConstructor(Z){let J=this;function $(...X){let Y=Z.fastify.apply(this,X);return Y.addHook("onRequest",J._hookOnRequest()),Y.addHook("preHandler",J._hookPreHandler()),jb1(),J._wrap(Y,"addHook",J._wrapAddHook()),Y}if(Z.errorCodes!==void 0)$.errorCodes=Z.errorCodes;return $.fastify=$,$.default=$,$}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function($){return function(...Y){let Q=Y[0];if(!Z.isEnabled())return $.apply(this,Y);return AJ.safeExecuteInTheMiddle(()=>{return $.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;_G(this,W)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function($,X,Y){if(!Z.isEnabled())return Y();let Q=$,W=Q.routeOptions?.handler||Q.context?.handler,K=W?.name.startsWith("bound ")?W.name.substring(6):W?.name,z=`${YQ.REQUEST_HANDLER} - ${K||this.pluginName||Pn}`,G={[C9.PLUGIN_NAME]:this.pluginName,[C9.FASTIFY_TYPE]:XQ.REQUEST_HANDLER,[In.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:$.routerPath};if(K)G[C9.FASTIFY_NAME]=K;let H=pD(X,Z.tracer,z,G);Sn(H);let{requestHook:V}=Z.getConfig();if(V)AJ.safeExecuteInTheMiddle(()=>V(H,{request:$}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return Z5.context.with(Z5.trace.setSpan(Z5.context.active(),H),()=>{Y()})}}}function jb1(){let Z=p();if(Z)Z.on("spanStart",(J)=>{Sn(J)})}function Sn(Z){let J=X1(Z).data,$=J["fastify.type"];if(J[U1]||!$)return;Z.setAttributes({[W1]:"auto.http.otel.fastify",[U1]:`${$}.fastify`});let X=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof X==="string"){let Y=X.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(Y)}}var AG="Fastify",kn=s(`${AG}.v3`,()=>new iD);function Nb1(){let Z=p();if(!Z)return;else return Z.getIntegrationByName(AG)}function yn(Z,J,$,X){let Y=Nb1()?.getShouldHandleError()||hn;if(X==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&X==="onError-hook"){u0&&R.warn("Fastify error handler was already registered via diagnostics channel.","You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options.");return}if(Y(Z,J,$))O1(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var xn=s(`${AG}.v5`,()=>{let Z=new lD,J=Z.plugin();return nD.subscribe("fastify.initialization",($)=>{let X=$.fastify;X?.register(J).after((Y)=>{if(Y)u0&&R.error("Failed to setup Fastify instrumentation",Y);else if(Cb1(),X)qb1(X)})}),nD.subscribe("tracing:fastify.request.handler:error",($)=>{let{error:X,request:Y,reply:Q}=$;yn.call(yn,X,Y,Q,"diagnostics-channel")}),Z}),Rb1=({shouldHandleError:Z})=>{let J;return{name:AG,setupOnce(){J=Z||hn,kn(),xn()},getShouldHandleError(){return J},setShouldHandleError($){J=$}}},vn=k((Z={})=>Rb1(Z));function hn(Z,J,$){let X=$.statusCode;return X>=500||X<=299}function fn(Z){let J=X1(Z),$=J.description,X=J.data,Y=X["fastify.type"],Q=Y==="hook",W=Y===$?.startsWith("handler -"),K=$==="request"||Y==="request-handler";if(X[U1]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[W1]:"auto.http.otel.fastify",[U1]:`${z}.fastify`});let G=X["fastify.name"]||X["plugin.name"]||X["hook.name"];if(typeof G==="string"){let H=G.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(H)}}function Cb1(){let Z=p();if(Z)Z.on("spanStart",(J)=>{fn(J)})}function qb1(Z){Z.addHook("onRequest",async(J,$)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)fn(Q)}let X=J.routeOptions?.url,Y=J.method||"GET";d1().setTransactionName(`${Y} ${X}`)})}var Ta=v(u(),1),Ma=v(Aa(),1);var ja="Graphql",Na=s(ja,Ma.GraphQLInstrumentation,(Z)=>{let J=Ca(Z);return{...J,responseHook($,X){if(Y0($,"auto.graphql.otel.graphql"),X.errors?.length&&!X1($).status)$.setStatus({code:Ta.SpanStatusCode.ERROR});let Q=X1($).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=g0($),H=X1(z).data[$X]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute($X,H);else if(typeof H==="string")z.setAttribute($X,[H,V]);else z.setAttribute($X,V);if(!X1(z).data["original-description"])z.setAttribute("original-description",X1(z).description);z.updateName(`${X1(z).data["original-description"]} (${Xg1(H)})`)}}}}),$g1=(Z={})=>{return{name:ja,setupOnce(){Na(Ca(Z))}}},Ra=k($g1);function Ca(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function Xg1(Z){if(Array.isArray(Z)){let J=Z.slice().sort();if(J.length<=5)return J.join(", ");else return`${J.slice(0,5).join(", ")}, +${J.length-5}`}return`${Z}`}var oa=v(aa(),1);var ra="Kafka",sa=s(ra,()=>new oa.KafkaJsInstrumentation({consumerHook(Z){Y0(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){Y0(Z,"auto.kafkajs.otel.producer")}})),jg1=()=>{return{name:ra,setupOnce(){sa()}}},ta=k(jg1);var Ho=v(Go(),1);var Vo="LruMemoizer",Fo=s(Vo,()=>new Ho.LruMemoizerInstrumentation),qg1=()=>{return{name:Vo,setupOnce(){Fo()}}},Bo=k(qg1);var Io=v(Po(),1);var So="Mongo",yo=s(So,()=>new Io.MongoDBInstrumentation({dbStatementSerializer:cg1,responseHook(Z){Y0(Z,"auto.db.otel.mongo")}}));function cg1(Z){let J=WO(Z);return JSON.stringify(J)}function WO(Z){if(Array.isArray(Z))return Z.map((J)=>WO(J));if(lg1(Z)){let J={};return Object.entries(Z).map(([$,X])=>[$,WO(X)]).reduce(($,X)=>{if(ig1(X))$[X[0]]=X[1];return $},J)}return"?"}function lg1(Z){return typeof Z==="object"&&Z!==null&&!pg1(Z)}function pg1(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function ig1(Z){return Array.isArray(Z)}var ng1=()=>{return{name:So,setupOnce(){yo()}}},ko=k(ng1);var Zr=v(eo(),1);var Jr="Mongoose",$r=s(Jr,()=>new Zr.MongooseInstrumentation({responseHook(Z){Y0(Z,"auto.db.otel.mongoose")}})),Um1=()=>{return{name:Jr,setupOnce(){$r()}}},Xr=k(Um1);var Ar=v(wr(),1);var Tr="Mysql",Mr=s(Tr,()=>new Ar.MySQLInstrumentation({})),gm1=()=>{return{name:Tr,setupOnce(){Mr()}}},jr=k(gm1);var dr=v(ur(),1);var cr="Mysql2",lr=s(cr,()=>new dr.MySQL2Instrumentation({responseHook(Z){Y0(Z,"auto.db.otel.mysql2")}})),Bu1=()=>{return{name:cr,setupOnce(){lr()}}},pr=k(Bu1);var ls=v(Hs(),1),ps=v(gs(),1);var ou1=["get","set","setex"],EO=["get","mget"],ru1=["set","setex"];function LQ(Z,J){return Z.includes(J.toLowerCase())}function PO(Z){if(LQ(EO,Z))return"cache.get";else if(LQ(ru1,Z))return"cache.put";else return}function su1(Z,J){return J.some(($)=>Z.startsWith($))}function us(Z,J){try{if(J.length===0)return;let $=(Y)=>{if(typeof Y==="string"||typeof Y==="number"||Buffer.isBuffer(Y))return[Y.toString()];else if(Array.isArray(Y))return ms(Y.map((Q)=>$(Q)));else return["<unknown>"]},X=J[0];if(LQ(ou1,Z)&&X!=null)return $(X);return ms(J.map((Y)=>$(Y)))}catch{return}}function ds(Z,J,$){if(!PO(Z))return!1;for(let X of J)if(su1(X,$))return!0;return!1}function cs(Z){let J=($)=>{try{if(Buffer.isBuffer($))return $.byteLength;else if(typeof $==="string")return $.length;else if(typeof $==="number")return $.toString().length;else if($===null||$===void 0)return 0;return JSON.stringify($).length}catch{return}};return Array.isArray(Z)?Z.reduce(($,X)=>{let Y=J(X);return typeof Y==="number"?$!==void 0?$+Y:Y:$},0):J(Z)}function ms(Z){let J=[],$=(X)=>{X.forEach((Y)=>{if(Array.isArray(Y))$(Y);else J.push(Y)})};return $(Z),J}var vG="Redis",DQ={},is=(Z,J,$,X)=>{Z.setAttribute(W1,"auto.db.otel.redis");let Y=us(J,$),Q=PO(J);if(!Y||!Q||!DQ.cachePrefixes||!ds(J,Y,DQ.cachePrefixes))return;let W=X1(Z).data["net.peer.name"],K=X1(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=cs(X);if(z)Z.setAttribute(wL,z);if(LQ(EO,J)&&z!==void 0)Z.setAttribute(OL,z>0);Z.setAttributes({[U1]:Q,[_L]:Y});let G=Y.join(", ");Z.updateName(DQ.maxCacheKeyLength?M7(G,DQ.maxCacheKeyLength):G)},tu1=s(`${vG}.IORedis`,()=>{return new ls.IORedisInstrumentation({responseHook:is})}),eu1=s(`${vG}.Redis`,()=>{return new ps.RedisInstrumentation({responseHook:is})}),ns=Object.assign(()=>{tu1(),eu1()},{id:vG}),Zd1=(Z={})=>{return{name:vG,setupOnce(){DQ=Z,ns()}}},as=k(Zd1);var Nt=v(jt(),1);var Rt="Postgres",Ct=s(Rt,()=>new Nt.PgInstrumentation({requireParentSpan:!0,requestHook(Z){Y0(Z,"auto.db.otel.postgres")}})),id1=()=>{return{name:Rt,setupOnce(){Ct()}}},qt=k(id1);var jX=v(u(),1),I9=v(D1(),1),t0=v(X0(),1);var dG="PostgresJs",Et=[">=3.0.0 <4"],nd1=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,uG=Symbol("sentryPostgresConnectionContext"),hO=Symbol.for("sentry.instrumented.postgresjs"),Pt=Symbol.for("sentry.query.from.instrumented.sql"),It=s(dG,(Z)=>new St({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class St extends I9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",u1,Z)}init(){let Z=new I9.InstrumentationNodeModuleDefinition("postgres",Et,(J)=>{try{return this._patchPostgres(J)}catch($){return u0&&R.error("Failed to patch postgres module:",$),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new I9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,Et,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",$=J?Z:Z.default;if(typeof $!=="function")return u0&&R.warn("postgres module does not export a function. Skipping instrumentation."),Z;let X=this,Y=function(...Q){let W=Reflect.construct($,Q);if(!W||typeof W!=="function")return u0&&R.warn("postgres() did not return a valid instance"),W;return X._instrumentSqlInstance(W)};Object.setPrototypeOf(Y,$),Object.setPrototypeOf(Y.prototype,$.prototype);for(let Q of Object.getOwnPropertyNames($))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor($,Q);if(W)Object.defineProperty(Y,Q,W)}if(J)return Y;else return q3(Z,"default",Y),Z}_wrapQueryMethod(Z,J,$){let X=this;return function(...Y){let Q=Reflect.apply(Z,J,Y);if(Q&&typeof Q==="object"&&"handle"in Q)X._wrapSingleQueryHandle(Q,$);return Q}}_wrapCallbackMethod(Z,J,$){let X=this;return function(...Y){let Q=$[uG];if(typeof Y[Y.length-1]!=="function"){let H=Reflect.apply(Z,J,Y);if(H&&typeof H.then==="function")return H.then((V)=>{return X._instrumentSqlInstance(V,Q)});return H}let K=Y.length===1?Y[0]:Y[1],z=function(H){let V=X._instrumentSqlInstance(H,Q);return K(V)},G=Y.length===1?[z]:[Y[0],z];return Reflect.apply(Z,J,G)}}_setConnectionAttributes(Z,J){if(!J)return;if(J.ATTR_DB_NAMESPACE)Z.setAttribute(t0.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(t0.ATTR_SERVER_ADDRESS,J.ATTR_SERVER_ADDRESS);if(J.ATTR_SERVER_PORT!==void 0){let $=parseInt(J.ATTR_SERVER_PORT,10);if(!isNaN($))Z.setAttribute(t0.ATTR_SERVER_PORT,$)}}_setOperationName(Z,J,$){if($){Z.setAttribute(t0.ATTR_DB_OPERATION_NAME,$);return}let X=J?.match(nd1);if(X?.[1])Z.setAttribute(t0.ATTR_DB_OPERATION_NAME,X[1].toUpperCase())}_attachConnectionContext(Z,J){let $=Z;if(!$.options||typeof $.options!=="object")return;let X=$.options,Y=X.host?.[0]||"localhost",Q=X.port?.[0]||5432,W={ATTR_DB_NAMESPACE:typeof X.database==="string"&&X.database!==""?X.database:void 0,ATTR_SERVER_ADDRESS:Y,ATTR_SERVER_PORT:String(Q)};J[uG]=W}_instrumentSqlInstance(Z,J){if(Z[hO])return Z;let $=this,X=new Proxy(Z,{apply(Y,Q,W){let K=Reflect.apply(Y,Q,W);if(K&&typeof K==="object"&&"handle"in K)$._wrapSingleQueryHandle(K,X);return K},get(Y,Q){let W=Y[Q];if(typeof Q!=="string"||typeof W!=="function")return W;if(Q==="unsafe"||Q==="file")return $._wrapQueryMethod(W,Y,X);if(Q==="begin"||Q==="reserve")return $._wrapCallbackMethod(W,Y,X);return W}});if(J)X[uG]=J;else this._attachConnectionContext(Z,X);return Z[hO]=!0,X[hO]=!0,X}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Pt]=!0;let $=Z.handle,X=this,Y=async function(...Q){if(!X._shouldCreateSpans())return $.apply(this,Q);let W=X._reconstructQuery(Z.strings),K=X._sanitizeSqlQuery(W);return P4({name:K||"postgresjs.query",op:"db"},(z)=>{Y0(z,"auto.db.postgresjs"),z.setAttributes({[t0.ATTR_DB_SYSTEM_NAME]:"postgres",[t0.ATTR_DB_QUERY_TEXT]:K});let G=J?J[uG]:void 0;X._setConnectionAttributes(z,G);let H=X.getConfig(),{requestHook:V}=H;if(V)I9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),u0&&R.error(`Error in requestHook for ${dG} integration:`,B)},!0);let F=this;F.resolve=new Proxy(F.resolve,{apply:(B,U,L)=>{try{X._setOperationName(z,K,L?.[0]?.command),z.end()}catch(O){u0&&R.error("Error ending span in resolve callback:",O)}return Reflect.apply(B,U,L)}}),F.reject=new Proxy(F.reject,{apply:(B,U,L)=>{try{z.setStatus({code:v1,message:L?.[0]?.message||"unknown_error"}),z.setAttribute(t0.ATTR_DB_RESPONSE_STATUS_CODE,L?.[0]?.code||"unknown"),z.setAttribute(t0.ATTR_ERROR_TYPE,L?.[0]?.name||"unknown"),X._setOperationName(z,K),z.end()}catch(O){u0&&R.error("Error ending span in reject callback:",O)}return Reflect.apply(B,U,L)}});try{return $.apply(this,Q)}catch(B){throw z.setStatus({code:v1,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return jX.trace.getSpan(jX.context.active())!==void 0||!Z.requireParentSpan}_reconstructQuery(Z){if(!Z?.length)return;if(Z.length===1)return Z[0]||void 0;return Z.reduce((J,$,X)=>X===0?$:`${J}$${X}${$}`,"")}_sanitizeSqlQuery(Z){if(!Z)return"Unknown SQL Query";return Z.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/;\s*$/,"").replace(/\s+/g," ").trim().replace(/\bX'[0-9A-Fa-f]*'/gi,"?").replace(/\bB'[01]*'/gi,"?").replace(/'(?:[^']|'')*'/g,"?").replace(/\b0x[0-9A-Fa-f]+/gi,"?").replace(/\b(?:TRUE|FALSE)\b/gi,"?").replace(/-?\b\d+\.?\d*[eE][+-]?\d+\b/g,"?").replace(/-?\b\d+\.\d+\b/g,"?").replace(/-?\.\d+\b/g,"?").replace(/(?<!\$)-?\b\d+\b/g,"?").replace(/\bIN\b\s*\(\s*\?(?:\s*,\s*\?)*\s*\)/gi,"IN (?)").replace(/\bIN\b\s*\(\s*\$\d+(?:\s*,\s*\$\d+)*\s*\)/gi,"IN ($?)")}_patchQueryPrototype(Z){let J=this,$=Z.Query.prototype.handle;return Z.Query.prototype.handle=async function(...X){if(this[Pt])return $.apply(this,X);if(!J._shouldCreateSpans())return $.apply(this,X);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return P4({name:Q||"postgresjs.query",op:"db"},(W)=>{Y0(W,"auto.db.postgresjs"),W.setAttributes({[t0.ATTR_DB_SYSTEM_NAME]:"postgres",[t0.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)I9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),u0&&R.error(`Error in requestHook for ${dG} integration:`,V)},!0);let G=this.resolve;this.resolve=new Proxy(G,{apply:(V,F,B)=>{try{J._setOperationName(W,Q,B?.[0]?.command),W.end()}catch(U){u0&&R.error("Error ending span in resolve callback:",U)}return Reflect.apply(V,F,B)}});let H=this.reject;this.reject=new Proxy(H,{apply:(V,F,B)=>{try{W.setStatus({code:v1,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(t0.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(t0.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){u0&&R.error("Error ending span in reject callback:",U)}return Reflect.apply(V,F,B)}});try{return $.apply(this,X)}catch(V){throw W.setStatus({code:v1,message:V instanceof Error?V.message:"unknown_error"}),W.end(),V}})},Z.Query.prototype.handle.__sentry_original__=$,Z}_unpatchQueryPrototype(Z){if(Z.Query.prototype.handle.__sentry_original__)Z.Query.prototype.handle=Z.Query.prototype.handle.__sentry_original__;return Z}}var ad1=(Z)=>{return{name:dG,setupOnce(){It(Z)}}},yt=k(ad1);var O8=v(u(),1);var vt=v(u(),1),cG=v(D1(),1),XZ=v(u(),1);var od1=process.env.PRISMA_SHOW_ALL_TRACES==="true",rd1="00-10-10-00";function sd1(Z){switch(Z){case"client":return XZ.SpanKind.CLIENT;case"internal":default:return XZ.SpanKind.INTERNAL}}var td1=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=XZ.trace.getSpanContext(Z??XZ.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return rd1}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),$=new Map,X=Z.filter((Y)=>Y.parentId===null);for(let Y of X)ht(J,Y,Z,$,this.ignoreSpanTypes)}getActiveContext(){return XZ.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!od1)return J();let $=this.tracerProvider.getTracer("prisma"),X=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(ft(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=$.startSpan(Y,Z,X);return kt(Q,J(Q,X))}return $.startActiveSpan(Y,Z,(Q)=>kt(Q,J(Q,X)))}};function ht(Z,J,$,X,Y){if(ft(J.name,Y))return;let Q={attributes:J.attributes,kind:sd1(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(W)=>{if(X.set(J.id,W.spanContext().spanId),J.links)W.addLinks(J.links.flatMap((z)=>{let G=X.get(z);if(!G)return[];return{context:{spanId:G,traceId:W.spanContext().traceId,traceFlags:W.spanContext().traceFlags}}}));let K=$.filter((z)=>z.parentId===J.id);for(let z of K)ht(Z,z,$,X,Y);W.end(J.endTime)})}function kt(Z,J){if(ed1(J))return J.then(($)=>{return Z.end(),$},($)=>{throw Z.end(),$});return Z.end(),J}function ed1(Z){return Z!=null&&typeof Z.then==="function"}function ft(Z,J){return J.some(($)=>typeof $==="string"?$===Z:$.test(Z))}var bt={name:"@prisma/instrumentation",version:"6.19.0",description:"OpenTelemetry compliant instrumentation for Prisma Client",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{require:{types:"./dist/index.d.ts",default:"./dist/index.js"},import:{types:"./dist/index.d.ts",default:"./dist/index.mjs"}}},license:"Apache-2.0",homepage:"https://www.prisma.io",repository:{type:"git",url:"https://github.com/prisma/prisma.git",directory:"packages/instrumentation"},bugs:"https://github.com/prisma/prisma/issues",devDependencies:{"@prisma/internals":"workspace:*","@types/node":"18.19.76","@opentelemetry/api":"1.9.0",typescript:"5.4.5"},dependencies:{"@opentelemetry/instrumentation":">=0.52.0 <1"},peerDependencies:{"@opentelemetry/api":"^1.8"},files:["dist"],keywords:["prisma","instrumentation","opentelemetry","otel"],scripts:{dev:"DEV=true tsx helpers/build.ts",build:"tsx helpers/build.ts",prepublishOnly:"pnpm run build",test:"vitest run"},sideEffects:!1},bO=bt.version,Zc1=bO.split(".")[0],xt="PRISMA_INSTRUMENTATION",fO=`V${Zc1}_PRISMA_INSTRUMENTATION`,Jc1=bt.name,$c1="@prisma/client",gt=class extends cG.InstrumentationBase{tracerProvider;constructor(Z={}){super(Jc1,bO,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new cG.InstrumentationNodeModuleDefinition($c1,[bO])]}enable(){let Z=this._config,J={helper:new td1({tracerProvider:this.tracerProvider??vt.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[xt]=J,global[fO]=J}disable(){delete global[xt],delete global[fO]}isEnabled(){return Boolean(global[fO])}};var mt="Prisma";function Xc1(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function ut(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class dt extends gt{constructor(){super()}enable(){super.enable();let Z=ut();if(Xc1(Z))Z.createEngineSpan=(J)=>{let $=O8.trace.getTracer("prismaV5Compatibility"),X=$._idGenerator;if(!X){o0(()=>{console.warn("[Sentry] Could not find _idGenerator on tracer, skipping Prisma v5 compatibility - some Prisma spans may be missing!")});return}try{J.spans.forEach((Y)=>{let Q=Yc1(Y.kind),W=Y.parent_span_id,K=Y.span_id,z=Y.trace_id,G=Y.links?.map((V)=>{return{context:{traceId:V.trace_id,spanId:V.span_id,traceFlags:O8.TraceFlags.SAMPLED}}}),H=O8.trace.setSpanContext(O8.context.active(),{traceId:z,spanId:W,traceFlags:O8.TraceFlags.SAMPLED});O8.context.with(H,()=>{let V={generateTraceId:()=>{return z},generateSpanId:()=>{return K}};$._idGenerator=V,$.startSpan(Y.name,{kind:Q,links:G,startTime:Y.start_time,attributes:Y.attributes}).end(Y.end_time),$._idGenerator=X})})}finally{$._idGenerator=X}}}}function Yc1(Z){switch(Z){case"client":return O8.SpanKind.CLIENT;case"internal":default:return O8.SpanKind.INTERNAL}}var Qc1=s(mt,(Z)=>{return new dt}),ct=k((Z)=>{return{name:mt,setupOnce(){Qc1()},setup(J){if(!ut())return;J.on("spanStart",($)=>{let X=X1($);if(X.description?.startsWith("prisma:"))$.setAttribute(W1,"auto.db.otel.prisma");if(X.description==="prisma:engine:db_query"&&X.data["db.query.text"])$.updateName(X.data["db.query.text"]);if(X.description==="prisma:engine:db_query"&&!X.data["db.system"])$.setAttribute("db.system","prisma")})}}});var Ve=v(He(),1);var Fe="Hapi",Be=s(Fe,()=>new Ve.HapiInstrumentation),Pc1=()=>{return{name:Fe,setupOnce(){Be()}}},Ue=k(Pc1);var iG=v(X0(),1);var QZ={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},TQ={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var jJ=v(u(),1),pG=v(D1(),1);var Ic1="@sentry/instrumentation-hono",Sc1="0.0.1";class cO extends pG.InstrumentationBase{constructor(Z={}){super(Ic1,Sc1,Z)}init(){return[new pG.InstrumentationNodeModuleDefinition("hono",[">=4.0.0 <5"],(Z)=>this._patch(Z))]}_patch(Z){let J=this;class $ extends Z.Hono{constructor(...X){super(...X);J._wrap(this,"get",J._patchHandler()),J._wrap(this,"post",J._patchHandler()),J._wrap(this,"put",J._patchHandler()),J._wrap(this,"delete",J._patchHandler()),J._wrap(this,"options",J._patchHandler()),J._wrap(this,"patch",J._patchHandler()),J._wrap(this,"all",J._patchHandler()),J._wrap(this,"on",J._patchOnHandler()),J._wrap(this,"use",J._patchMiddlewareHandler())}}try{Z.Hono=$}catch{return{...Z,Hono:$}}return Z}_patchHandler(){let Z=this;return function(J){return function(...X){if(typeof X[0]==="string"){let Y=X[0];if(X.length===1)return J.apply(this,[Y]);let Q=X.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,X.map((Y)=>Z._wrapHandler(Y)))}}}_patchOnHandler(){let Z=this;return function(J){return function(...X){let Y=X.slice(2);return J.apply(this,[...X.slice(0,2),...Y.map((Q)=>Z._wrapHandler(Q))])}}}_patchMiddlewareHandler(){let Z=this;return function(J){return function(...X){if(typeof X[0]==="string"){let Y=X[0];if(X.length===1)return J.apply(this,[Y]);let Q=X.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,X.map((Y)=>Z._wrapHandler(Y)))}}}_wrapHandler(Z){let J=this;return function($,X){if(!J.isEnabled())return Z.apply(this,[$,X]);let Y=$.req.path,Q=J.tracer.startSpan(Y);return jJ.context.with(jJ.trace.setSpan(jJ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[$,X]);if(t4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[QZ.HONO_TYPE]:z,[QZ.HONO_NAME]:z===TQ.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[QZ.HONO_TYPE]:K,[QZ.HONO_NAME]:K===TQ.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),W}},()=>Q.end(),(W)=>{J._handleError(Q,W),Q.end()})})}}_safeExecute(Z,J,$){try{let X=Z();if(t4(X))X.then(()=>J(),(Y)=>$(Y));else J();return X}catch(X){throw $(X),X}}_determineHandlerType(Z){return Z===void 0?TQ.MIDDLEWARE:TQ.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:jJ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var Le="Hono";function yc1(Z){let J=X1(Z).data,$=J[QZ.HONO_TYPE];if(J[U1]||!$)return;Z.setAttributes({[W1]:"auto.http.otel.hono",[U1]:`${$}.hono`});let X=J[QZ.HONO_NAME];if(typeof X==="string")Z.updateName(X);if(d1()===y6()){u0&&R.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[iG.ATTR_HTTP_ROUTE],Q=J[iG.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")d1().setTransactionName(`${Q} ${Y}`)}var De=s(Le,()=>new cO({responseHook:(Z)=>{yc1(Z)}})),kc1=()=>{return{name:Le,setupOnce(){De()}}},Oe=k(kc1);var me=v(ge(),1),ue=v(X0(),1);var de="Koa",ce=s(de,me.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,$){Y0(J,"auto.http.otel.koa");let X=X1(J).data,Y=X["koa.type"];if(Y)J.setAttribute(U1,`${Y}.koa`);let Q=X["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(d1()===y6()){u0&&R.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=X[ue.ATTR_HTTP_ROUTE],K=$.context?.request?.method?.toUpperCase()||"GET";if(W)d1().setTransactionName(`${K} ${W}`)}}}),pc1=(Z={})=>{return{name:de,setupOnce(){ce(Z)}}},le=k(pc1);var V11=v(H11(),1);var F11="Connect",B11=s(F11,()=>new V11.ConnectInstrumentation),Ql1=()=>{return{name:F11,setupOnce(){B11()}}},U11=k(Ql1);var y11=v(S11(),1);var Al1=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),k11="Tedious",x11=s(k11,()=>new y11.TediousInstrumentation({})),Tl1=()=>{let Z;return{name:k11,setupOnce(){let J=x11();Z=i3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let{description:X,data:Y}=X1($);if(!X||Y["db.system"]!=="mssql")return;let Q=X.split(" ")[0]||"";if(Al1.has(Q))$.setAttribute(W1,"auto.db.otel.tedious")}))}}},v11=k(Tl1);var p11=v(l11(),1);var i11="GenericPool",n11=s(i11,()=>new p11.GenericPoolInstrumentation({})),Rl1=()=>{let Z;return{name:i11,setupOnce(){let J=n11();Z=i3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let Y=X1($).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")$.setAttribute(W1,"auto.db.otel.generic_pool")}))}}},a11=k(Rl1);var _01=v(O01(),1);var w01="Amqplib",Qp1={consumeEndHook:(Z)=>{Y0(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{Y0(Z,"auto.amqplib.otel.publisher")}},A01=s(w01,()=>new _01.AmqplibInstrumentation(Qp1)),Wp1=()=>{return{name:w01,setupOnce(){A01()}}},T01=k(Wp1);var CQ="VercelAI";var JH=v(D1(),1);var Kp1=[">=3.0.0 <7"],M01=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function zp1(Z){if(typeof Z!=="object"||Z===null)return!1;let J=Z;return"type"in J&&"error"in J&&"toolName"in J&&"toolCallId"in J&&J.type==="tool-error"&&J.error instanceof Error}function Gp1(Z){if(typeof Z!=="object"||Z===null||!("content"in Z))return;let J=Z;if(!Array.isArray(J.content))return;for(let $ of J.content)if(zp1($)){let X=F2($.toolCallId);if(X){let Y=X.spanContext();D6((Q)=>{Q.setContext("trace",{trace_id:Y.traceId,span_id:Y.spanId}),Q.setTag("vercel.ai.tool.name",$.toolName),Q.setTag("vercel.ai.tool.callId",$.toolCallId),Q.setLevel("error"),O1($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),B2($.toolCallId)}else D6((Y)=>{Y.setTag("vercel.ai.tool.name",$.toolName),Y.setTag("vercel.ai.tool.callId",$.toolCallId),Y.setLevel("error"),O1($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function Hp1(Z,J,$,X){let Y=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:$===!0?!0:X,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:$===!0?!0:X;return{recordInputs:Y,recordOutputs:Q}}class qQ extends JH.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",u1,Z);qQ.prototype.__init.call(this),qQ.prototype.__init2.call(this)}init(){return new JH.InstrumentationNodeModuleDefinition("ai",Kp1,this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach(($)=>$()),this._callbacks=[];let J=($)=>{return new Proxy($,{apply:(X,Y,Q)=>{let W=Q[0].experimental_telemetry||{},K=W.isEnabled,z=p(),G=z?.getIntegrationByName(CQ),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=Hp1(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},k6(()=>Reflect.apply(X,Y,Q),(U)=>{if(U&&typeof U==="object")Z4(U,"_sentry_active_span",M5())},()=>{},(U)=>{Gp1(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let $ of M01)Z[$]=J(Z[$]);return Z}else{let $=M01.reduce((X,Y)=>{return X[Y]=J(Z[Y]),X},{});return{...Z,...$}}}}var j01=s(CQ,()=>new qQ({}));function Vp1(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var Fp1=(Z={})=>{let J;return{name:CQ,options:Z,setupOnce(){J=j01()},afterAllSetup($){if(Z.force??Vp1($))jz($);else J?.callWhenPatched(()=>jz($))}}},N01=k(Fp1);var $H=v(D1(),1);var Bp1=[">=4.0.0 <7"];class z_ extends $H.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",u1,Z)}init(){return new $H.InstrumentationNodeModuleDefinition("openai",Bp1,this._patch.bind(this))}_patch(Z){let J=Z;return J=this._patchClient(J,"OpenAI"),J=this._patchClient(J,"AzureOpenAI"),J}_patchClient(Z,J){let $=Z[J];if(!$)return Z;let X=this.getConfig(),Y=function(...Q){if(KJ(c7))return Reflect.construct($,Q);let W=Reflect.construct($,Q),K=p(),z=Boolean(K?.getOptions().sendDefaultPii),G=X.recordInputs??z,H=X.recordOutputs??z;return Cz(W,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(Y,$),Object.setPrototypeOf(Y.prototype,$.prototype);for(let Q of Object.getOwnPropertyNames($))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor($,Q);if(W)Object.defineProperty(Y,Q,W)}try{Z[J]=Y}catch(Q){Object.defineProperty(Z,J,{value:Y,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===$)try{Z.default=Y}catch(Q){Object.defineProperty(Z,"default",{value:Y,writable:!0,configurable:!0,enumerable:!0})}return Z}}var R01=s(c7,(Z)=>new z_(Z)),Up1=(Z={})=>{return{name:c7,setupOnce(){R01(Z)}}},C01=k(Up1);var XH=v(D1(),1);var Lp1=[">=0.19.2 <1.0.0"];class G_ extends XH.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",u1,Z)}init(){return new XH.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",Lp1,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,$=this.getConfig(),X=function(...Y){if(KJ(l7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=p(),K=Boolean(W?.getOptions().sendDefaultPii),z=$.recordInputs??K,G=$.recordOutputs??K;return D2(Q,{recordInputs:z,recordOutputs:G})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let Q=Object.getOwnPropertyDescriptor(J,Y);if(Q)Object.defineProperty(X,Y,Q)}try{Z.Anthropic=X}catch(Y){Object.defineProperty(Z,"Anthropic",{value:X,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===J)try{Z.default=X}catch(Y){Object.defineProperty(Z,"default",{value:X,writable:!0,configurable:!0,enumerable:!0})}return Z}}var q01=s(l7,(Z)=>new G_(Z)),Dp1=(Z={})=>{return{name:l7,options:Z,setupOnce(){q01(Z)}}},E01=k(Dp1);var EX=v(D1(),1);var P01=[">=0.10.0 <2"];class H_ extends EX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",u1,Z)}init(){return new EX.InstrumentationNodeModuleDefinition("@google/genai",P01,(J)=>this._patch(J),(J)=>J,[new EX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",P01,(J)=>this._patch(J),(J)=>J)])}_patch(Z){let J=Z.GoogleGenAI,$=this.getConfig();if(typeof J!=="function")return Z;let X=function(...Y){if(KJ(p7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=p(),K=Boolean(W?.getOptions().sendDefaultPii),z=$,G=z?.recordInputs??K,H=z?.recordOutputs??K;return A2(Q,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(X,J),Object.setPrototypeOf(X.prototype,J.prototype);for(let Y of Object.getOwnPropertyNames(J))if(!["length","name","prototype"].includes(Y)){let Q=Object.getOwnPropertyDescriptor(J,Y);if(Q)Object.defineProperty(X,Y,Q)}return q3(Z,"GoogleGenAI",X),Z}}var I01=s(p7,(Z)=>new H_(Z)),Op1=(Z={})=>{return{name:p7,setupOnce(){I01(Z)}}},S01=k(Op1);var zZ=v(D1(),1);var YH=[">=0.1.0 <2.0.0"];function _p1(Z,J){if(!Z)return[J];if(Array.isArray(Z)){if(Z.includes(J))return Z;return[...Z,J]}if(typeof Z==="object")return[Z,J];return Z}function wp1(Z,J,$){return new Proxy(Z,{apply(X,Y,Q){let K=Q[1];if(!K||typeof K!=="object"||Array.isArray(K))K={},Q[1]=K;let z=K.callbacks,G=_p1(z,J);return K.callbacks=G,Reflect.apply(X,Y,Q)}})}class V_ extends zZ.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",u1,Z)}init(){let Z=[],J=["@langchain/anthropic","@langchain/openai","@langchain/google-genai","@langchain/mistralai","@langchain/google-vertexai","@langchain/groq"];for(let $ of J)Z.push(new zZ.InstrumentationNodeModuleDefinition($,YH,this._patch.bind(this),(X)=>X,[new zZ.InstrumentationNodeModuleFile(`${$}/dist/index.cjs`,YH,this._patch.bind(this),(X)=>X)]));return Z.push(new zZ.InstrumentationNodeModuleDefinition("langchain",YH,this._patch.bind(this),($)=>$,[new zZ.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",YH,this._patch.bind(this),($)=>$)])),Z}_patch(Z){iL([c7,l7,p7]);let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X?.recordInputs??$,Q=X?.recordOutputs??$,W=Ez({recordInputs:Y,recordOutputs:Q});return this._patchRunnableMethods(Z,W),Z}_patchRunnableMethods(Z,J){let $=["ChatAnthropic","ChatOpenAI","ChatGoogleGenerativeAI","ChatMistralAI","ChatVertexAI","ChatGroq","ConfigurableModel"],X=Z.universal_exports??Z,Y=Object.values(X).find((K)=>{return typeof K==="function"&&$.includes(K.name)});if(!Y)return;let Q=Y.prototype,W=["invoke","stream","batch"];for(let K of W){let z=Q[K];if(typeof z==="function")Q[K]=wp1(z,J)}}}var y01=s(qz,(Z)=>new V_(Z)),Ap1=(Z={})=>{return{name:qz,setupOnce(){y01(Z)}}},k01=k(Ap1);var PX=v(D1(),1);var x01=[">=0.0.0 <2.0.0"];class F_ extends PX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",u1,Z)}init(){return new PX.InstrumentationNodeModuleDefinition("@langchain/langgraph",x01,this._patch.bind(this),(J)=>J,[new PX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",x01,this._patch.bind(this),(J)=>J)])}_patch(Z){let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X.recordInputs??$,Q=X.recordOutputs??$,W={recordInputs:Y,recordOutputs:Q};if(Z.StateGraph&&typeof Z.StateGraph==="function"){let K=Z.StateGraph;K.prototype.compile=j2(K.prototype.compile,W)}return Z}}var v01=s(Pz,(Z)=>new F_(Z)),Tp1=(Z={})=>{return{name:Pz,setupOnce(){v01(Z)}}},h01=k(Tp1);var l01=v(D1(),1);var y9=v(u(),1),k9=v(D1(),1),_8=v(X0(),1);import*as b01 from"net";function g01(Z,J,$,X,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{k9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;y9.diag.error(V?.message)},!0)};let z=new k9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>f01(H,$,X,Z,W)),G=["@firebase/firestore/dist/lite/index.node.cjs.js","@firebase/firestore/dist/lite/index.node.mjs.js","@firebase/firestore/dist/lite/index.rn.esm2017.js","@firebase/firestore/dist/lite/index.cjs.js"];for(let H of G)z.files.push(new k9.InstrumentationNodeModuleFile(H,J,(V)=>f01(V,$,X,Z,W),(V)=>m01(V,X)));return z}function f01(Z,J,$,X,Y){return m01(Z,$),J(Z,"addDoc",Mp1(X,Y)),J(Z,"getDocs",Np1(X,Y)),J(Z,"setDoc",Rp1(X,Y)),J(Z,"deleteDoc",jp1(X,Y)),Z}function m01(Z,J){for(let $ of["addDoc","getDocs","setDoc","deleteDoc"])if(k9.isWrapped(Z[$]))J(Z,$);return Z}function Mp1(Z,J){return function(X){return function(Y,Q){let W=WH(Z,"addDoc",Y);return J(W),QH(W,()=>{return X(Y,Q)})}}}function jp1(Z,J){return function(X){return function(Y){let Q=WH(Z,"deleteDoc",Y.parent||Y);return J(Q),QH(Q,()=>{return X(Y)})}}}function Np1(Z,J){return function(X){return function(Y){let Q=WH(Z,"getDocs",Y);return J(Q),QH(Q,()=>{return X(Y)})}}}function Rp1(Z,J){return function(X){return function(Y,Q,W){let K=WH(Z,"setDoc",Y.parent||Y);return J(K),QH(K,()=>{return typeof W<"u"?X(Y,Q,W):X(Y,Q)})}}}function QH(Z,J){return y9.context.with(y9.trace.setSpan(y9.context.active(),Z),()=>{return k9.safeExecuteInTheMiddle(()=>{return J()},($)=>{if($)Z.recordException($);Z.end()},!0)})}function WH(Z,J,$){let X=Z.startSpan(`${J} ${$.path}`,{kind:y9.SpanKind.CLIENT});return qp1(X,$),X.setAttribute(_8.ATTR_DB_OPERATION_NAME,J),X}function Cp1(Z){let J,$;if(typeof Z.host==="string")if(Z.host.startsWith("[")){if(Z.host.endsWith("]"))J=Z.host.replace(/^\[|\]$/g,"");else if(Z.host.includes("]:")){let X=Z.host.lastIndexOf(":");if(X!==-1)J=Z.host.slice(1,X).replace(/^\[|\]$/g,""),$=Z.host.slice(X+1)}}else if(b01.isIPv6(Z.host))J=Z.host;else{let X=Z.host.lastIndexOf(":");if(X!==-1)J=Z.host.slice(0,X),$=Z.host.slice(X+1);else J=Z.host}return{address:J,port:$?parseInt($,10):void 0}}function qp1(Z,J){let $=J.firestore.app,X=$.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[_8.ATTR_DB_COLLECTION_NAME]:J.path,[_8.ATTR_DB_NAMESPACE]:$.name,[_8.ATTR_DB_SYSTEM_NAME]:"firebase.firestore","firebase.firestore.type":J.type,"firebase.firestore.options.projectId":X.projectId,"firebase.firestore.options.appId":X.appId,"firebase.firestore.options.messagingSenderId":X.messagingSenderId,"firebase.firestore.options.storageBucket":X.storageBucket},{address:K,port:z}=Cp1(Q);if(K)W[_8.ATTR_SERVER_ADDRESS]=K;if(z)W[_8.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var k5=v(u(),1),x9=v(D1(),1);function u01(Z,J,$,X,Y){let Q=()=>{},W=()=>{},K=Y.functions?.errorHook,z=Y.functions?.requestHook,G=Y.functions?.responseHook;if(typeof G==="function")W=(F,B)=>{x9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;k5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{x9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;k5.diag.error(B?.message)},!0)};let H=new x9.InstrumentationNodeModuleDefinition("firebase-functions",J);return[{name:"firebase-functions/lib/v2/providers/https.js",triggerType:"function"},{name:"firebase-functions/lib/v2/providers/firestore.js",triggerType:"firestore"},{name:"firebase-functions/lib/v2/providers/scheduler.js",triggerType:"scheduler"},{name:"firebase-functions/lib/v2/storage.js",triggerType:"storage"}].forEach(({name:F,triggerType:B})=>{H.files.push(new x9.InstrumentationNodeModuleFile(F,J,(U)=>Ep1(U,$,X,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>d01(U,X)))}),H}function Q6(Z,J,$){return function(Y){return function(...Q){let W=typeof Q[0]==="function"?Q[0]:Q[1],K=typeof Q[0]==="function"?void 0:Q[0];if(!W)return Y.call(this,...Q);let z=async function(...G){let H=process.env.FUNCTION_TARGET||process.env.K_SERVICE||"unknown",V=Z.startSpan(`firebase.function.${$}`,{kind:k5.SpanKind.SERVER}),F={"faas.name":H,"faas.trigger":$,"faas.provider":"firebase"};if(process.env.GCLOUD_PROJECT)F["cloud.project_id"]=process.env.GCLOUD_PROJECT;if(process.env.EVENTARC_CLOUD_EVENT_SOURCE)F["cloud.event_source"]=process.env.EVENTARC_CLOUD_EVENT_SOURCE;return V.setAttributes(F),J?.requestHook?.(V),k5.context.with(k5.trace.setSpan(k5.context.active(),V),async()=>{let B,U;try{U=await W.apply(this,G)}catch(L){B=L}if(J?.responseHook?.(V,B),B)V.recordException(B);if(V.end(),B)throw await J?.errorHook?.(V,B),B;return U})};if(K)return Y.call(this,K,z);else return Y.call(this,z)}}}function Ep1(Z,J,$,X,Y,Q){switch(d01(Z,$),Q){case"function":J(Z,"onRequest",Q6(X,Y,"http.request")),J(Z,"onCall",Q6(X,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",Q6(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",Q6(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",Q6(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",Q6(X,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",Q6(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",Q6(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",Q6(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",Q6(X,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",Q6(X,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",Q6(X,Y,"storage.object.finalized")),J(Z,"onObjectArchived",Q6(X,Y,"storage.object.archived")),J(Z,"onObjectDeleted",Q6(X,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",Q6(X,Y,"storage.object.metadataUpdated"));break}return Z}function d01(Z,J){let $=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let X of $)if(x9.isWrapped(Z[X]))J(Z,X);return Z}var c01={},Pp1=[">=3.0.0 <5"],Ip1=[">=6.0.0 <7"];class B_ extends l01.InstrumentationBase{constructor(Z=c01){super("@sentry/instrumentation-firebase",u1,Z)}setConfig(Z={}){super.setConfig({...c01,...Z})}init(){let Z=[];return Z.push(g01(this.tracer,Pp1,this._wrap,this._unwrap,this.getConfig())),Z.push(u01(this.tracer,Ip1,this._wrap,this._unwrap,this.getConfig())),Z}}var p01="Firebase",Sp1={firestoreSpanCreationHook:(Z)=>{Y0(Z,"auto.firebase.otel.firestore"),Z.setAttribute(U1,"db.query")},functions:{requestHook:(Z)=>{Y0(Z,"auto.firebase.otel.functions"),Z.setAttribute(U1,"http.request")},errorHook:async(Z,J)=>{if(J)O1(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await Kz(2000)}}},i01=s(p01,()=>new B_(Sp1)),yp1=()=>{return{name:p01,setupOnce(){i01()}}},n01=k(yp1);function EQ(){return[ai(),vn(),Ra(),Oe(),ko(),Xr(),jr(),pr(),as(),qt(),ct(),Ue(),le(),U11(),v11(),a11(),ta(),T01(),Bo(),k01(),h01(),N01(),C01(),E01(),S01(),yt(),n01()]}var IX=v(u(),1);var SX=v(X0(),1);var U_=1e6;function a01(Z,J={}){if(Z.getOptions().debug)TD();let[$,X]=kp1(Z,J);Z.traceProvider=$,Z.asyncLocalStorageLookup=X}function kp1(Z,J={}){let $=new rz({sampler:new WD(Z),resource:y3().merge(lz({[SX.ATTR_SERVICE_NAME]:"node",[SX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[SX.ATTR_SERVICE_VERSION]:u1})),forceFlushTimeoutMillis:500,spanProcessors:[new QD({timeout:xp1(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});IX.trace.setGlobalTracerProvider($),IX.propagation.setGlobalPropagator(new YD);let X=new XG;return IX.context.setGlobalContextManager(X),[$,X.getAsyncLocalStorageLookup()]}function xp1(Z){if(Z==null)return;if(Z>U_)return u0&&R.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${U_}`),U_;else if(Z<=0||Number.isNaN(Z)){u0&&R.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function o01(){return zG().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(a3(),r3())}function r01(Z){return[...o01(),...P0(Z)?EQ():[]]}function L_(Z={}){return vp1(Z,r01)}function vp1(Z={},J){_9(Z,"node");let $=SD({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if($&&!Z.skipOpenTelemetrySetup)a01($,{spanProcessors:Z.openTelemetrySpanProcessors}),GG();return $}import*as J41 from"os";var hp1="BunServer",fp1=()=>{return{name:hp1,setupOnce(){bp1()}}},e01=k(fp1),s01=!1;function bp1(){if(s01)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,$){t01($[0]);let X=Z.apply(J,$),Y=X.reload.bind(X);return X.reload=(Q)=>{return t01(Q),Y(Q)},X}}),s01=!0}function t01(Z){gp1(Z),mp1(Z)}function gp1(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,$,X){return D_(J,$,X)}})}function mp1(Z){if(!Z.routes)return;if(typeof Z.routes!=="object")return;Object.keys(Z.routes).forEach((J)=>{let $=Z.routes[J];if(typeof $==="function")Z.routes[J]=new Proxy($,{apply:(X,Y,Q)=>{return D_(X,Y,Q,J)}});if($ instanceof Response)return;if(typeof $==="object")Object.entries($).forEach(([X,Y])=>{if(typeof Y==="function")Z.routes[J][X]=new Proxy(Y,{apply:(Q,W,K)=>{return D_(Q,W,K,J)}})})})}function D_(Z,J,$,X){return rZ((Y)=>{let Q=$[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,$);let K=L3(Q.url),z=up1(K,Q),G=K?.pathname||"/";if(Q.params){if(Object.keys(Q.params).forEach((H)=>{z[`url.path.parameter.${H}`]=Q.params[H]}),X)z[E0]="route",z["url.template"]=X,G=X}if(X?.endsWith("/*"))z[E0]="route",z["url.template"]=X,G=X;return Object.assign(z,v$(Q.headers.toJSON(),p()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),Yz({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>h6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,$);if(V?.status)dK(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw O1(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function up1(Z,J){let $={[W1]:"auto.http.bun.serve",[AL]:J.method||"GET",[E0]:"url"};if(Z){if(Z.search)$["url.query"]=Z.search;if(Z.hash)$["url.fragment"]=Z.hash;if(Z.pathname)$["url.path"]=Z.pathname;if(!aL(Z)){if($["url.full"]=Z.href,Z.port)$["url.port"]=Z.port;if(Z.protocol)$["url.scheme"]=Z.protocol;if(Z.hostname)$["url.domain"]=Z.hostname}}return $}function Z41(Z){function J($){let X={body:$.body,method:"POST",headers:Z.headers};try{return S7(()=>{return fetch(Z.url,X).then((Y)=>{return{statusCode:Y.status,headers:{"x-sentry-rate-limits":Y.headers.get("X-Sentry-Rate-Limits"),"retry-after":Y.headers.get("Retry-After")}}})})}catch(Y){return Promise.reject(Y)}}return WJ(Z,J)}function $41(Z){return[f$(),h$(),b$(),g$(),m$(),a3(),r3(),HX(),VX(),zX(),KX(),GX(),e01(),...P0(Z)?EQ():[]]}function O_(Z={}){_9(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||J41.hostname()};if(J.transport=J.transport||Z41,J.defaultIntegrations===void 0)J.defaultIntegrations=$41(J);return L_(J)}O_({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as X41}from"fs";import{join as Y41}from"path";function O0(){return"3.3.0-beta.2"}function __(Z){let[J,$]=Z.split("-"),X=(J||"0.0.0").split(".").map(Number),Y=null,Q=0;if($){let W=$.match(/^([a-z]+)\.?(\d+)?$/i);if(W)Y=W[1]||null,Q=parseInt(W[2]||"0",10);else Y=$}return{major:X[0]||0,minor:X[1]||0,patch:X[2]||0,preRelease:Y,preReleaseNum:Q}}function v9(Z){let J=__(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function PQ(Z,J){try{let $=__(Z),X=__(J);if($.major>X.major)return!1;if($.major<X.major)return!1;if(X.preRelease&&!$.preRelease)return!1;if(!X.preRelease&&$.preRelease)return!1;if(X.preRelease&&$.preRelease){if($.minor<X.minor)return!1;if($.minor>X.minor)return!0;if($.patch>X.patch)return!0;if($.patch<X.patch)return!1;return $.preReleaseNum>X.preReleaseNum}if($.minor>X.minor)return!0;if($.minor<X.minor)return!1;if($.patch>X.patch)return!0;return!1}catch($){return!1}}import{parseArgs as cp1}from"util";var lp1={debug:{type:"boolean",short:"d",default:!1,description:"Enable debug logging"},"mqtt-port":{type:"string",default:"8884",description:"MQTT broker port"},"terminal-port":{type:"string",default:"3001",description:"Terminal server port"},"router-port":{type:"string",default:"8883",description:"Router port"},username:{type:"string",short:"u",description:"MQTT broker username (required)"},password:{type:"string",short:"p",description:"MQTT broker password (required)"},"ngrok-token":{type:"string",description:"ngrok authentication token (optional)"},"ngrok-domain":{type:"string",description:"ngrok static domain (optional, paid plan)"},"no-auto-update":{type:"boolean",default:!1,description:"Disable auto-update checking"},"terminal-audit":{type:"boolean",default:!1,description:"Enable terminal input audit logging (logs commands, not output)"},"auto-update-check-interval":{type:"string",default:"60",description:"Auto-update check interval in minutes (default: 60)"},help:{type:"boolean",short:"h",default:!1,description:"Show help message"},version:{type:"boolean",short:"v",default:!1,description:"Show version"}};function Q41(){let Z=cp1({options:lp1,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${O0()}`),process.exit(0);if(Z.values.help)pp1(),process.exit(0);let J=process.env.CCC_USERNAME||Z.values.username,$=process.env.CCC_PASSWORD||Z.values.password,X=process.env.CCC_NGROK_TOKEN||Z.values["ngrok-token"],Y=process.env.CCC_NGROK_DOMAIN||Z.values["ngrok-domain"];if(!J||!$)console.error("\x1B[31mError: Authentication credentials are required.\x1B[0m"),console.error(""),console.error("These credentials secure the MQTT communication between the app and backend."),console.error(""),console.error("You can provide them via:"),console.error(""),console.error(" Environment variables (recommended for security):"),console.error(" export CCC_USERNAME=myuser"),console.error(" export CCC_PASSWORD=mypassword"),console.error(" export CCC_NGROK_TOKEN=your_token # optional"),console.error(" export CCC_NGROK_DOMAIN=your_domain # optional"),console.error(" ccc"),console.error(""),console.error(" Or CLI arguments:"),console.error(" ccc --username myuser --password mypassword"),console.error(" ccc -u myuser -p mypassword"),console.error(""),process.exit(1);return{debug:Z.values.debug,mqttPort:parseInt(Z.values["mqtt-port"],10),terminalPort:parseInt(Z.values["terminal-port"],10),routerPort:parseInt(Z.values["router-port"],10),username:J,password:$,ngrokToken:X,ngrokDomain:Y,autoUpdate:!Z.values["no-auto-update"],autoUpdateCheckInterval:parseInt(Z.values["auto-update-check-interval"],10),terminalAudit:Z.values["terminal-audit"]}}function pp1(){console.log(`
55
55
  Backend v2 - Clean modular architecture
56
56
 
57
57
  Usage:
@@ -2339,7 +2339,7 @@ Please ensure librust_pty.so is available or use the install script.`)}}return x
2339
2339
  `);return}_.push(A)}if(_.length>0)V=Buffer.concat(_)}let F=new AbortController,B=setTimeout(()=>F.abort(),30000),U=await fetch(G,{method:Z.method||"GET",headers:H,body:V,signal:F.signal,redirect:"manual",tls:{rejectUnauthorized:!1}});clearTimeout(B),this.logger.debug("[Proxy Response]",{url:G,status:U.status,contentType:U.headers.get("content-type"),contentLength:U.headers.get("content-length")});let L={};for(let[O,_]of U.headers.entries())if(!KX0.has(O.toLowerCase()))L[O]=_;if(L["content-encoding"]="identity",U.body){let O=U.headers.get("content-length");if(!O){let w=await U.arrayBuffer();if(w.byteLength>104857600){if(!J.headersSent)J.writeHead(502,{"Content-Type":"text/plain"});if(!J.writableEnded)J.end(`Response too large
2340
2340
  `);return}let A=Buffer.from(w);L["content-length"]=String(A.length),J.writeHead(U.status,L),J.end(A)}else{L["content-length"]=O,J.writeHead(U.status,L);let _=U.body.getReader();try{while(!0){let{done:w,value:A}=await _.read();if(w)break;if(!J.write(A))await new Promise((T)=>J.once("drain",T))}}finally{_.releaseLock()}J.end()}}else J.writeHead(U.status,L),J.end()}catch(V){let F=V;if(F.name==="AbortError"){if(this.logger.error("Proxy timeout",{target:$.target,path:K}),!J.headersSent)J.writeHead(504,{"Content-Type":"text/plain"});if(!J.writableEnded)J.end(`Gateway Timeout
2341
2341
  `);return}if(this.logger.error("HTTP proxy error",{error:F.message,target:$.target,path:K,method:Z.method,code:F.code}),!J.headersSent)J.writeHead(502,{"Content-Type":"text/plain"});if(!J.writableEnded)J.end(`Bad Gateway - Unable to connect to backend service
2342
- `)}}async stop(){if(!this.server&&!this.wss)return;return new Promise((Z)=>{for(let J of this.activeBrokerSockets)try{J.removeAllListeners(),J.destroy()}catch($){this.logger.debug("Error destroying broker socket",{error:$})}if(this.activeBrokerSockets.clear(),this.wss)this.wss.clients?.forEach((J)=>{J.removeAllListeners(),J.close(1000,"Server shutting down")}),this.wss.close();this.wss=null;for(let J of this.activeConnections)try{J.destroy()}catch{}if(this.activeConnections.clear(),this.defaultRoute=null,this.server){let J=setTimeout(()=>{this.logger.warn("Server close timeout, forcing shutdown"),this.running=!1,this.server=null,Z()},500);this.server.close(()=>{clearTimeout(J),this.logger.debug("Router stopped"),this.running=!1,this.server=null,Z()})}else Z()})}getStatus(){return{name:"Router",running:this.running,port:this.config.port,startedAt:this.startedAt,routes:this.routes}}addRoute(Z,J,$){let X=this.routes.findIndex((Y)=>Y.path===Z);if(X>=0&&this.routes[X])this.routes[X].target=J,this.routes[X].ssl=$;else this.routes.push({path:Z,target:J,ssl:$});if(this.config.debug)this.logger.debug(`Route added: ${Z} -> ${J}${$?" (ssl)":""}`)}removeRoute(Z){let J=this.routes.findIndex(($)=>$.path===Z);if(J>=0){if(this.routes.splice(J,1),this.config.debug)this.logger.debug(`Route removed: ${Z}`)}}setDefaultRoute(Z,J){this.defaultRoute={path:"",target:Z,ssl:J},this.logger.debug(`Default route set -> ${Z}${J?" (ssl)":""}`)}clearDefaultRoute(){this.defaultRoute=null,this.logger.debug("Default route cleared")}handleWebSocketUpgrade(Z,J,$,X){let Y=Z.url||"/";this.logger.debug("WebSocket upgrade request",{url:Y});let Q=this.findRoute(Y);if(!Q){this.logger.warn("WebSocket upgrade to unknown path",{url:Y}),J.destroy();return}X.handleUpgrade(Z,J,$,(W)=>{if(Y.startsWith("/mqtt"))this.bridgeWebSocketToTcp(W,Q);else this.bridgeWebSocketToWebSocket(W,Q,Y,Z)})}bridgeWebSocketToTcp(Z,J){let[$,X]=J.target.split(":"),Y=parseInt(X||"8883",10);this.logger.debug("WebSocket-to-TCP bridge established",{target:J.target});let Q=SQ1.connect(Y,$||"localhost",()=>{this.logger.debug("Connected to MQTT broker",{target:J.target})});this.activeBrokerSockets.add(Q),Z.on("message",(W)=>{if(!Q.destroyed&&Q.writable)Q.write(W);else this.logger.warn("Broker socket not writable")}),Q.on("data",(W)=>{Z.send(W,(K)=>{if(K)this.logger.error("Error sending WebSocket message",{error:K instanceof Error?K.message:String(K)})})}),Z.on("close",()=>{this.logger.debug("WebSocket client closed"),Q.destroy()}),Z.on("error",(W)=>{this.logger.error("WebSocket error",{error:W.message}),Q.destroy()}),Q.on("close",()=>{this.logger.debug("MQTT broker connection closed"),this.activeBrokerSockets.delete(Q),Z.close()}),Q.on("error",(W)=>{this.logger.error("MQTT broker error",{error:W.message,target:J.target}),this.activeBrokerSockets.delete(Q),Z.close()})}static WS_INTERNAL_HEADERS=new Set(["sec-websocket-key","sec-websocket-version","sec-websocket-extensions","sec-websocket-protocol","connection","upgrade"]);bridgeWebSocketToWebSocket(Z,J,$,X){let[Y,Q]=J.target.split(":"),W=parseInt(Q||"3001",10),K=Y||"localhost",G=`${J.ssl?"wss":"ws"}://${K}:${W}${$}`;this.logger.debug("WebSocket-to-WebSocket bridge connecting",{target:G});let H={};if(X)for(let[O,_]of Object.entries(X.headers)){if(_===void 0)continue;let w=O.toLowerCase();if(fW.WS_INTERNAL_HEADERS.has(w))continue;if(w==="host")H[O]=`${K}:${W}`;else H[O]=Array.isArray(_)?_.join(", "):_}let V=X?.headers["sec-websocket-protocol"]?.split(",").map((O)=>O.trim()).filter(Boolean)||[],F;try{let O={headers:H};if(V.length>0)O.protocols=V;if(J.ssl)O.tls={rejectUnauthorized:!1};F=new globalThis.WebSocket(G,O)}catch(O){this.logger.error(`WebSocket creation failed: ${O.message}`),Z.close();return}let B=[],U=!1,L=()=>{B.length=0};F.onopen=()=>{U=!0;while(B.length>0)F.send(B.shift())},Z.on("message",(O,_)=>{let w=_?O:typeof O==="string"?O:O.toString("utf-8");if(U&&F.readyState===globalThis.WebSocket.OPEN)F.send(w);else if(B.length<100)B.push(w)}),F.onmessage=(O)=>{if(Z.readyState===1)Z.send(O.data)},F.onerror=()=>{L(),Z.close()},F.onclose=()=>{L(),Z.close()},Z.on("close",()=>{if(L(),F.readyState<=globalThis.WebSocket.OPEN)F.close()}),Z.on("error",()=>{if(L(),F.readyState<=globalThis.WebSocket.OPEN)F.close()})}findRoute(Z){let J=Z.split("?")[0]||Z,$=this.routes.find((Y)=>Y.path===J);if($)return $;let X=this.routes.find((Y)=>J.startsWith(Y.path+"/")||J===Y.path);if(X)return X;return this.defaultRoute??void 0}}var bW=null;async function zX0(){if(!bW)try{bW=await import("../../lib/ngrok-loader.generated")}catch{bW=await import("@ngrok/ngrok")}return bW.default||bW}class hV{listener;tunnelUrl=null;running=!1;startedAt;config;name="CCC Ngrok Service";constructor(Z){this.config=Z}async start(){try{let Z=S();Z.debug("Starting ngrok tunnel",{port:this.config.routerPort,domain:this.config.domain||"(auto)"});let J={authtoken:this.config.authToken,addr:`localhost:${this.config.routerPort}`};if(this.config.domain)J.domain=this.config.domain;let $=await zX0();this.listener=await $.forward(J),this.tunnelUrl=this.listener?.url()??null,this.running=!0,this.startedAt=new Date;let X=this.tunnelUrl?.replace(/^https?:\/\//,"");Z.debug("ngrok tunnel established",{url:X,fullUrl:this.tunnelUrl})}catch(Z){let J=S(),$=Z instanceof Error?Z.message:String(Z);throw J.error("Failed to start ngrok tunnel",Z),Error(`ngrok tunnel failed: ${$}`)}}async stop(){try{let Z=S();if(!this.running)return;if(Z.debug("Stopping ngrok tunnel"),this.listener)await Promise.race([this.listener.close(),new Promise((J)=>{setTimeout(()=>{Z.warn("ngrok listener close timeout, forcing shutdown"),J()},3000)})]);this.running=!1,this.tunnelUrl=null,Z.debug("ngrok tunnel closed")}catch(Z){S().error("Error stopping ngrok tunnel",Z)}}getStatus(){return{name:this.name,running:this.running,active:this.isActive(),tunnelUrl:this.tunnelUrl?this.tunnelUrl.replace(/^https?:\/\//,""):void 0,routerPort:this.config.routerPort,startedAt:this.startedAt}}getUrl(){return this.tunnelUrl}isActive(){return!!this.listener&&!!this.tunnelUrl}}var $W1=v(JW1(),1);class mV{running=!1;startedAt;config;codesGenerated=0;name="CCC QR Code Service";constructor(Z){this.config=Z}async start(){try{let Z=S();Z.debug("QR Code Service starting"),this.running=!0,this.startedAt=new Date,this.display(),Z.debug("QR Code Service started")}catch(Z){throw S().error("Failed to start QR Code service",Z),this.running=!1,Z}}async stop(){try{let Z=S();if(!this.running)return;this.running=!1,Z.debug("QR Code Service stopped")}catch(Z){S().error("Error stopping QR Code service",Z)}}getStatus(){return{name:this.name,running:this.running,codesGenerated:this.codesGenerated,urls:{ipBased:this.config.ipBasedUrl,ngrok:this.config.ngrokUrl},startedAt:this.startedAt}}display(){let Z=S();try{if(this.codesGenerated=0,console.log(`
2342
+ `)}}async stop(){if(!this.server&&!this.wss)return;return new Promise((Z)=>{for(let J of this.activeBrokerSockets)try{J.removeAllListeners(),J.destroy()}catch($){this.logger.debug("Error destroying broker socket",{error:$})}if(this.activeBrokerSockets.clear(),this.wss)this.wss.clients?.forEach((J)=>{J.removeAllListeners(),J.close(1000,"Server shutting down")}),this.wss.close();this.wss=null;for(let J of this.activeConnections)try{J.destroy()}catch{}if(this.activeConnections.clear(),this.defaultRoute=null,this.server){let J=setTimeout(()=>{this.logger.warn("Server close timeout, forcing shutdown"),this.running=!1,this.server=null,Z()},500);this.server.close(()=>{clearTimeout(J),this.logger.debug("Router stopped"),this.running=!1,this.server=null,Z()})}else Z()})}getStatus(){return{name:"Router",running:this.running,port:this.config.port,startedAt:this.startedAt,routes:this.routes}}addRoute(Z,J,$){let X=this.routes.findIndex((Y)=>Y.path===Z);if(X>=0&&this.routes[X])this.routes[X].target=J,this.routes[X].ssl=$;else this.routes.push({path:Z,target:J,ssl:$});if(this.config.debug)this.logger.debug(`Route added: ${Z} -> ${J}${$?" (ssl)":""}`)}removeRoute(Z){let J=this.routes.findIndex(($)=>$.path===Z);if(J>=0){if(this.routes.splice(J,1),this.config.debug)this.logger.debug(`Route removed: ${Z}`)}}setDefaultRoute(Z,J){this.defaultRoute={path:"",target:Z,ssl:J},this.logger.debug(`Default route set -> ${Z}${J?" (ssl)":""}`)}clearDefaultRoute(){this.defaultRoute=null,this.logger.debug("Default route cleared")}mountForwardedPort(Z,J=!1){this.addRoute(`/p/${Z}`,`localhost:${Z}`,J)}unmountForwardedPort(Z){this.removeRoute(`/p/${Z}`)}handleWebSocketUpgrade(Z,J,$,X){let Y=Z.url||"/";this.logger.debug("WebSocket upgrade request",{url:Y});let Q=this.findRoute(Y);if(!Q){this.logger.warn("WebSocket upgrade to unknown path",{url:Y}),J.destroy();return}X.handleUpgrade(Z,J,$,(W)=>{if(Y.startsWith("/mqtt"))this.bridgeWebSocketToTcp(W,Q);else this.bridgeWebSocketToWebSocket(W,Q,Y,Z)})}bridgeWebSocketToTcp(Z,J){let[$,X]=J.target.split(":"),Y=parseInt(X||"8883",10);this.logger.debug("WebSocket-to-TCP bridge established",{target:J.target});let Q=SQ1.connect(Y,$||"localhost",()=>{this.logger.debug("Connected to MQTT broker",{target:J.target})});this.activeBrokerSockets.add(Q),Z.on("message",(W)=>{if(!Q.destroyed&&Q.writable)Q.write(W);else this.logger.warn("Broker socket not writable")}),Q.on("data",(W)=>{Z.send(W,(K)=>{if(K)this.logger.error("Error sending WebSocket message",{error:K instanceof Error?K.message:String(K)})})}),Z.on("close",()=>{this.logger.debug("WebSocket client closed"),Q.destroy()}),Z.on("error",(W)=>{this.logger.error("WebSocket error",{error:W.message}),Q.destroy()}),Q.on("close",()=>{this.logger.debug("MQTT broker connection closed"),this.activeBrokerSockets.delete(Q),Z.close()}),Q.on("error",(W)=>{this.logger.error("MQTT broker error",{error:W.message,target:J.target}),this.activeBrokerSockets.delete(Q),Z.close()})}static WS_INTERNAL_HEADERS=new Set(["sec-websocket-key","sec-websocket-version","sec-websocket-extensions","sec-websocket-protocol","connection","upgrade"]);bridgeWebSocketToWebSocket(Z,J,$,X){let[Y,Q]=J.target.split(":"),W=parseInt(Q||"3001",10),K=Y||"localhost",G=`${J.ssl?"wss":"ws"}://${K}:${W}${$}`;this.logger.debug("WebSocket-to-WebSocket bridge connecting",{target:G});let H={};if(X)for(let[O,_]of Object.entries(X.headers)){if(_===void 0)continue;let w=O.toLowerCase();if(fW.WS_INTERNAL_HEADERS.has(w))continue;if(w==="host")H[O]=`${K}:${W}`;else H[O]=Array.isArray(_)?_.join(", "):_}let V=X?.headers["sec-websocket-protocol"]?.split(",").map((O)=>O.trim()).filter(Boolean)||[],F;try{let O={headers:H};if(V.length>0)O.protocols=V;if(J.ssl)O.tls={rejectUnauthorized:!1};F=new globalThis.WebSocket(G,O)}catch(O){this.logger.error(`WebSocket creation failed: ${O.message}`),Z.close();return}let B=[],U=!1,L=()=>{B.length=0};F.onopen=()=>{U=!0;while(B.length>0)F.send(B.shift())},Z.on("message",(O,_)=>{let w=_?O:typeof O==="string"?O:O.toString("utf-8");if(U&&F.readyState===globalThis.WebSocket.OPEN)F.send(w);else if(B.length<100)B.push(w)}),F.onmessage=(O)=>{if(Z.readyState===1)Z.send(O.data)},F.onerror=()=>{L(),Z.close()},F.onclose=()=>{L(),Z.close()},Z.on("close",()=>{if(L(),F.readyState<=globalThis.WebSocket.OPEN)F.close()}),Z.on("error",()=>{if(L(),F.readyState<=globalThis.WebSocket.OPEN)F.close()})}findRoute(Z){let J=Z.split("?")[0]||Z,$=this.routes.find((Y)=>Y.path===J);if($)return $;let X=this.routes.find((Y)=>J.startsWith(Y.path+"/")||J===Y.path);if(X)return X;return this.defaultRoute??void 0}}var bW=null;async function zX0(){if(!bW)try{bW=await import("../../lib/ngrok-loader.generated")}catch{bW=await import("@ngrok/ngrok")}return bW.default||bW}class hV{listener;tunnelUrl=null;running=!1;startedAt;config;name="CCC Ngrok Service";constructor(Z){this.config=Z}async start(){try{let Z=S();Z.debug("Starting ngrok tunnel",{port:this.config.routerPort,domain:this.config.domain||"(auto)"});let J={authtoken:this.config.authToken,addr:`localhost:${this.config.routerPort}`};if(this.config.domain)J.domain=this.config.domain;let $=await zX0();this.listener=await $.forward(J),this.tunnelUrl=this.listener?.url()??null,this.running=!0,this.startedAt=new Date;let X=this.tunnelUrl?.replace(/^https?:\/\//,"");Z.debug("ngrok tunnel established",{url:X,fullUrl:this.tunnelUrl})}catch(Z){let J=S(),$=Z instanceof Error?Z.message:String(Z);throw J.error("Failed to start ngrok tunnel",Z),Error(`ngrok tunnel failed: ${$}`)}}async stop(){try{let Z=S();if(!this.running)return;if(Z.debug("Stopping ngrok tunnel"),this.listener)await Promise.race([this.listener.close(),new Promise((J)=>{setTimeout(()=>{Z.warn("ngrok listener close timeout, forcing shutdown"),J()},3000)})]);this.running=!1,this.tunnelUrl=null,Z.debug("ngrok tunnel closed")}catch(Z){S().error("Error stopping ngrok tunnel",Z)}}getStatus(){return{name:this.name,running:this.running,active:this.isActive(),tunnelUrl:this.tunnelUrl?this.tunnelUrl.replace(/^https?:\/\//,""):void 0,routerPort:this.config.routerPort,startedAt:this.startedAt}}getUrl(){return this.tunnelUrl}isActive(){return!!this.listener&&!!this.tunnelUrl}}var $W1=v(JW1(),1);class mV{running=!1;startedAt;config;codesGenerated=0;name="CCC QR Code Service";constructor(Z){this.config=Z}async start(){try{let Z=S();Z.debug("QR Code Service starting"),this.running=!0,this.startedAt=new Date,this.display(),Z.debug("QR Code Service started")}catch(Z){throw S().error("Failed to start QR Code service",Z),this.running=!1,Z}}async stop(){try{let Z=S();if(!this.running)return;this.running=!1,Z.debug("QR Code Service stopped")}catch(Z){S().error("Error stopping QR Code service",Z)}}getStatus(){return{name:this.name,running:this.running,codesGenerated:this.codesGenerated,urls:{ipBased:this.config.ipBasedUrl,ngrok:this.config.ngrokUrl},startedAt:this.startedAt}}display(){let Z=S();try{if(this.codesGenerated=0,console.log(`
2343
2343
  `),this.config.ipBasedUrl)this.displayQRCode(this.config.ipBasedUrl,this.config.username,this.config.password,!1,this.config.profileName),this.codesGenerated++,console.log("");if(this.config.ngrokUrl)this.displayQRCode(this.config.ngrokUrl,this.config.username,this.config.password,!0,this.config.profileName),this.codesGenerated++,console.log("");if(this.codesGenerated===0)Z.warn("No connection URLs available for QR codes");else Z.debug(`Displayed ${this.codesGenerated} QR code(s)`);console.log(`Press "q" to redisplay QR codes
2344
2344
  `)}catch(J){Z.error("Error displaying QR codes",J)}}updateConfig(Z){if(this.config={...this.config,...Z},this.running)this.display()}displayQRCode(Z,J,$,X,Y){let Q=Z.replace(/^https?:\/\//,""),W={serverUrl:Q,useSSL:X,profileName:Y};if(J)W.username=J;if($)W.password=$;let K=JSON.stringify(W);$W1.default.generate(K,{small:!0});let z=this.getLabel(Q,X);console.log(`${z}`),console.log(` Server: ${Q}`),console.log(` Profile: ${Y}`),console.log(` Username: ${J?`${J.substring(0,8)}...`:"(none)"}`),console.log(` Password: ${$?"***":"(none)"}`),console.log(` SSL/TLS: ${X?"Yes (wss)":"No (ws)"}`)}getLabel(Z,J){if(Z.includes("ngrok"))return"\uD83C\uDF10 REMOTE CONNECTION (ngrok)";return"\uD83D\uDCF1 LOCAL NETWORK CONNECTION"}}import{existsSync as dV,renameSync as GW1,unlinkSync as OX0,chmodSync as _X0,mkdirSync as wX0,readFileSync as AX0,writeFileSync as TX0}from"fs";import{join as gW}from"path";import{homedir as MX0}from"os";import{homedir as YW1}from"os";import{join as QW1,normalize as XW1}from"path";function KY(){{let J=XW1(process.execPath),$=XW1(QW1(YW1(),".local","bin")),X=J.toLowerCase().replace(/\\/g,"/"),Y=$.toLowerCase().replace(/\\/g,"/");if(X.startsWith(Y))return"binary";return"development"}let Z=process.argv[1]||"";if(Z.includes("node_modules")||Z.includes(".bun"))return"npm";return"development"}function WW1(){return QW1(YW1(),".local","bin")}function KW1(){let Z=process.platform==="win32"?"windows":process.platform==="darwin"?"darwin":"linux",J=process.arch==="arm64"?"arm64":"x64",$=process.platform==="win32"?".exe":"";return`ccc-${Z}-${J}${$}`}function zW1(){return process.platform==="win32"?"ccc.exe":"ccc"}var H0=S(),uV=gW(MX0(),".ccc"),bT=gW(uV,"update-tracking.json");function jX0(){if(!dV(uV))wX0(uV,{recursive:!0}),H0.debug("Created .ccc directory",{path:uV})}function NX0(){try{if(dV(bT)){let Z=AX0(bT,"utf-8");return JSON.parse(Z)}}catch(Z){H0.debug("Error reading update tracking file",{error:Z})}return{}}function RX0(Z){try{jX0(),TX0(bT,JSON.stringify(Z,null,2)),H0.debug("Updated tracking file",{tracking:Z})}catch(J){H0.error("Error writing update tracking file",{error:J})}}function HW1(Z,J){let $=NX0(),X=$.lastDownloadedVersion===Z&&$.installationType===J;if(X)H0.debug("Version already downloaded",{version:Z,installationType:J,lastDownloadTime:$.lastDownloadTime});return X}function VW1(Z,J){RX0({lastDownloadedVersion:Z,lastDownloadTime:new Date().toISOString(),installationType:J})}function FW1(Z){switch(Z){case"alpha":return"alpha";case"beta":return"beta";default:return"latest"}}async function mW(Z){let J=O0(),$=v9(J);H0.debug("Checking for updates",{currentVersion:J,releaseChannel:$,packageName:Z});try{let X=FW1($),Y=await fetch(`https://registry.npmjs.org/${Z}`,{headers:{Accept:"application/json"}});if(!Y.ok)return H0.warn("Failed to check for updates",{status:Y.status,statusText:Y.statusText}),{updateAvailable:!1,currentVersion:J,latestVersion:J,releaseChannel:$};let Q=await Y.json(),W=Q["dist-tags"]?.[X]||Q["dist-tags"]?.latest;if(H0.debug("NPM registry response",{distTags:Q["dist-tags"],requestedTag:X,latestVersion:W}),!W)return H0.warn("Could not determine latest version from npm registry"),{updateAvailable:!1,currentVersion:J,latestVersion:J,releaseChannel:$};let K=PQ(W,J);return H0.debug("Version comparison result",{currentVersion:J,latestVersion:W,updateAvailable:K,isNewer:PQ(W,J)}),H0.debug("Update check completed",{currentVersion:J,latestVersion:W,updateAvailable:K,releaseChannel:$,distTag:X}),{updateAvailable:K,currentVersion:J,latestVersion:W,releaseChannel:$}}catch(X){return H0.error("Error checking for updates",{error:X}),{updateAvailable:!1,currentVersion:J,latestVersion:J,releaseChannel:$}}}async function cV(Z,J){let $=O0(),X=v9($),Y=FW1(X);if(J&&HW1(J,"npm"))return H0.info("Update already downloaded, please restart to apply",{version:J}),!0;H0.debug("Starting package update",{packageName:Z,currentVersion:$,targetVersion:J,distTag:Y});try{let Q=Bun.spawn(["bun","install","-g",`${Z}@${Y}`],{stdout:"pipe",stderr:"pipe"}),W=await new Response(Q.stdout).text(),K=await new Response(Q.stderr).text(),z=await Q.exited;if(z!==0)return H0.error("Package update failed",{error:K,packageName:Z,exitCode:z}),!1;if(H0.debug("Package updated successfully",{packageName:Z,distTag:Y}),W)H0.debug("bun install output",{output:W.trim()});if(J)VW1(J,"npm");return!0}catch(Q){return H0.error("Package update error",{error:Q}),!1}}var fT="vishal-android-freak/ccc-releases";async function uW(){let Z=O0(),J=v9(Z);H0.debug("Checking for GitHub updates",{currentVersion:Z,releaseChannel:J,repo:fT});try{let $=J==="stable"?`https://api.github.com/repos/${fT}/releases/latest`:`https://api.github.com/repos/${fT}/releases?per_page=50`,X=await fetch($,{headers:{Accept:"application/vnd.github.v3+json"}});if(!X.ok)return H0.warn("Failed to fetch GitHub releases",{status:X.status,statusText:X.statusText}),{updateAvailable:!1,currentVersion:Z,latestVersion:Z,releaseChannel:J};let Y;if(J==="stable")Y=await X.json();else{let H=(await X.json()).filter((V)=>{if(!V.prerelease)return!1;let F=(V.tag_name||"").replace(/^v/,"");return v9(F)===J});if(H.length===0)return H0.debug("No matching prerelease found for channel",{releaseChannel:J}),{updateAvailable:!1,currentVersion:Z,latestVersion:Z,releaseChannel:J};Y=H.sort((V,F)=>{let B=(V.tag_name||"").replace(/^v/,""),U=(F.tag_name||"").replace(/^v/,"");return PQ(B,U)?-1:1})[0]}let Q=(Y.tag_name||"").replace(/^v/,""),W=KW1(),K=Y.assets?.find((G)=>G.name===W),z=PQ(Q,Z);return H0.debug("GitHub release check",{currentVersion:Z,latestVersion:Q,updateAvailable:z,binaryName:W,hasAsset:!!K,releaseChannel:J}),{updateAvailable:z,currentVersion:Z,latestVersion:Q,releaseChannel:J,downloadUrl:K?.browser_download_url}}catch($){return H0.error("Error checking GitHub releases",{error:$}),{updateAvailable:!1,currentVersion:Z,latestVersion:Z,releaseChannel:J}}}async function lV(Z,J){try{if(J&&HW1(J,"binary"))return H0.info("Update already downloaded, please restart to apply",{version:J}),!0;let $=WW1(),X=zW1(),Y=gW($,X),Q=gW($,`${X}.new`),W=gW($,`${X}.backup`);H0.info("Downloading binary update",{downloadUrl:Z,targetPath:Y,targetVersion:J});let K=await fetch(Z);if(!K.ok)throw Error(`Download failed: ${K.status} ${K.statusText}`);let z=await K.arrayBuffer();if(await Bun.write(Q,z),process.platform!=="win32")_X0(Q,493);if(dV(Y))GW1(Y,W);if(GW1(Q,Y),dV(W))OX0(W);if(J)VW1(J,"binary");return H0.info("Binary update installed successfully",{targetPath:Y,targetVersion:J}),!0}catch($){return H0.error("Binary update failed",{error:$}),!1}}class pV{name="CCC Auto-Update Service";config;running=!1;enabled=!1;logger=S();checkInterval=null;lastCheckTime;nextCheckTime;updateAvailable=!1;latestVersion;startedAt;installationType;downloadUrl;constructor(Z){this.config={checkIntervalMinutes:60,...Z},this.enabled=Z.enabled,this.installationType=KY()}async start(){try{if(this.logger.debug("Starting Auto-Update Service",{enabled:this.enabled,packageName:this.config.packageName,checkIntervalMinutes:this.config.checkIntervalMinutes}),!this.enabled){this.logger.info("Auto-Update Service disabled"),this.running=!1;return}this.running=!0,this.startedAt=new Date,this.logger.info("Performing initial update check"),await this.performUpdateCheck(),this.scheduleNextCheck(),this.logger.info("Auto-Update Service started",{nextCheckTime:this.nextCheckTime})}catch(Z){if(this.logger.error("Failed to start Auto-Update Service",Z),this.checkInterval)clearInterval(this.checkInterval),this.checkInterval=null;throw this.running=!1,Z}}async stop(){try{if(!this.running)return;if(this.checkInterval)clearInterval(this.checkInterval),this.checkInterval=null;this.running=!1,this.logger.debug("Auto-Update Service stopped")}catch(Z){throw this.logger.error("Failed to stop Auto-Update Service",Z),Z}}getStatus(){return{name:this.name,running:this.running,enabled:this.enabled,lastCheckTime:this.lastCheckTime,nextCheckTime:this.nextCheckTime,currentVersion:O0(),updateAvailable:this.updateAvailable,latestVersion:this.latestVersion,releaseChannel:v9(O0()),startedAt:this.startedAt,installationType:this.installationType}}scheduleNextCheck(){if(!this.enabled)return;let Z=(this.config.checkIntervalMinutes||60)*60*1000;if(this.checkInterval)clearInterval(this.checkInterval);this.nextCheckTime=new Date(Date.now()+Z),this.checkInterval=setInterval(async()=>{this.nextCheckTime=new Date(Date.now()+Z);try{await this.performUpdateCheck()}catch(J){this.logger.error("Error in scheduled update check",J)}},Z),this.logger.debug("Next update check scheduled",{nextCheckTime:this.nextCheckTime,intervalMinutes:this.config.checkIntervalMinutes})}async performUpdateCheck(){if(this.lastCheckTime=new Date,this.installationType=KY(),this.installationType==="development"){this.logger.debug("Skipping auto-update in development mode");return}try{if(this.logger.debug("Performing update check",{packageName:this.config.packageName,currentVersion:O0(),installationType:this.installationType}),this.installationType==="binary"){let Z=await uW();if(this.updateAvailable=Z.updateAvailable,this.latestVersion=Z.latestVersion,this.downloadUrl=Z.downloadUrl,Z.updateAvailable)this.logger.info("Binary update available",{current:Z.currentVersion,latest:Z.latestVersion,channel:Z.releaseChannel}),await this.performAutoUpdate();else this.logger.debug("Already running latest binary version",{version:Z.currentVersion,channel:Z.releaseChannel})}else{let Z=await mW(this.config.packageName);if(this.updateAvailable=Z.updateAvailable,this.latestVersion=Z.latestVersion,Z.updateAvailable)this.logger.info("Package update available",{current:Z.currentVersion,latest:Z.latestVersion,channel:Z.releaseChannel}),await this.performAutoUpdate();else this.logger.debug("Already running latest package version",{version:Z.currentVersion,channel:Z.releaseChannel})}}catch(Z){this.logger.error("Error during update check",Z)}}async performAutoUpdate(){try{this.logger.info("Starting auto-update",{packageName:this.config.packageName,installationType:this.installationType,targetVersion:this.latestVersion});let Z=!1;if(this.installationType==="binary"&&this.downloadUrl)if(Z=await lV(this.downloadUrl,this.latestVersion),Z)this.logger.info("Binary update installed successfully",{newVersion:this.latestVersion});else this.logger.warn("Binary update failed");else if(this.installationType==="npm")if(Z=await cV(this.config.packageName,this.latestVersion),Z)this.logger.info("Package update installed successfully",{newVersion:this.latestVersion,packageName:this.config.packageName});else this.logger.warn("Package update failed",{packageName:this.config.packageName})}catch(Z){this.logger.error("Error during auto-update",Z)}}}RZ();import{watch as PX0,readdirSync as IX0,existsSync as aV}from"fs";import{stat as wW1}from"fs/promises";import{join as Z7,basename as AW1}from"path";import{homedir as dT}from"os";RZ();import*as j4 from"fs";import*as mT from"readline";import*as Q4 from"path";import*as dW from"os";var zY=S();class LW1{async parseSessionFile(Z,J,$=50){let X=!1;try{let Y=Bun.file(Z);if(!await Y.exists())return zY.warn("[SessionMessageParser] Session file not found:",Z),{messages:[],hasMore:!1};let K=(await Y.text()).trim().split(`
2345
2345
  `),z=[],G=new Map,H=new Map;for(let B of K)try{if(!B.trim())continue;let U=JSON.parse(B);if(U.uuid)H.set(U.uuid,U.parentUuid||null);let L=this.parseEntry(U);if(L)z.push(L),G.set(L.uuid,L)}catch(U){zY.warn("[SessionMessageParser] Failed to parse line:",U)}let V=this.buildActiveBranch(z,G,H),F;if(J){let B=V.findIndex((U)=>U.uuid===J);if(B===-1)zY.warn("[SessionMessageParser] lastKnownUuid not found in active branch, returning latest messages"),F=V.slice(-$),X=V.length>$;else{let U=V.slice(B+1);F=U.slice(0,$),X=U.length>$}}else if(V.length>$)F=V.slice(-$),X=!0;else F=V,X=!1;return zY.debug("[SessionMessageParser] Parsed session file:",{filePath:Z,totalMessages:z.length,activeBranchMessages:V.length,returnedMessages:F.length,lastKnownUuid:J,hasMore:X,limit:$,parentUuidMapSize:H.size}),{messages:F,hasMore:X}}catch(Y){throw zY.error("[SessionMessageParser] Error parsing session file:",Y),Y}}buildActiveBranch(Z,J,$){if(Z.length===0)return[];let X=Z.filter((V)=>V.type==="system"),Y=Z.filter((V)=>V.type!=="system");if(Y.length===0)return Z.sort((V,F)=>new Date(V.timestamp).getTime()-new Date(F.timestamp).getTime());let Q=new Set;for(let V of Y)if(V.parentUuid)Q.add(V.parentUuid);let W=Y.filter((V)=>!Q.has(V.uuid));if(W.length===0)return Z.sort((V,F)=>new Date(V.timestamp).getTime()-new Date(F.timestamp).getTime());let K=W.reduce((V,F)=>{let B=new Date(V.timestamp).getTime();return new Date(F.timestamp).getTime()>B?F:V}),z=new Set,G=K.uuid;while(G){if(J.has(G))z.add(G);let V=$.get(G);if(V)G=V;else G=null}let H=[];for(let V of Z)if(z.has(V.uuid)||V.type==="system")H.push(V);return H.sort((V,F)=>new Date(V.timestamp).getTime()-new Date(F.timestamp).getTime()),H}parseEntry(Z){try{let J=Z.uuid;if(!J)return null;if(Z.isMeta)return null;let $={uuid:J,parentUuid:Z.parentUuid||null,timestamp:Z.timestamp||new Date().toISOString(),type:this.determineMessageType(Z),role:Z.message?.role,content:Z.message?.content||Z.content||"",metadata:{sessionId:Z.sessionId,version:Z.version,gitBranch:Z.gitBranch,cwd:Z.cwd,requestId:Z.requestId,isSidechain:Z.isSidechain,parentToolUseId:Z.parent_tool_use_id,message:Z.message}};if(Z.message?.content&&Array.isArray(Z.message.content)){let Y=Z.message.content.find((Q)=>Q.type==="tool_use");if(Y)$.toolName=Y.name,$.toolInput=Y.input,$.toolUseId=Y.id}if(Z.toolUseResult)$.toolOutput=Z.toolUseResult.stdout||Z.toolUseResult.content||"",$.isError=Z.toolUseResult.isError||Z.is_error||!1;if(Z.type==="summary"&&Z.summary)$.content=Z.summary;let X=null;if(Z.type==="system"&&Z.subtype==="local_command")X=Z.content;else if(typeof $.content==="string")X=$.content;else if(Array.isArray($.content)){let Y=$.content.find((Q)=>Q.type==="text"&&Q.text);if(Y)X=Y.text}if(X){let Y=this.parseSlashCommand(X);if(Y)$.slashCommand=Y,$.type="system";let Q=this.parseSlashCommandOutput(X);if(Q)$.slashCommand={name:"",message:"",args:"",output:Q.output,error:Q.error},$.type="system"}return $}catch(J){return zY.warn("[SessionMessageParser] Failed to parse entry:",J),null}}determineMessageType(Z){if(Z.type==="summary")return"summary";if(Z.type==="system")return"system";if(Z.type==="user"){if(Z.message?.content&&Array.isArray(Z.message.content)){if(Z.message.content.some(($)=>$.type==="tool_result"))return"tool"}if(typeof Z.message?.content==="string"){let J=Z.message.content;if(J.includes("<command-name>")||J.includes("<local-command-stdout>")||J.includes("<local-command-stderr>"))return"system"}return"user"}if(Z.type==="assistant")return"assistant";if(Z.message?.role==="user")return"user";if(Z.message?.role==="assistant")return"assistant";return"user"}parseSlashCommand(Z){if(!Z||typeof Z!=="string")return null;let J=Z.match(/<command-name>(\/[^<]+)<\/command-name>/),$=Z.match(/<command-message>([^<]*)<\/command-message>/),X=Z.match(/<command-args>([^<]*)<\/command-args>/);if(J&&J[1])return{name:J[1].trim(),message:$&&$[1]?$[1].trim():"",args:X&&X[1]?X[1].trim():""};return null}parseSlashCommandOutput(Z){if(!Z||typeof Z!=="string")return null;let J=Z.match(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/),$=Z.match(/<local-command-stderr>([\s\S]*?)<\/local-command-stderr>/);if(J||$)return{output:J?J[1]:void 0,error:$?$[1]:void 0};return null}}var DW1=new LW1;var y8={SYSTEM_PROMPT:3300,TOOLS_TOTAL:15600,AUTOCOMPACT_BUFFER:45000,CONTEXT_LIMIT_STANDARD:200000,CONTEXT_LIMIT_1M:1e6};async function OW1(){try{let Z=Q4.join(dW.homedir(),".claude.json"),J=Bun.file(Z);if(await J.exists()){if((await J.json()).autoCompactEnabled===!1)return!1}}catch(Z){V0.debug("[SessionManager] Failed to read ~/.claude.json:",Z)}return!0}var CX0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qX0="worktrees",V0=S();function EX0(Z){let J=Z.replace(/[\\/]+$/,"");return J=J.replace(/:[\\/]+/g,"--"),J=J.replace(/:/g,"--"),J=J.replace(/[\\/]+/g,"-"),`--${J}--`}class _W1{claudeProjectsDir;piSessionsDir;cccDir;constructor(){this.claudeProjectsDir=Q4.join(dW.homedir(),".claude","projects"),this.piSessionsDir=Q4.join(dW.homedir(),".pi","agent","sessions"),this.cccDir=Q4.join(dW.homedir(),".ccc")}async getWorktreePathsForProject(Z){let J=Q4.basename(Z),$=Q4.join(this.cccDir,`${J}-${qX0}`);if(V0.debug("[SessionManager] Looking for worktrees:",{projectPath:Z,repoName:J,cccDir:this.cccDir,worktreesDir:$}),!j4.existsSync($))return V0.debug("[SessionManager] Worktrees directory does not exist:",$),[];try{let X=j4.readdirSync($,{withFileTypes:!0}),Y=[];for(let Q of X)if(Q.isDirectory()){let W=Q4.join($,Q.name);Y.push(W)}return V0.debug("[SessionManager] Found worktree paths:",Y),Y}catch(X){return V0.warn("[SessionManager] Error reading worktrees directory:",X),[]}}getProjectSessionsDir(Z){return Q4.join(this.claudeProjectsDir,Y9(Z))}getPiSessionsDir(Z){return Q4.join(this.piSessionsDir,EX0(Z))}async extractPiSessionMetadata(Z,J){try{let $=J.replace(".jsonl",""),X=$.split("_"),Y=X.length>1?X.slice(1).join("_"):$,{title:Q,messageCount:W}=await new Promise((G)=>{let H="Pi Session",V=0,F=mT.createInterface({input:j4.createReadStream(Z,{encoding:"utf-8"})});F.on("line",(B)=>{if(!B.trim())return;try{let U=JSON.parse(B);if(U.type==="message"){if(V++,U.message?.role==="assistant"&&H==="Pi Session"){let L=U.message.content;if(Array.isArray(L)){let O=L.find((_)=>_.type==="text");if(O?.text)H=O.text.substring(0,80).replace(/\n/g," ").trim()||H}}}else if(U.type==="session_info"&&U.name)H=U.name}catch{}}),F.on("close",()=>G({title:H,messageCount:V})),F.on("error",()=>G({title:H,messageCount:V}))});if(W===0)return null;let K=await this.getFileModTime(Z),z=K?K.toISOString():new Date().toISOString();return{sessionId:Y,title:Q,lastActivity:z,messageCount:W,provider:"pi"}}catch($){return V0.warn(`[SessionManager] Error extracting Pi session metadata from ${J}`,$),null}}async listPiSessions(Z){let J=this.getPiSessionsDir(Z);if(!j4.existsSync(J))return[];try{let $=j4.readdirSync(J).filter((Y)=>Y.endsWith(".jsonl"));if($.length===0)return[];let X=[];for(let Y of $){let Q=Q4.join(J,Y),W=await this.extractPiSessionMetadata(Q,Y);if(W)X.push(W)}return X.sort((Y,Q)=>new Date(Q.lastActivity).getTime()-new Date(Y.lastActivity).getTime()),X}catch($){return V0.debug("[SessionManager] Error scanning Pi sessions:",$),[]}}async getLatestPiSession(Z){return(await this.listPiSessions(Z))[0]??null}async pathExists(Z){try{return await Bun.file(Z).exists()}catch{return!1}}async dirExists(Z){try{return await Bun.file(Z).stat()!==null}catch{try{return j4.existsSync(Z)&&j4.statSync(Z).isDirectory()}catch{return!1}}}async readDir(Z){try{return j4.readdirSync(Z)}catch{return[]}}async extractTitleAndCount(Z){try{let J=j4.createReadStream(Z,{encoding:"utf-8"}),$=mT.createInterface({input:J,crlfDelay:1/0}),X=null,Y=null,Q=[];for await(let z of $){if(!z.trim())continue;try{let G=JSON.parse(z);if(G.uuid&&(G.type==="user"||G.type==="assistant"))Q.push({uuid:G.uuid,parentUuid:G.parentUuid||null});if(G.type==="summary"&&G.summary)X=G.summary;if(!Y&&!G.isMeta&&G.message){let H=G.type==="user"||G.message?.role==="user",V=Array.isArray(G.message?.content)&&G.message.content.some((F)=>F.type==="tool_result");if(H&&!V){let F=G.message?.content,B=null;if(typeof F==="string")B=F;else if(Array.isArray(F)){let L=F.find((O)=>O.type==="text");if(L?.text)B=L.text}let U=B?.trim();if(U&&U!=="Warmup"&&!U.startsWith("<command-name>")&&!U.startsWith("<local-command-stdout>"))Y=U}}}catch{}}let W=0;if(Q.length>0){let z=new Map(Q.map((V)=>[V.uuid,V])),G=new Set(Q.map((V)=>V.parentUuid).filter(Boolean)),H=Q.filter((V)=>!G.has(V.uuid));if(H.length===0)W=Q.length;else{let F=H[H.length-1];while(F)if(W++,F.parentUuid)F=z.get(F.parentUuid);else break}}return{title:(X||Y||"Untitled Session").substring(0,100),messageCount:W}}catch(J){return V0.warn("[SessionManager] Error extracting title/count:",J),{title:"Untitled Session",messageCount:0}}}async getFileModTime(Z){try{return j4.statSync(Z).mtime}catch{return null}}async getSessionMetadataForFile(Z,J){return this.extractSessionMetadata(Z,J)}async extractSessionMetadata(Z,J){try{let{title:$,messageCount:X}=await this.extractTitleAndCount(Z),Y=await this.getFileModTime(Z),Q=Y?Y.toISOString():new Date().toISOString();return{sessionId:J,title:$,lastActivity:Q,messageCount:X,provider:"claude"}}catch($){return V0.warn(`[SessionManager] Error extracting metadata for session ${J}`,$),null}}async listSessionsFromDir(Z,J){if(!j4.existsSync(Z))return[];try{let X=(await this.readDir(Z)).filter((Q)=>{if(!Q.endsWith(".jsonl"))return!1;let W=Q4.basename(Q,".jsonl");return CX0.test(W)}),Y=[];for(let Q of X){let W=Q4.basename(Q,".jsonl"),K=Q4.join(Z,Q),z=await this.extractSessionMetadata(K,W);if(z&&z.messageCount>0){if(J)z.worktreePath=J.path,z.worktreeBranch=J.branch;Y.push(z)}}return Y}catch($){return V0.warn(`[SessionManager] Error listing sessions from ${Z}`,$),[]}}async listSessions(Z){if(!j4.existsSync(Z))return V0.warn("[SessionManager] Project path does not exist:",Z),{sessions:[],projectPath:Z,pathExists:!1};try{let $=this.getProjectSessionsDir(Z);V0.debug("[SessionManager] Main sessions dir:",$);let X=await this.listSessionsFromDir($);V0.debug("[SessionManager] Main sessions count:",X.length);let Y=await this.getWorktreePathsForProject(Z);V0.debug("[SessionManager] Worktree paths to check:",Y.length);let Q=Y.map(async(H)=>{let V=this.getProjectSessionsDir(H);V0.debug("[SessionManager] Checking worktree sessions dir:",V);let F=Q4.basename(H),B={path:H,branch:`session/${F}`},U=await this.listSessionsFromDir(V,B);return V0.debug("[SessionManager] Found sessions in worktree:",{worktreePath:H,count:U.length,worktreeInfo:B}),U}),K=(await Promise.all(Q)).flat();V0.debug("[SessionManager] Total worktree sessions:",K.length);let z=new Map;for(let H of X)z.set(H.sessionId,H);for(let H of K){let V=z.get(H.sessionId);if(!V||new Date(H.lastActivity)>new Date(V.lastActivity)||H.messageCount>V.messageCount)z.set(H.sessionId,H)}let G=Array.from(z.values()).sort((H,V)=>new Date(V.lastActivity).getTime()-new Date(H.lastActivity).getTime());return V0.debug(`[SessionManager] Found ${G.length} sessions for ${Z} (${X.length} main, ${K.length} worktree)`),{sessions:G,projectPath:Z,pathExists:!0}}catch($){return V0.error(`[SessionManager] Error listing sessions for ${Z}`,$),{sessions:[],projectPath:Z,pathExists:!0}}}async getLatestSession(Z){let J=await this.listSessions(Z);if(J.sessions.length===0)return null;return J.sessions[0]??null}async getSessionCounts(Z){return await Promise.all(Z.map(async($)=>{let X=await this.listSessions($);return{projectPath:$,sessionCount:X.sessions.length}}))}async findSessionFilePath(Z,J){let $=this.getProjectSessionsDir(Z),X=Q4.join($,`${J}.jsonl`);if(j4.existsSync(X))return{filePath:X};let Y=await this.getWorktreePathsForProject(Z);for(let Q of Y){let W=this.getProjectSessionsDir(Q),K=Q4.join(W,`${J}.jsonl`);if(j4.existsSync(K)){let z=Q4.basename(Q);return{filePath:K,worktreePath:Q,worktreeBranch:`session/${z}`}}}return{filePath:null}}async getSessionMessages(Z,J,$,X=50){let{filePath:Y,worktreePath:Q,worktreeBranch:W}=await this.findSessionFilePath(Z,J);try{if(!Y)return V0.warn("[SessionManager] Session file not found for:",{projectPath:Z,sessionId:J}),{messages:[],hasMore:!1,sessionId:J,projectPath:Z,timestamp:Date.now()};let K=await DW1.parseSessionFile(Y,$,X),z=K.messages.filter((F)=>F.slashCommand);if(z.length>0)V0.debug(`[SessionManager] Found ${z.length} slash command messages`),z.forEach((F)=>V0.debug("[SessionManager] Slash cmd:",{type:F.type,slashCommand:F.slashCommand}));let{title:G}=await this.extractTitleAndCount(Y),H=await this.calculateContextBreakdown(Y),V={totalInputTokens:H.inputTokens,totalOutputTokens:H.outputTokens,totalCacheCreationTokens:H.cacheCreation,totalCacheReadTokens:H.cacheRead,totalTokens:H.total};return{...K,sessionId:J,projectPath:Z,title:G,context:H,totalUsage:V,timestamp:Date.now(),worktreePath:Q,worktreeBranch:W}}catch(K){throw V0.error(`[SessionManager] Error getting session messages for ${J}`,K),K}}async calculateContextBreakdown(Z){try{let X=(await Bun.file(Z).text()).trim().split(`
@@ -2406,7 +2406,7 @@ $ ${z}
2406
2406
  ${H}${H.endsWith(`
2407
2407
  `)?"":`
2408
2408
  `}\`\`\`${V!==0?`
2409
- Exit code: ${V}`:""}`}]}};this.publishOutput($,W.sessionId,F)}catch(G){let H={type:"error",error:{message:`Bash: ${G instanceof Error?G.message:"failed"}`,type:"bash_error"}};this.publishOutput($,W.sessionId,H)}finally{this.publishStatus($,W.sessionId,{type:"session_idle",sessionId:W.sessionId,timestamp:Date.now()})}this.totalMessagesProcessed++;return}}await this.sessionManager.sendMessage(Y.sessionId,Y.message||"",Y.attachments),this.totalMessagesProcessed++}catch(X){V1.error("[PiAgent] Error handling user input:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handlePermissionResponseFromMobile(Z,J){let $,X,Y="";try{let Q=await this.parseMessage(J);if(!Q)return;if($=Q.data,X=$.requestId,Y=Q.profileId,!this.sessionManager.getSession(Z)){V1.warn(`[PiAgent] Session ${Z} not found for permission response`),this.publishStatus(Y,Z,{type:"session_stopped",reason:"session_lost",message:"Session is no longer active.",timestamp:Date.now()});return}if(this.sessionManager.sendApprovalResponse(X,$.approved),!$.approved&&$.hardDeny){let K=Y;setTimeout(()=>{this.sessionManager.stopSession(Z).catch(()=>{}),this.publishStatus(K,Z,{type:"session_stopped",reason:"permission_denied",message:$.denyMessage||"Permission denied by user",timestamp:Date.now()})},100)}if(X)this.pendingPermissions.delete(X),B0.removePermission(X).catch(()=>{})}catch(Q){if(V1.error("[PiAgent] Error handling permission response:",{profileId:Y,sessionId:Z,error:Q instanceof Error?Q.message:"Unknown error"}),Y)this.publishStatus(Y,Z,{type:"session_stopped",reason:"session_lost",message:"Session is no longer active. The permission request could not be delivered.",timestamp:Date.now()});if(X)this.pendingPermissions.delete(X),B0.removePermission(X).catch(()=>{})}}async handleSessionStop(Z,J){let X=(await this.parseMessage(J))?.profileId||"";V1.debug("[PiAgent] Session stop request:",{profileId:X,sessionId:Z});try{await this.sessionManager.stopSession(Z)}catch(Y){V1.error("[PiAgent] Failed to stop session",{sessionId:Z,error:Y})}}async handleTogglePi(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let{enabled:X}=$.data;if(X)V1.info("[PiAgent] Enabling Pi..."),W7("pi_enabled",!0);else V1.info("[PiAgent] Disabling Pi, stopping all sessions..."),W7("pi_enabled",!1),await this.sessionManager.stopAll();this.publishToggleResponse(J,{enabled:!!X})}catch($){if(V1.error("[PiAgent] Error toggling Pi:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishToggleResponse(J,{enabled:!1,error:$ instanceof Error?$.message:"Failed to toggle Pi"})}}async handleGetEnabled(Z){let J=await this.parseMessage(Z);if(!J)return;let $=J.profileId,X=D5("pi_enabled")||!1;this.publishToggleResponse($,{enabled:X})}async handleSetModel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{model:Y}=X.data;await this.sessionManager.setModel(Z,Y)}catch(X){V1.error("[PiAgent] Error setting model:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handleSetThinkingLevel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{level:Y}=X.data;this.sessionManager.setThinkingLevel(Z,Y),this.publishStatus($,Z,{type:"thinking_level_changed",thinkingLevel:Y,timestamp:Date.now()})}catch(X){V1.error("[PiAgent] Error setting thinking level:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handleCompact(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId,await this.sessionManager.compactSession(Z);let Y=`pi/${$}/compact/response/${Z}`;await this.publishEncrypted(Y,{type:"compact_started",sessionId:Z},$)}catch(X){if(V1.error("[PiAgent] Error handling compact:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/compact/response/${Z}`;await this.publishEncrypted(Y,{type:"compact_error",sessionId:Z,error:X instanceof Error?X.message:"Compact failed"},$)}}}async handleSteer(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{message:Y}=X.data;await this.sessionManager.steerSession(Z,Y)}catch(X){V1.error("[PiAgent] Error handling steer:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}serializeTreeNode(Z){let J=Z.entry,$={id:J.id,parentId:J.parentId,type:J.type,timestamp:J.timestamp,label:Z.label,children:Array.isArray(Z.children)?Z.children.map((X)=>this.serializeTreeNode(X)):[]};if(J.type==="message"){let X=J.message;$.role=X?.role;let Y=X?.content,Q="";if(typeof Y==="string")Q=Y;else if(Array.isArray(Y))Q=Y.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join(" ");$.preview=Q.substring(0,200)}else if(J.type==="compaction")$.summary=J.summary,$.tokensBefore=J.tokensBefore;else if(J.type==="branch_summary")$.summary=J.summary;else if(J.type==="model_change")$.modelId=J.modelId;else if(J.type==="thinking_level_change")$.thinkingLevel=J.thinkingLevel;else if(J.type==="label")$.label=J.label;else if(J.type==="session_info")$.name=J.name;else if(J.type==="custom"||J.type==="custom_message")$.customType=J.customType;return $}hasMultipleBranches(Z){for(let J of Z){if((J.children?.length||0)>1)return!0;if(J.children&&this.hasMultipleBranches(J.children))return!0}return!1}async handleTreeList(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{directoryPath:Y}=X.data||{},Q=`pi/${$}/tree/response/${Z}`,W=this.sessionManager.getSessionTree(Z);if(!W){if(!Y)throw Error("directoryPath required to read session from disk");let{piSdk:z}=await W9(),H=(await z.SessionManager.list(Y)).find((F)=>F.id===Z);if(!H)throw Error(`Pi session ${Z} not found on disk`);let V=z.SessionManager.open(H.path);W={nodes:V.getTree(),leafId:V.getLeafId()}}let K=W.nodes.map((z)=>this.serializeTreeNode(z));await this.publishEncrypted(Q,{sessionId:Z,nodes:K,leafId:W.leafId,hasMultipleBranches:this.hasMultipleBranches(K)},$)}catch(X){if(V1.error("[PiAgent] Error handling tree list:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/tree/response/${Z}`;await this.publishEncrypted(Y,{sessionId:Z,nodes:[],leafId:null,hasMultipleBranches:!1,error:X instanceof Error?X.message:"Failed to load tree"},$)}}}async handleRewind(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{targetId:Y,summarize:Q=!1,directoryPath:W,checkpointUuid:K}=X.data||{},z=Y||K,G=`pi/${$}/rewind/response/${Z}`;if(!z){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,error:"targetId is required"},$);return}if(this.sessionManager.isSessionStreaming(Z)){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,checkpointUuid:z,error:"Cannot navigate while agent is streaming. Stop the session first."},$);return}let H=this.sessionManager.getSession(Z);if(!H?.piSession){if(!W)throw Error("directoryPath required to resume session for navigation");H=await this.sessionManager.resumeSession(Z,$,"",W)}if(!H?.piSession)throw Error("Could not activate Pi session for tree navigation");let V=await this.sessionManager.navigateTree(Z,z,!!Q);if(V.cancelled||V.aborted){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,checkpointUuid:z,error:V.aborted?"Navigation aborted":"Navigation cancelled"},$);return}await this.publishEncrypted(G,{type:"rewind_complete",sessionId:Z,checkpointUuid:z,mode:Q?"branch_with_summary":"conversation_only",restoredMessage:V.editorText},$),this.publishStatus($,Z,{type:"session_idle",sessionId:Z,timestamp:Date.now()})}catch(X){if(V1.error("[PiAgent] Error handling rewind:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/rewind/response/${Z}`;await this.publishEncrypted(Y,{type:"rewind_failed",sessionId:Z,error:X instanceof Error?X.message:"Navigation failed"},$)}}}async handleSetLabel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{targetId:Y,label:Q,directoryPath:W}=X.data||{},K=`pi/${$}/label/response/${Z}`;if(!Y){await this.publishEncrypted(K,{type:"label_failed",sessionId:Z,error:"targetId is required"},$);return}let z=this.sessionManager.getSession(Z);if(!z?.piSession){if(!W)throw Error("directoryPath required to resume session for labeling");z=await this.sessionManager.resumeSession(Z,$,"",W)}if(!z?.piSession)throw Error("Could not activate Pi session for labeling");let G=Q?String(Q).trim():void 0,H=this.sessionManager.setLabel(Z,Y,G);await this.publishEncrypted(K,{type:"label_set",sessionId:Z,targetId:Y,label:G,entryId:H},$)}catch(X){if(V1.error("[PiAgent] Error handling set label:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/label/response/${Z}`;await this.publishEncrypted(Y,{type:"label_failed",sessionId:Z,error:X instanceof Error?X.message:"Label update failed"},$)}}}async handleRename(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{name:Y,directoryPath:Q}=X.data||{},W=`pi/${$}/rename/response/${Z}`;if(!Y||typeof Y!=="string"||!Y.trim()){await this.publishEncrypted(W,{success:!1,sessionId:Z,error:"name is required"},$);return}let K=Y.trim(),{wasInMemory:z,session:G}=await this.sessionManager.renameSession(Z,K,Q);if(!z){if(this.publishStatus($,Z,{type:"title_generated",title:K,timestamp:Date.now()}),this.sessionsService&&Q)this.sessionsService.notifyProviderSessionUpdate(Q,{sessionId:Z,title:K,status:"idle",provider:"pi"})}else if(G)this.handleTitleGenerated(G,K);await this.publishEncrypted(W,{success:!0,sessionId:Z,name:K},$)}catch(X){if(V1.error("[PiAgent] Error handling rename:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/rename/response/${Z}`;await this.publishEncrypted(Y,{success:!1,sessionId:Z,error:X instanceof Error?X.message:"Rename failed"},$)}}}async getSettingsManager(){if(this.settingsManager)return this.settingsManager;let{piSdk:Z}=await W9();return this.settingsManager=Z.SettingsManager.create(process.cwd()),this.settingsManager}async readMobileSettings(){let Z=await this.getSettingsManager(),J=Z.getCompactionSettings(),$=Z.getRetrySettings(),X=Z.getBranchSummarySettings();return{compactionEnabled:J.enabled,compactionReserveTokens:J.reserveTokens,compactionKeepRecentTokens:J.keepRecentTokens,retryEnabled:$.enabled,retryMaxRetries:$.maxRetries,retryBaseDelayMs:$.baseDelayMs,retryMaxDelayMs:$.maxDelayMs,steeringMode:Z.getSteeringMode(),followUpMode:Z.getFollowUpMode(),defaultThinkingLevel:Z.getDefaultThinkingLevel()??null,branchSummarySkipPrompt:X.skipPrompt}}async applyMobileSettings(Z){let J=await this.getSettingsManager();if(Z.compactionEnabled!==void 0)J.setCompactionEnabled(Z.compactionEnabled);if(Z.retryEnabled!==void 0)J.setRetryEnabled(Z.retryEnabled);if(Z.steeringMode!==void 0)J.setSteeringMode(Z.steeringMode);if(Z.followUpMode!==void 0)J.setFollowUpMode(Z.followUpMode);if(Z.defaultThinkingLevel!==void 0)if(Z.defaultThinkingLevel!==null)J.setDefaultThinkingLevel(Z.defaultThinkingLevel);else J.applyOverrides({defaultThinkingLevel:void 0});let $={};if(Z.compactionReserveTokens!==void 0||Z.compactionKeepRecentTokens!==void 0)$.compaction={...Z.compactionReserveTokens!==void 0&&{reserveTokens:Z.compactionReserveTokens},...Z.compactionKeepRecentTokens!==void 0&&{keepRecentTokens:Z.compactionKeepRecentTokens}};if(Z.retryMaxRetries!==void 0||Z.retryBaseDelayMs!==void 0||Z.retryMaxDelayMs!==void 0)$.retry={...Z.retryMaxRetries!==void 0&&{maxRetries:Z.retryMaxRetries},...Z.retryBaseDelayMs!==void 0&&{baseDelayMs:Z.retryBaseDelayMs},...Z.retryMaxDelayMs!==void 0&&{maxDelayMs:Z.retryMaxDelayMs}};if(Z.branchSummarySkipPrompt!==void 0)$.branchSummary={skipPrompt:Z.branchSummarySkipPrompt};if(Object.keys($).length>0)J.applyOverrides($);await J.flush()}async handleSettingsGet(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=await this.readMobileSettings(),Y=`pi/${J}/settings/response`;await this.publishEncrypted(Y,{success:!0,settings:X},J)}catch($){if(V1.error("[PiAgent] Error reading settings:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:$ instanceof Error?$.message:"Failed to read settings"},J)}}async handleSettingsSet(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=$.data?.patch;if(!X||typeof X!=="object"){await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:"patch is required"},J);return}await this.applyMobileSettings(X);let Y=await this.readMobileSettings();await this.publishEncrypted(`pi/${J}/settings/response`,{success:!0,settings:Y},J)}catch($){if(V1.error("[PiAgent] Error writing settings:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:$ instanceof Error?$.message:"Failed to write settings"},J)}}async handleProvidersList(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=[];try{let{piAi:W}=await W9(),K=await import("fs"),z=await import("path"),G=await import("os"),H=z.join(G.homedir(),".pi","agent","auth.json"),V=[];try{let U=K.readFileSync(H,"utf-8");V=Object.keys(JSON.parse(U))}catch{V=["anthropic"]}let F="";try{let U=z.join(G.homedir(),".pi","agent","settings.json");F=JSON.parse(K.readFileSync(U,"utf-8")).defaultModel||""}catch{}let B=/^claude-.*-\d{8}$/;for(let U of V)try{let L=W.getModels(U);for(let O of L){if(B.test(O.id))continue;if(O.id.startsWith("claude-3-"))continue;X.push({id:O.id,displayName:O.name||O.id,provider:O.provider,isDefault:O.id===F,reasoning_variants:O.reasoning?["minimal","low","medium","high","xhigh"]:void 0})}}catch{V1.debug(`[PiAgent] No built-in models for provider: ${U}`)}}catch(W){V1.debug("[PiAgent] Failed to read Pi model catalog:",W)}if(X.length===0)X=[{id:"claude-sonnet-4-5",displayName:"Claude Sonnet 4.5",provider:"anthropic",isDefault:!0},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",provider:"anthropic"},{id:"claude-haiku-4-5",displayName:"Claude Haiku 4.5",provider:"anthropic"}];let Y={};for(let W of X){let K=W.provider||"unknown";if(!Y[K])Y[K]=[];Y[K].push(W)}let Q=Object.entries(Y).map(([W,K])=>({id:W,name:W.charAt(0).toUpperCase()+W.slice(1),models:Object.fromEntries(K.map((z)=>[z.id,{name:z.displayName||z.id,family:W,capabilities:{reasoning:!!z.reasoning_variants,attachment:!0,toolcall:!0},reasoning_variants:z.reasoning_variants}]))}));this.publishProviderResponse(J,{providers:Q,connected:Object.keys(Y)})}catch($){if(V1.error("[PiAgent] Error listing providers:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishProviderResponse(J,{error:$ instanceof Error?$.message:"Failed to list providers"})}}handleSessionInitialized(Z){if(Z.worktreePath&&Z.tempId&&Z.sessionId)this.worktreeManager.updateSessionId(Z.worktreePath,Z.tempId,Z.sessionId);if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_started",sessionId:Z.sessionId,tempId:Z.tempId,model:Z.model,thinkingLevel:Z.thinkingLevel,worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch,slashCommands:[],agents:[],skills:[],timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:Z.status,provider:"pi"})}handleTitleGenerated(Z,J){if(this.publishStatus(Z.userId,Z.sessionId,{type:"title_generated",title:J,timestamp:Date.now()}),this.sessionsService&&Z.sessionId)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:J,status:Z.status,provider:"pi"})}handleAssistantMessage(Z,J){if(Z.sessionId)this.publishOutput(Z.userId,Z.sessionId,J)}handlePermissionRequest(Z,J){if(!Z.sessionId)return;this.pendingPermissions.set(J.request_id,{requestId:J.request_id,action:J.action,params:J.params,createdAt:Date.now()}),B0.addPermission({requestId:J.request_id,sessionId:Z.sessionId,projectPath:Z.directoryPath,action:J.action,params:J.params,createdAt:new Date().toISOString()}).catch(()=>{});let $=`pi/${Z.userId}/permission/request/${Z.sessionId}`;this.publishEncrypted($,J,Z.userId).catch((X)=>{V1.error("[PiAgent] Failed to publish permission request",{error:X instanceof Error?X.message:"Unknown error"})})}handleSessionError(Z,J){this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"error",error:J,timestamp:Date.now()})}handleSessionStopped(Z,J){if(this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"session_stopped",reason:J,timestamp:Date.now()}),this.sessionsService){if(this.sessionsService.notifySessionStopped(),Z.sessionId)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:"stopped",provider:"pi"})}}handleProcessingStarted(Z){if(Z.sessionId)this.publishStatus(Z.userId,Z.sessionId,{type:"session_processing",sessionId:Z.sessionId,timestamp:Date.now()})}handleProcessingComplete(Z){if(!Z.sessionId)return;if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()}),Z.tempId&&Z.tempId!==Z.sessionId)this.publishStatus(Z.userId,Z.tempId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()});if(this.sessionsService)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:"idle",messageCount:Z.messageCount,provider:"pi"})}handleContextUpdate(Z,J){if(Z.sessionId)this.publishContextUpdate(Z.userId,Z.sessionId,J)}handleExtensionUiRequest(Z,J){let $=Z.sessionId||Z.tempId;if(!$)return;let X=`pi/${Z.userId}/extension/ui/request/${$}`;this.publishEncrypted(X,J,Z.userId).catch((Y)=>{V1.error("[PiAgent] Failed to publish extension UI request",{method:J.method,error:Y instanceof Error?Y.message:"Unknown error"})})}async handleExtensionUiResponse(Z){try{let J=await this.parseMessage(Z);if(!J)return;this.sessionManager.resolveUiResponse(J.data)}catch(J){V1.error("[PiAgent] Error handling extension UI response:",{error:J instanceof Error?J.message:"Unknown error"})}}publishStatus(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/status/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish status",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishOutput(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/output/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish output",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishContextUpdate(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/context/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish context",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishToggleResponse(Z,J){if(!this.mqttClient)return;let $=`pi/${Z}/toggle/response`;this.publishEncrypted($,J,Z).catch((X)=>{V1.error("[PiAgent] Failed to publish toggle response",{error:X instanceof Error?X.message:"Unknown error"})})}publishProviderResponse(Z,J){if(!this.mqttClient)return;let $=`pi/${Z}/providers/response`;this.publishEncrypted($,J,Z).catch((X)=>{V1.error("[PiAgent] Failed to publish provider response",{error:X instanceof Error?X.message:"Unknown error"})})}async parseMessage(Z){try{let J=JSON.parse(Z.toString());if(M1.isEncryptedEnvelope(J)){let $=J.c;if(!$)return null;let X=M1.getClientKeyOrRekey($);if(!X)return null;let Y=await M1.decrypt(X,J);return{data:JSON.parse(Y),profileId:$}}return V1.warn("[PiAgent] Received unencrypted message \u2014 dropping"),null}catch(J){return V1.warn("[PiAgent] Failed to parse message",{error:J}),null}}async publishEncrypted(Z,J,$){if(!this.mqttClient)return;if(!$)return;let X=M1.getClientKeyOrRekey($);if(!X){V1.warn(`[PiAgent] No encryption key for profile ${$} \u2014 dropping message on ${Z} (rekey requested)`);return}let Y=await M1.encrypt(X,JSON.stringify(J));Y.c=$,await this.mqttClient.publish(Z,JSON.stringify(Y),{qos:1})}cleanupStalePendingPermissions(){let Z=Date.now();for(let[J,$]of this.pendingPermissions)if(Z-$.createdAt>tW.PENDING_PERMISSION_TTL_MS)this.pendingPermissions.delete(J),B0.removePermission(J).catch(()=>{})}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.sessionManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessionCount(){return this.sessionManager.getSessionCount()}getActiveSessions(){return this.sessionManager.getActiveSessions()}async getSessionMessages(Z,J){let $=this.sessionManager.getSessionEntries(Z);if((!$||$.length===0)&&J)try{let{piSdk:K}=await W9(),G=(await K.SessionManager.list(J)).find((H)=>H.id===Z);if(G)$=K.SessionManager.open(G.path).getEntries()}catch(K){V1.warn("[PiAgent] Failed to read session messages from disk",{sessionId:Z,error:K instanceof Error?K.message:"Unknown error"})}let X=jY0($||[]),Y=this.sessionManager.getSession(Z),Q=Y?.contextUsage,W=Y?.title;return{messages:X,title:W,context:Q}}}function jY0(Z){let J=[],$=null;for(let X of Z){if(!X||X.type!=="message")continue;let Y=X.message;if(!Y)continue;let Q=X.id,W=X.timestamp||new Date().toISOString(),K=Y.role;if(K==="user"){let z;if(typeof Y.content==="string")z=Y.content;else if(Array.isArray(Y.content))z=Y.content.map((G)=>{if(G.type==="text")return{type:"text",text:G.text};if(G.type==="image"&&G.source)return{type:"image",source:{type:"base64",media_type:G.source.mediaType??G.source.media_type,data:G.source.data}};return null}).filter(Boolean);else z="";J.push({uuid:Q,parentUuid:$,timestamp:W,type:"user",role:"user",content:z}),$=Q}else if(K==="assistant"){let z=[],G=Array.isArray(Y.content)?Y.content:[];for(let H of G)if(H.type==="text"&&H.text)z.push({type:"text",text:H.text});else if(H.type==="thinking"&&H.thinking)z.push({type:"thinking",thinking:H.thinking});else if(H.type==="toolCall")z.push({type:"tool_use",id:H.id||H.toolCallId,name:H.name,input:H.arguments??H.input??{}});if(z.length===0)continue;J.push({uuid:Q,parentUuid:$,timestamp:W,type:"assistant",role:"assistant",content:z}),$=Q}else if(K==="toolResult"){let z=Y.toolCallId,G="";if(typeof Y.content==="string")G=Y.content;else if(Array.isArray(Y.content))G=Y.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
2409
+ Exit code: ${V}`:""}`}]}};this.publishOutput($,W.sessionId,F)}catch(G){let H={type:"error",error:{message:`Bash: ${G instanceof Error?G.message:"failed"}`,type:"bash_error"}};this.publishOutput($,W.sessionId,H)}finally{this.publishStatus($,W.sessionId,{type:"session_idle",sessionId:W.sessionId,timestamp:Date.now()})}this.totalMessagesProcessed++;return}}await this.sessionManager.sendMessage(Y.sessionId,Y.message||"",Y.attachments),this.totalMessagesProcessed++}catch(X){V1.error("[PiAgent] Error handling user input:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handlePermissionResponseFromMobile(Z,J){let $,X,Y="";try{let Q=await this.parseMessage(J);if(!Q)return;if($=Q.data,X=$.requestId,Y=Q.profileId,!this.sessionManager.getSession(Z)){V1.warn(`[PiAgent] Session ${Z} not found for permission response`),this.publishStatus(Y,Z,{type:"session_stopped",reason:"session_lost",message:"Session is no longer active.",timestamp:Date.now()});return}if(this.sessionManager.sendApprovalResponse(X,$.approved),!$.approved&&$.hardDeny){let K=Y;setTimeout(()=>{this.sessionManager.stopSession(Z).catch(()=>{}),this.publishStatus(K,Z,{type:"session_stopped",reason:"permission_denied",message:$.denyMessage||"Permission denied by user",timestamp:Date.now()})},100)}if(X)this.pendingPermissions.delete(X),B0.removePermission(X).catch(()=>{})}catch(Q){if(V1.error("[PiAgent] Error handling permission response:",{profileId:Y,sessionId:Z,error:Q instanceof Error?Q.message:"Unknown error"}),Y)this.publishStatus(Y,Z,{type:"session_stopped",reason:"session_lost",message:"Session is no longer active. The permission request could not be delivered.",timestamp:Date.now()});if(X)this.pendingPermissions.delete(X),B0.removePermission(X).catch(()=>{})}}async handleSessionStop(Z,J){let X=(await this.parseMessage(J))?.profileId||"";V1.debug("[PiAgent] Session stop request:",{profileId:X,sessionId:Z});try{await this.sessionManager.stopSession(Z)}catch(Y){V1.error("[PiAgent] Failed to stop session",{sessionId:Z,error:Y})}}async handleTogglePi(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let{enabled:X}=$.data;if(X)V1.info("[PiAgent] Enabling Pi..."),W7("pi_enabled",!0);else V1.info("[PiAgent] Disabling Pi, stopping all sessions..."),W7("pi_enabled",!1),await this.sessionManager.stopAll();this.publishToggleResponse(J,{enabled:!!X})}catch($){if(V1.error("[PiAgent] Error toggling Pi:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishToggleResponse(J,{enabled:!1,error:$ instanceof Error?$.message:"Failed to toggle Pi"})}}async handleGetEnabled(Z){let J=await this.parseMessage(Z);if(!J)return;let $=J.profileId,X=D5("pi_enabled")||!1;this.publishToggleResponse($,{enabled:X})}async handleSetModel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{model:Y}=X.data;await this.sessionManager.setModel(Z,Y)}catch(X){V1.error("[PiAgent] Error setting model:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handleSetThinkingLevel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{level:Y}=X.data;this.sessionManager.setThinkingLevel(Z,Y),this.publishStatus($,Z,{type:"thinking_level_changed",thinkingLevel:Y,timestamp:Date.now()})}catch(X){V1.error("[PiAgent] Error setting thinking level:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}async handleCompact(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId,await this.sessionManager.compactSession(Z);let Y=`pi/${$}/compact/response/${Z}`;await this.publishEncrypted(Y,{type:"compact_started",sessionId:Z},$)}catch(X){if(V1.error("[PiAgent] Error handling compact:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/compact/response/${Z}`;await this.publishEncrypted(Y,{type:"compact_error",sessionId:Z,error:X instanceof Error?X.message:"Compact failed"},$)}}}async handleSteer(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{message:Y}=X.data;await this.sessionManager.steerSession(Z,Y)}catch(X){V1.error("[PiAgent] Error handling steer:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"})}}serializeTreeNode(Z){let J=Z.entry,$={id:J.id,parentId:J.parentId,type:J.type,timestamp:J.timestamp,label:Z.label,children:Array.isArray(Z.children)?Z.children.map((X)=>this.serializeTreeNode(X)):[]};if(J.type==="message"){let X=J.message;$.role=X?.role;let Y=X?.content,Q="";if(typeof Y==="string")Q=Y;else if(Array.isArray(Y))Q=Y.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join(" ");$.preview=Q.substring(0,200)}else if(J.type==="compaction")$.summary=J.summary,$.tokensBefore=J.tokensBefore;else if(J.type==="branch_summary")$.summary=J.summary;else if(J.type==="model_change")$.modelId=J.modelId;else if(J.type==="thinking_level_change")$.thinkingLevel=J.thinkingLevel;else if(J.type==="label")$.label=J.label;else if(J.type==="session_info")$.name=J.name;else if(J.type==="custom"||J.type==="custom_message")$.customType=J.customType;return $}hasMultipleBranches(Z){for(let J of Z){if((J.children?.length||0)>1)return!0;if(J.children&&this.hasMultipleBranches(J.children))return!0}return!1}async handleTreeList(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{directoryPath:Y}=X.data||{},Q=`pi/${$}/tree/response/${Z}`,W=this.sessionManager.getSessionTree(Z);if(!W){if(!Y)throw Error("directoryPath required to read session from disk");let{piSdk:z}=await W9(),H=(await z.SessionManager.list(Y)).find((F)=>F.id===Z);if(!H)throw Error(`Pi session ${Z} not found on disk`);let V=z.SessionManager.open(H.path);W={nodes:V.getTree(),leafId:V.getLeafId()}}let K=W.nodes.map((z)=>this.serializeTreeNode(z));await this.publishEncrypted(Q,{sessionId:Z,nodes:K,leafId:W.leafId,hasMultipleBranches:this.hasMultipleBranches(K)},$)}catch(X){if(V1.error("[PiAgent] Error handling tree list:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/tree/response/${Z}`;await this.publishEncrypted(Y,{sessionId:Z,nodes:[],leafId:null,hasMultipleBranches:!1,error:X instanceof Error?X.message:"Failed to load tree"},$)}}}async handleRewind(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{targetId:Y,summarize:Q=!1,directoryPath:W,checkpointUuid:K}=X.data||{},z=Y||K,G=`pi/${$}/rewind/response/${Z}`;if(!z){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,error:"targetId is required"},$);return}if(this.sessionManager.isSessionStreaming(Z)){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,checkpointUuid:z,error:"Cannot navigate while agent is streaming. Stop the session first."},$);return}let H=this.sessionManager.getSession(Z);if(!H?.piSession){if(!W)throw Error("directoryPath required to resume session for navigation");H=await this.sessionManager.resumeSession(Z,$,"",W)}if(!H?.piSession)throw Error("Could not activate Pi session for tree navigation");let V=await this.sessionManager.navigateTree(Z,z,!!Q);if(V.cancelled||V.aborted){await this.publishEncrypted(G,{type:"rewind_failed",sessionId:Z,checkpointUuid:z,error:V.aborted?"Navigation aborted":"Navigation cancelled"},$);return}await this.publishEncrypted(G,{type:"rewind_complete",sessionId:Z,checkpointUuid:z,mode:Q?"branch_with_summary":"conversation_only",restoredMessage:V.editorText},$),this.publishStatus($,Z,{type:"session_idle",sessionId:Z,timestamp:Date.now()})}catch(X){if(V1.error("[PiAgent] Error handling rewind:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/rewind/response/${Z}`;await this.publishEncrypted(Y,{type:"rewind_failed",sessionId:Z,error:X instanceof Error?X.message:"Navigation failed"},$)}}}async handleSetLabel(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{targetId:Y,label:Q,directoryPath:W}=X.data||{},K=`pi/${$}/label/response/${Z}`;if(!Y){await this.publishEncrypted(K,{type:"label_failed",sessionId:Z,error:"targetId is required"},$);return}let z=this.sessionManager.getSession(Z);if(!z?.piSession){if(!W)throw Error("directoryPath required to resume session for labeling");z=await this.sessionManager.resumeSession(Z,$,"",W)}if(!z?.piSession)throw Error("Could not activate Pi session for labeling");let G=Q?String(Q).trim():void 0,H=this.sessionManager.setLabel(Z,Y,G);await this.publishEncrypted(K,{type:"label_set",sessionId:Z,targetId:Y,label:G,entryId:H},$)}catch(X){if(V1.error("[PiAgent] Error handling set label:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/label/response/${Z}`;await this.publishEncrypted(Y,{type:"label_failed",sessionId:Z,error:X instanceof Error?X.message:"Label update failed"},$)}}}async handleRename(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{name:Y,directoryPath:Q}=X.data||{},W=`pi/${$}/rename/response/${Z}`;if(!Y||typeof Y!=="string"||!Y.trim()){await this.publishEncrypted(W,{success:!1,sessionId:Z,error:"name is required"},$);return}let K=Y.trim(),{wasInMemory:z,session:G}=await this.sessionManager.renameSession(Z,K,Q);if(!z){if(this.publishStatus($,Z,{type:"title_generated",title:K,timestamp:Date.now()}),this.sessionsService&&Q)this.sessionsService.notifyProviderSessionUpdate(Q,{sessionId:Z,title:K,status:"idle",provider:"pi"})}else if(G)this.handleTitleGenerated(G,K);await this.publishEncrypted(W,{success:!0,sessionId:Z,name:K},$)}catch(X){if(V1.error("[PiAgent] Error handling rename:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`pi/${$}/rename/response/${Z}`;await this.publishEncrypted(Y,{success:!1,sessionId:Z,error:X instanceof Error?X.message:"Rename failed"},$)}}}async getSettingsManager(){if(this.settingsManager)return this.settingsManager;let{piSdk:Z}=await W9();return this.settingsManager=Z.SettingsManager.create(process.cwd()),this.settingsManager}async readMobileSettings(){let Z=await this.getSettingsManager(),J=Z.getCompactionSettings(),$=Z.getRetrySettings(),X=Z.getBranchSummarySettings();return{compactionEnabled:J.enabled,compactionReserveTokens:J.reserveTokens,compactionKeepRecentTokens:J.keepRecentTokens,retryEnabled:$.enabled,retryMaxRetries:$.maxRetries,retryBaseDelayMs:$.baseDelayMs,retryMaxDelayMs:$.maxDelayMs,steeringMode:Z.getSteeringMode(),followUpMode:Z.getFollowUpMode(),defaultThinkingLevel:Z.getDefaultThinkingLevel()??null,branchSummarySkipPrompt:X.skipPrompt}}async applyMobileSettings(Z){let J=await this.getSettingsManager();if(Z.compactionEnabled!==void 0)J.setCompactionEnabled(Z.compactionEnabled);if(Z.retryEnabled!==void 0)J.setRetryEnabled(Z.retryEnabled);if(Z.steeringMode!==void 0)J.setSteeringMode(Z.steeringMode);if(Z.followUpMode!==void 0)J.setFollowUpMode(Z.followUpMode);if(Z.defaultThinkingLevel!==void 0)if(Z.defaultThinkingLevel!==null)J.setDefaultThinkingLevel(Z.defaultThinkingLevel);else J.applyOverrides({defaultThinkingLevel:void 0});let $={};if(Z.compactionReserveTokens!==void 0||Z.compactionKeepRecentTokens!==void 0)$.compaction={...Z.compactionReserveTokens!==void 0&&{reserveTokens:Z.compactionReserveTokens},...Z.compactionKeepRecentTokens!==void 0&&{keepRecentTokens:Z.compactionKeepRecentTokens}};if(Z.retryMaxRetries!==void 0||Z.retryBaseDelayMs!==void 0||Z.retryMaxDelayMs!==void 0)$.retry={...Z.retryMaxRetries!==void 0&&{maxRetries:Z.retryMaxRetries},...Z.retryBaseDelayMs!==void 0&&{baseDelayMs:Z.retryBaseDelayMs},...Z.retryMaxDelayMs!==void 0&&{maxDelayMs:Z.retryMaxDelayMs}};if(Z.branchSummarySkipPrompt!==void 0)$.branchSummary={skipPrompt:Z.branchSummarySkipPrompt};if(Object.keys($).length>0)J.applyOverrides($);await J.flush()}async handleSettingsGet(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=await this.readMobileSettings(),Y=`pi/${J}/settings/response`;await this.publishEncrypted(Y,{success:!0,settings:X},J)}catch($){if(V1.error("[PiAgent] Error reading settings:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:$ instanceof Error?$.message:"Failed to read settings"},J)}}async handleSettingsSet(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=$.data?.patch;if(!X||typeof X!=="object"){await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:"patch is required"},J);return}await this.applyMobileSettings(X);let Y=await this.readMobileSettings();await this.publishEncrypted(`pi/${J}/settings/response`,{success:!0,settings:Y},J)}catch($){if(V1.error("[PiAgent] Error writing settings:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)await this.publishEncrypted(`pi/${J}/settings/response`,{success:!1,error:$ instanceof Error?$.message:"Failed to write settings"},J)}}async handleProvidersList(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=[],Y={};try{let{piSdk:K}=await W9(),z=await import("fs"),G=await import("path"),H=await import("os"),V=K.AuthStorage.create(),F=K.ModelRegistry.create(V),B=F.getError?.();if(B)V1.debug("[PiAgent] ModelRegistry parse warning:",B);let U="";try{let _=G.join(H.homedir(),".pi","agent","settings.json");U=JSON.parse(z.readFileSync(_,"utf-8")).defaultModel||""}catch{}let L=/^claude-.*-\d{8}$/,O=F.getAvailable();for(let _ of O){if(L.test(_.id))continue;if(_.id.startsWith("claude-3-"))continue;if(X.push({id:_.id,displayName:_.name||_.id,provider:_.provider,isDefault:_.id===U,reasoning_variants:_.reasoning?["minimal","low","medium","high","xhigh"]:void 0,oauth:F.isUsingOAuth(_)}),!Y[_.provider])try{Y[_.provider]=F.getProviderDisplayName(_.provider)}catch{Y[_.provider]=_.provider}}}catch(K){V1.debug("[PiAgent] Failed to load Pi ModelRegistry:",K)}if(X.length===0)X=[{id:"claude-sonnet-4-5",displayName:"Claude Sonnet 4.5",provider:"anthropic",isDefault:!0,oauth:!1},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",provider:"anthropic",isDefault:!1,oauth:!1},{id:"claude-haiku-4-5",displayName:"Claude Haiku 4.5",provider:"anthropic",isDefault:!1,oauth:!1}];let Q={};for(let K of X){let z=K.provider||"unknown";if(!Q[z])Q[z]=[];Q[z].push(K)}let W=Object.entries(Q).map(([K,z])=>({id:K,name:Y[K]??K.charAt(0).toUpperCase()+K.slice(1),models:Object.fromEntries(z.map((G)=>[G.id,{name:G.displayName||G.id,family:K,capabilities:{reasoning:!!G.reasoning_variants,attachment:!0,toolcall:!0,oauth:G.oauth},reasoning_variants:G.reasoning_variants}]))}));this.publishProviderResponse(J,{providers:W,connected:Object.keys(Q)})}catch($){if(V1.error("[PiAgent] Error listing providers:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishProviderResponse(J,{error:$ instanceof Error?$.message:"Failed to list providers"})}}handleSessionInitialized(Z){if(Z.worktreePath&&Z.tempId&&Z.sessionId)this.worktreeManager.updateSessionId(Z.worktreePath,Z.tempId,Z.sessionId);if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_started",sessionId:Z.sessionId,tempId:Z.tempId,model:Z.model,thinkingLevel:Z.thinkingLevel,worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch,slashCommands:[],agents:[],skills:[],timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:Z.status,provider:"pi"})}handleTitleGenerated(Z,J){if(this.publishStatus(Z.userId,Z.sessionId,{type:"title_generated",title:J,timestamp:Date.now()}),this.sessionsService&&Z.sessionId)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:J,status:Z.status,provider:"pi"})}handleAssistantMessage(Z,J){if(Z.sessionId)this.publishOutput(Z.userId,Z.sessionId,J)}handlePermissionRequest(Z,J){if(!Z.sessionId)return;this.pendingPermissions.set(J.request_id,{requestId:J.request_id,action:J.action,params:J.params,createdAt:Date.now()}),B0.addPermission({requestId:J.request_id,sessionId:Z.sessionId,projectPath:Z.directoryPath,action:J.action,params:J.params,createdAt:new Date().toISOString()}).catch(()=>{});let $=`pi/${Z.userId}/permission/request/${Z.sessionId}`;this.publishEncrypted($,J,Z.userId).catch((X)=>{V1.error("[PiAgent] Failed to publish permission request",{error:X instanceof Error?X.message:"Unknown error"})})}handleSessionError(Z,J){this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"error",error:J,timestamp:Date.now()})}handleSessionStopped(Z,J){if(this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"session_stopped",reason:J,timestamp:Date.now()}),this.sessionsService){if(this.sessionsService.notifySessionStopped(),Z.sessionId)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:"stopped",provider:"pi"})}}handleProcessingStarted(Z){if(Z.sessionId)this.publishStatus(Z.userId,Z.sessionId,{type:"session_processing",sessionId:Z.sessionId,timestamp:Date.now()})}handleProcessingComplete(Z){if(!Z.sessionId)return;if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()}),Z.tempId&&Z.tempId!==Z.sessionId)this.publishStatus(Z.userId,Z.tempId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()});if(this.sessionsService)this.sessionsService.notifyProviderSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"Pi Session",status:"idle",messageCount:Z.messageCount,provider:"pi"})}handleContextUpdate(Z,J){if(Z.sessionId)this.publishContextUpdate(Z.userId,Z.sessionId,J)}handleExtensionUiRequest(Z,J){let $=Z.sessionId||Z.tempId;if(!$)return;let X=`pi/${Z.userId}/extension/ui/request/${$}`;this.publishEncrypted(X,J,Z.userId).catch((Y)=>{V1.error("[PiAgent] Failed to publish extension UI request",{method:J.method,error:Y instanceof Error?Y.message:"Unknown error"})})}async handleExtensionUiResponse(Z){try{let J=await this.parseMessage(Z);if(!J)return;this.sessionManager.resolveUiResponse(J.data)}catch(J){V1.error("[PiAgent] Error handling extension UI response:",{error:J instanceof Error?J.message:"Unknown error"})}}publishStatus(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/status/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish status",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishOutput(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/output/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish output",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishContextUpdate(Z,J,$){if(!this.mqttClient)return;let X=`pi/${Z}/context/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{V1.error("[PiAgent] Failed to publish context",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishToggleResponse(Z,J){if(!this.mqttClient)return;let $=`pi/${Z}/toggle/response`;this.publishEncrypted($,J,Z).catch((X)=>{V1.error("[PiAgent] Failed to publish toggle response",{error:X instanceof Error?X.message:"Unknown error"})})}publishProviderResponse(Z,J){if(!this.mqttClient)return;let $=`pi/${Z}/providers/response`;this.publishEncrypted($,J,Z).catch((X)=>{V1.error("[PiAgent] Failed to publish provider response",{error:X instanceof Error?X.message:"Unknown error"})})}async parseMessage(Z){try{let J=JSON.parse(Z.toString());if(M1.isEncryptedEnvelope(J)){let $=J.c;if(!$)return null;let X=M1.getClientKeyOrRekey($);if(!X)return null;let Y=await M1.decrypt(X,J);return{data:JSON.parse(Y),profileId:$}}return V1.warn("[PiAgent] Received unencrypted message \u2014 dropping"),null}catch(J){return V1.warn("[PiAgent] Failed to parse message",{error:J}),null}}async publishEncrypted(Z,J,$){if(!this.mqttClient)return;if(!$)return;let X=M1.getClientKeyOrRekey($);if(!X){V1.warn(`[PiAgent] No encryption key for profile ${$} \u2014 dropping message on ${Z} (rekey requested)`);return}let Y=await M1.encrypt(X,JSON.stringify(J));Y.c=$,await this.mqttClient.publish(Z,JSON.stringify(Y),{qos:1})}cleanupStalePendingPermissions(){let Z=Date.now();for(let[J,$]of this.pendingPermissions)if(Z-$.createdAt>tW.PENDING_PERMISSION_TTL_MS)this.pendingPermissions.delete(J),B0.removePermission(J).catch(()=>{})}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.sessionManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessionCount(){return this.sessionManager.getSessionCount()}getActiveSessions(){return this.sessionManager.getActiveSessions()}async getSessionMessages(Z,J){let $=this.sessionManager.getSessionEntries(Z);if((!$||$.length===0)&&J)try{let{piSdk:K}=await W9(),G=(await K.SessionManager.list(J)).find((H)=>H.id===Z);if(G)$=K.SessionManager.open(G.path).getEntries()}catch(K){V1.warn("[PiAgent] Failed to read session messages from disk",{sessionId:Z,error:K instanceof Error?K.message:"Unknown error"})}let X=jY0($||[]),Y=this.sessionManager.getSession(Z),Q=Y?.contextUsage,W=Y?.title;return{messages:X,title:W,context:Q}}}function jY0(Z){let J=[],$=null;for(let X of Z){if(!X||X.type!=="message")continue;let Y=X.message;if(!Y)continue;let Q=X.id,W=X.timestamp||new Date().toISOString(),K=Y.role;if(K==="user"){let z;if(typeof Y.content==="string")z=Y.content;else if(Array.isArray(Y.content))z=Y.content.map((G)=>{if(G.type==="text")return{type:"text",text:G.text};if(G.type==="image"&&G.source)return{type:"image",source:{type:"base64",media_type:G.source.mediaType??G.source.media_type,data:G.source.data}};return null}).filter(Boolean);else z="";J.push({uuid:Q,parentUuid:$,timestamp:W,type:"user",role:"user",content:z}),$=Q}else if(K==="assistant"){let z=[],G=Array.isArray(Y.content)?Y.content:[];for(let H of G)if(H.type==="text"&&H.text)z.push({type:"text",text:H.text});else if(H.type==="thinking"&&H.thinking)z.push({type:"thinking",thinking:H.thinking});else if(H.type==="toolCall")z.push({type:"tool_use",id:H.id||H.toolCallId,name:H.name,input:H.arguments??H.input??{}});if(z.length===0)continue;J.push({uuid:Q,parentUuid:$,timestamp:W,type:"assistant",role:"assistant",content:z}),$=Q}else if(K==="toolResult"){let z=Y.toolCallId,G="";if(typeof Y.content==="string")G=Y.content;else if(Array.isArray(Y.content))G=Y.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
2410
2410
  `);J.push({uuid:Q,parentUuid:$,timestamp:W,type:"tool",toolName:Y.toolName,toolUseId:z,isError:!!Y.isError,content:[{type:"tool_result",tool_use_id:z,content:G,is_error:!!Y.isError}]}),$=Q}}return J}import*as T0 from"fs/promises";import*as LM from"fs";import*as W4 from"path";import*as qZ from"fs/promises";var OY=S(),Gz1=10485760;async function A0(Z,J={}){let{maxSize:$=Gz1,encoding:X="utf-8",logWarnings:Y=!0}=J;try{let Q=await qZ.stat(Z);if(!Q.isFile()){if(Y)OY.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Q.size>$){if(Y)OY.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Q.size,maxSize:$});return null}return await qZ.readFile(Z,X)}catch(Q){if(Q.code!=="ENOENT"&&Y)OY.debug("[SafeFS] Error reading file",{filePath:Z,error:Q});return null}}async function Hz1(Z,J={}){let{maxSize:$=Gz1,logWarnings:X=!0}=J;try{let Y=await qZ.stat(Z);if(!Y.isFile()){if(X)OY.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Y.size>$){if(X)OY.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Y.size,maxSize:$});return null}return await qZ.readFile(Z)}catch(Y){if(Y.code!=="ENOENT"&&X)OY.debug("[SafeFS] Error reading file",{filePath:Z,error:Y});return null}}async function H6(Z){try{return(await qZ.stat(Z)).isDirectory()}catch{return!1}}async function z7(Z){try{return await qZ.stat(Z)}catch{return null}}var G7=S();class DF{validatePath(Z,J){try{let $=W4.resolve(Z),X=W4.resolve($,J);if(!(X===$||X.startsWith($+W4.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};try{let Q=LM.realpathSync(X),W=LM.realpathSync($);if(!(Q===W||Q.startsWith(W+W4.sep)))return{valid:!1,fullPath:"",error:"Symlink escape detected: symlink points outside project directory"}}catch{}return{valid:!0,fullPath:X}}catch($){return{valid:!1,fullPath:"",error:`Path validation error: ${$ instanceof Error?$.message:"Unknown error"}`}}}async listDirectory(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{entries:[],error:$.error};try{if(!(await T0.stat($.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let Y=await T0.readdir($.fullPath,{withFileTypes:!0}),Q=await Promise.all(Y.map(async(W)=>{let K=W4.join($.fullPath,W.name);try{let z=await T0.stat(K);return{name:W.name,type:W.isDirectory()?"directory":"file",size:W.isFile()?z.size:void 0,modified:z.mtime.toISOString()}}catch{return{name:W.name,type:W.isDirectory()?"directory":"file"}}}));return Q.sort((W,K)=>{if(W.type!==K.type)return W.type==="directory"?-1:1;return W.name.localeCompare(K.name,void 0,{sensitivity:"base"})}),{entries:Q}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] listDirectory error",{error:Y,path:$.fullPath}),{entries:[],error:`Failed to list directory: ${Y}`}}}async readFile(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{content:"",size:0,error:$.error};try{let X=await z7($.fullPath);if(!X||!X.isFile())return{content:"",size:0,error:"Path is not a file"};let Y=await A0($.fullPath);if(Y===null)return{content:"",size:0,error:"Failed to read file"};return{content:Y,size:Number(X.size)}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] readFile error",{error:Y,path:$.fullPath}),{content:"",size:0,error:`Failed to read file: ${Y}`}}}async writeFile(Z,J,$){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{let Y=W4.dirname(X.fullPath);return await T0.mkdir(Y,{recursive:!0}),await T0.writeFile(X.fullPath,$,"utf-8"),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return G7.error("[FileManager] writeFile error",{error:Q,path:X.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}async createFile(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{try{return await T0.access($.fullPath),{success:!1,error:"File already exists"}}catch{}let X=W4.basename(J);if(!this.isValidFilename(X))return{success:!1,error:"Invalid filename"};let Y=W4.dirname($.fullPath);return await T0.mkdir(Y,{recursive:!0}),await T0.writeFile($.fullPath,"","utf-8"),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] createFile error",{error:Y,path:$.fullPath}),{success:!1,error:`Failed to create file: ${Y}`}}}async createDirectory(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{let X=W4.basename(J);if(!this.isValidFilename(X))return{success:!1,error:"Invalid directory name"};try{if((await T0.stat($.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await T0.mkdir($.fullPath,{recursive:!0}),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] createDirectory error",{error:Y,path:$.fullPath}),{success:!1,error:`Failed to create directory: ${Y}`}}}async deleteFile(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{if(!(await T0.stat($.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await T0.unlink($.fullPath),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] deleteFile error",{error:Y,path:$.fullPath}),{success:!1,error:`Failed to delete file: ${Y}`}}}async deleteDirectory(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};if($.fullPath===W4.resolve(Z))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await T0.stat($.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await T0.rm($.fullPath,{recursive:!0,force:!0}),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] deleteDirectory error",{error:Y,path:$.fullPath}),{success:!1,error:`Failed to delete directory: ${Y}`}}}async pathExists(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return!1;try{return await T0.access($.fullPath),!0}catch{return!1}}async getStats(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return null;try{let X=await T0.stat($.fullPath);return{isFile:X.isFile(),isDirectory:X.isDirectory(),size:X.size,modified:X.mtime.toISOString()}}catch{return null}}async readFileBinary(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return{content:Buffer.alloc(0),size:0,mimeType:"",error:$.error};try{let X=await z7($.fullPath);if(!X||!X.isFile())return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Path is not a file"};let Y=52428800;if(X.size>Y)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"File exceeds maximum size of 50MB"};let Q=await Hz1($.fullPath,{maxSize:Y});if(Q===null)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Failed to read file"};let W=this.getMimeType(W4.basename(J));return{content:Q,size:Number(X.size),mimeType:W}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return G7.error("[FileManager] readFileBinary error",{error:Y,path:$.fullPath}),{content:Buffer.alloc(0),size:0,mimeType:"",error:`Failed to read file: ${Y}`}}}async writeFileBinary(Z,J,$){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{let Y=W4.basename(J);if(!this.isValidFilename(Y))return{success:!1,error:"Invalid filename"};let Q=W4.dirname(X.fullPath);return await T0.mkdir(Q,{recursive:!0}),await T0.writeFile(X.fullPath,$),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return G7.error("[FileManager] writeFileBinary error",{error:Q,path:X.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}getMimeType(Z){let J=W4.extname(Z).toLowerCase();return{".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".tiff":"image/tiff",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".txt":"text/plain",".json":"application/json",".xml":"application/xml",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".tsx":"application/typescript",".jsx":"application/javascript",".md":"text/markdown",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".7z":"application/x-7z-compressed",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".m4a":"audio/mp4",".flac":"audio/flac",".aac":"audio/aac",".mp4":"video/mp4",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".webm":"video/webm",".wmv":"video/x-ms-wmv",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".apk":"application/vnd.android.package-archive",".ipa":"application/octet-stream",".exe":"application/x-msdownload",".dmg":"application/x-apple-diskimage",".deb":"application/x-deb",".rpm":"application/x-rpm"}[J]||"application/octet-stream"}isValidFilename(Z){if(!Z||Z.length===0)return!1;if(Z.includes("/")||Z.includes("\\"))return!1;let J=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"],$=(Z.split(".")[0]||"").toUpperCase();if(J.includes($))return!1;if(/[<>:"|?*\x00-\x1f]/.test(Z))return!1;if(Z==="."||Z==="..")return!1;return!0}}import*as DM from"path";var V6=S(),_Y=51200,Vz1=50,NY0=60000,Fz1=300000;class OF extends Q0{name="File Browser Service";get logPrefix(){return"[FileBrowser]"}fileManager;fileSaveOperations=new Map;binaryUploadOperations=new Map;staleOpCleanupInterval=null;constructor(){super();this.fileManager=new DF}async onStart(){this.staleOpCleanupInterval=setInterval(()=>{this.cleanupStaleOperations()},NY0)}async onStop(){if(this.staleOpCleanupInterval)clearInterval(this.staleOpCleanupInterval),this.staleOpCleanupInterval=null;this.fileSaveOperations.clear(),this.binaryUploadOperations.clear()}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("files/list/request",(Z,J)=>{this.handleDirectoryListRequest(J)}),this.registerHandler("files/content/request",(Z,J)=>{this.handleFileContentRequest(J)}),this.registerHandler("files/save/request",(Z,J)=>{this.handleFileSaveRequest(J)}),this.registerHandler("files/create/request",(Z,J)=>{this.handleFileCreateRequest(J)}),this.registerHandler("files/delete/request",(Z,J)=>{this.handleFileDeleteRequest(J)}),this.registerHandler("files/upload/request",(Z,J)=>{this.handleBinaryUploadRequest(J)}),this.registerHandler("files/download/request",(Z,J)=>{this.handleBinaryDownloadRequest(J)}),V6.debug("[FileBrowser] MQTT handlers registered")}async handleDirectoryListRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=await this.fileManager.listDirectory($.projectPath,$.relativePath),Q={path:$.relativePath,entries:Y.entries,timestamp:Date.now(),error:Y.error};await this.publishResponse(this.buildResponseTopic("files/list",$.clientId,$.requestId),Q,X),this.requestsHandled++}catch(J){V6.error("[FileBrowser] Error handling directory list request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileContentRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=await this.fileManager.readFile($.projectPath,$.relativePath),Q=this.buildResponseTopic("files/content",$.clientId,$.requestId);if(Y.error){let K={path:$.relativePath,chunk:{chunkIndex:0,totalChunks:1,content:""},totalSize:0,timestamp:Date.now(),error:Y.error};await this.publishResponse(Q,K,X);return}let W=Math.max(1,Math.ceil(Y.content.length/_Y));for(let K=0;K<W;K++){let z=K*_Y,G=Math.min(z+_Y,Y.content.length),H=Y.content.slice(z,G),V={path:$.relativePath,chunk:{chunkIndex:K,totalChunks:W,content:H},totalSize:Y.size,timestamp:Date.now()};if(await this.publishResponse(Q,V,X),K<W-1)await this.delay(Vz1)}this.requestsHandled++}catch(J){V6.error("[FileBrowser] Error handling file content request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileSaveRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=`${$.clientId}:${$.relativePath}`;if($.chunk.chunkIndex===0)this.fileSaveOperations.set(Y,{chunks:new Map,totalChunks:$.chunk.totalChunks,totalSize:$.totalSize,startedAt:Date.now()});let Q=this.fileSaveOperations.get(Y);if(!Q){await this.sendSaveResponse($,X,!1,"Save operation not initialized");return}if(Q.chunks.set($.chunk.chunkIndex,$.chunk.content),await this.sendSaveResponse($,X,!0),Q.chunks.size===Q.totalChunks){let W=[];for(let G=0;G<Q.totalChunks;G++){let H=Q.chunks.get(G);if(H===void 0){V6.error(`[FileBrowser] Missing chunk ${G} of ${Q.totalChunks} for ${Y}`),this.fileSaveOperations.delete(Y),await this.sendSaveResponse($,X,!1,`Missing chunk ${G} \u2014 file save aborted`);return}W.push(H)}let K=W.join(""),z=await this.fileManager.writeFile($.projectPath,$.relativePath,K);if(this.fileSaveOperations.delete(Y),!z.error)this.requestsHandled++}}catch(J){V6.error("[FileBrowser] Error handling file save request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileCreateRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y;if($.type==="directory")Y=await this.fileManager.createDirectory($.projectPath,$.relativePath);else Y=await this.fileManager.createFile($.projectPath,$.relativePath);let Q={path:$.relativePath,success:Y.success,type:$.type,timestamp:Date.now(),error:Y.error};if(await this.publishResponse(this.buildResponseTopic("files/create",$.clientId,$.requestId),Q,X),Y.success)this.requestsHandled++}catch(J){V6.error("[FileBrowser] Error handling file create request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileDeleteRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=await this.fileManager.getStats($.projectPath,$.relativePath),Q;if(!Y)Q={success:!1,error:"Path does not exist"};else if(Y.isDirectory)Q=await this.fileManager.deleteDirectory($.projectPath,$.relativePath);else Q=await this.fileManager.deleteFile($.projectPath,$.relativePath);let W={path:$.relativePath,success:Q.success,timestamp:Date.now(),error:Q.error};if(await this.publishResponse(this.buildResponseTopic("files/delete",$.clientId,$.requestId),W,X),Q.success)this.requestsHandled++}catch(J){V6.error("[FileBrowser] Error handling file delete request",{error:J instanceof Error?J.message:"Unknown error"})}}async sendSaveResponse(Z,J,$,X){let Y={path:Z.relativePath,success:$,chunkIndex:Z.chunk.chunkIndex,totalChunks:Z.chunk.totalChunks,timestamp:Date.now(),error:X};await this.publishResponse(this.buildResponseTopic("files/save",Z.clientId,Z.requestId),Y,J)}delay(Z){return new Promise((J)=>setTimeout(J,Z))}async handleBinaryUploadRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=`${$.clientId}:${$.relativePath}`;if($.chunk.chunkIndex===0){if($.totalSize>52428800){await this.sendBinaryUploadResponse($,X,!1,"File exceeds 50MB limit",0);return}this.binaryUploadOperations.set(Y,{chunks:new Map,totalChunks:$.chunk.totalChunks,totalSize:$.totalSize,filename:$.filename,mimeType:$.mimeType,receivedBytes:0,startedAt:Date.now()})}let Q=this.binaryUploadOperations.get(Y);if(!Q){await this.sendBinaryUploadResponse($,X,!1,"Upload operation not initialized",0);return}let W=Buffer.from($.chunk.data,"base64");if(Q.chunks.set($.chunk.chunkIndex,W),Q.receivedBytes+=W.length,await this.sendBinaryUploadResponse($,X,!0,void 0,Q.receivedBytes),Q.chunks.size===Q.totalChunks){let K=[];for(let H=0;H<Q.totalChunks;H++){let V=Q.chunks.get(H);if(!V){V6.error(`[FileBrowser] Missing binary chunk ${H} of ${Q.totalChunks} for ${Y}`),this.binaryUploadOperations.delete(Y),await this.sendBinaryUploadResponse($,X,!1,`Missing chunk ${H} \u2014 upload aborted`);return}K.push(V)}let z=Buffer.concat(K),G=await this.fileManager.writeFileBinary($.projectPath,$.relativePath,z);if(this.binaryUploadOperations.delete(Y),G.error)V6.error("[FileBrowser] Binary upload write failed",{error:G.error});else this.requestsHandled++,V6.debug("[FileBrowser] Binary upload completed",{path:$.relativePath,size:z.length})}}catch(J){V6.error("[FileBrowser] Error handling binary upload",{error:J instanceof Error?J.message:"Unknown error"})}}async sendBinaryUploadResponse(Z,J,$,X,Y){let Q={path:Z.relativePath,success:$,chunkIndex:Z.chunk.chunkIndex,totalChunks:Z.chunk.totalChunks,bytesReceived:Y||0,timestamp:Date.now(),error:X};await this.publishResponse(this.buildResponseTopic("files/upload",Z.clientId,Z.requestId),Q,J)}async handleBinaryDownloadRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("files/download",$.clientId,$.requestId),Q=await this.fileManager.readFileBinary($.projectPath,$.relativePath);if(Q.error){let G={path:$.relativePath,filename:DM.basename($.relativePath),mimeType:"",chunk:{chunkIndex:0,totalChunks:1,data:""},totalSize:0,timestamp:Date.now(),error:Q.error};await this.publishResponse(Y,G,X);return}let W=Q.content.toString("base64"),K=Math.max(1,Math.ceil(W.length/_Y)),z=DM.basename($.relativePath);for(let G=0;G<K;G++){let H=G*_Y,V=Math.min(H+_Y,W.length),F=W.slice(H,V),B={path:$.relativePath,filename:z,mimeType:Q.mimeType,chunk:{chunkIndex:G,totalChunks:K,data:F},totalSize:Q.size,timestamp:Date.now()};if(await this.publishResponse(Y,B,X),G<K-1)await this.delay(Vz1)}this.requestsHandled++,V6.debug("[FileBrowser] Binary download completed",{path:$.relativePath,size:Q.size,chunks:K})}catch(J){V6.error("[FileBrowser] Error handling binary download",{error:J instanceof Error?J.message:"Unknown error"})}}cleanupStaleOperations(){let Z=Date.now();for(let[J,$]of this.fileSaveOperations)if(Z-$.startedAt>Fz1)V6.warn(`[FileBrowser] Cleaning up stale file save operation: ${J} (age: ${Math.round((Z-$.startedAt)/1000)}s)`),this.fileSaveOperations.delete(J);for(let[J,$]of this.binaryUploadOperations)if(Z-$.startedAt>Fz1)V6.warn(`[FileBrowser] Cleaning up stale binary upload operation: ${J} (age: ${Math.round((Z-$.startedAt)/1000)}s)`),this.binaryUploadOperations.delete(J)}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,pendingSaveOperations:this.fileSaveOperations.size}}}var Z1=S();class _F extends Q0{name="Git Service";get logPrefix(){return"[GitService]"}worktreeManager;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){super();this.worktreeManager=new k8}async onStart(){if(this.ghAuthResult=await EW1(),!this.ghAuthResult.authenticated)Z1.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else{Z1.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username,gitProtocol:this.ghAuthResult.gitProtocol});let Z=await IW1();if(!Z.success)Z1.warn("[GitService] Could not sync gh config git_protocol",{error:Z.error});let J=await SW1();if(!J.success)Z1.warn("[GitService] Could not setup git credential helper",{error:J.error})}}async onStop(){this.worktreeManager.clearCache()}registerMQTTHandlers(){if(!this.mqttClient)return;this.registerHandler("git/orgs/request",(Z,J)=>{this.handleOrgsRequest(J)}),this.registerHandler("git/repos/request",(Z,J)=>{this.handleReposRequest(J)}),this.registerHandler("git/repos/search/request",(Z,J)=>{this.handleSearchReposRequest(J)}),this.registerHandler("git/branches/request",(Z,J)=>{this.handleBranchesRequest(J)}),this.registerHandler("git/clone/request",(Z,J)=>{this.handleCloneRequest(J)}),this.registerHandler("git/is-repo/request",(Z,J)=>{this.handleIsRepoRequest(J)}),this.registerHandler("git/worktree/get-or-create/request",(Z,J)=>{this.handleWorktreeGetOrCreateRequest(J)}),this.registerHandler("git/worktree/get/request",(Z,J)=>{this.handleWorktreeGetRequest(J)}),this.registerHandler("git/worktree/list/request",(Z,J)=>{this.handleWorktreeListRequest(J)}),this.registerHandler("git/status/request",(Z,J)=>{this.handleStatusRequest(J)}),this.registerHandler("git/diff/request",(Z,J)=>{this.handleDiffRequest(J)}),this.registerHandler("git/changes/all/request",(Z,J)=>{this.handleChangesAllRequest(J)}),this.registerHandler("git/stage/request",(Z,J)=>{this.handleStageRequest(J)}),this.registerHandler("git/unstage/request",(Z,J)=>{this.handleUnstageRequest(J)}),this.registerHandler("git/commit/request",(Z,J)=>{this.handleCommitRequest(J)}),this.registerHandler("git/unpushed/request",(Z,J)=>{this.handleUnpushedCommitsRequest(J)}),this.registerHandler("git/push/request",(Z,J)=>{this.handlePushRequest(J)}),this.registerHandler("git/history/request",(Z,J)=>{this.handleHistoryRequest(J)}),this.registerHandler("git/commit-details/request",(Z,J)=>{this.handleCommitDetailsRequest(J)}),this.registerHandler("git/commit-file-diff/request",(Z,J)=>{this.handleCommitFileDiffRequest(J)}),this.registerHandler("git/sync/request",(Z,J)=>{this.handleSyncRequest(J)}),this.registerHandler("git/create-pr/request",(Z,J)=>{this.handleCreatePRRequest(J)}),this.registerHandler("git/default-branch/request",(Z,J)=>{this.handleDefaultBranchRequest(J)}),this.registerHandler("git/existing-pr/request",(Z,J)=>{this.handleExistingPRRequest(J)}),this.registerHandler("git/remote-branches/request",(Z,J)=>{this.handleRemoteBranchesRequest(J)}),this.registerHandler("git/create-branch/request",(Z,J)=>{this.handleCreateBranchRequest(J)}),this.registerHandler("git/local-branches/request",(Z,J)=>{this.handleLocalBranchesRequest(J)}),this.registerHandler("git/checkout-branch/request",(Z,J)=>{this.handleCheckoutBranchRequest(J)}),Z1.debug("[GitService] MQTT handlers registered")}async handleOrgsRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z1.debug("[GitService] Orgs request",{clientId:$.clientId}),!this.ghAuthResult.authenticated){let W={orgs:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/orgs/${$.clientId}/response`,W,X);return}let Q={orgs:await iT(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling orgs request",{error:J})}}async handleReposRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=$.requestId||$.clientId;if(Z1.debug("[GitService] Repos request",{clientId:$.clientId,requestId:$.requestId,org:$.org,limit:$.limit}),!this.ghAuthResult.authenticated){let K={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/${Y}/response`,K,X);return}let W={repos:await JF($.org,$.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${Y}/response`,W,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling repos request",{error:J})}}async handleSearchReposRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z1.debug("[GitService] Search repos request",{clientId:$.clientId,query:$.query,limit:$.limit}),!this.ghAuthResult.authenticated){let Q={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/search/${$.clientId}/response`,Q,X);return}let Y=$.clientId;await yW1($.query,async(Q,W,K)=>{let z={repos:Q,timestamp:Date.now(),source:W,isComplete:K};await this.publishResponse(`git/repos/search/${Y}/response`,z,X),Z1.debug("[GitService] Sent search results",{source:W,count:Q.length,isComplete:K})},$.limit||50),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling search repos request",{error:J})}}async handleBranchesRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z1.debug("[GitService] Branches request",{clientId:$.clientId,owner:$.owner,repo:$.repo}),!this.ghAuthResult.authenticated){let W={branches:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/branches/${$.clientId}/response`,W,X);return}let Y=await kW1($.owner,$.repo),Q={branches:Y.branches,defaultBranch:Y.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/branches/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling branches request",{error:J})}}async handleCloneRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z1.debug("[GitService] Clone request",{clientId:$.clientId,repoUrl:$.repoUrl,targetPath:$.targetPath,branch:$.branch}),!this.ghAuthResult.authenticated){let W={success:!1,error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/clone/${$.clientId}/response`,W,X);return}let Y=await xW1($.repoUrl,$.targetPath,$.branch),Q=Y.success?{success:!0,path:Y.path,defaultBranch:Y.defaultBranch,timestamp:Date.now()}:{success:!1,error:Y.error||"Clone failed",timestamp:Date.now()};await this.publishResponse(`git/clone/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling clone request",{error:J})}}async handleIsRepoRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Is-repo request",{clientId:$.clientId,path:$.path});let Y=await I6($.path),Q;if(Y){let[W,K,z]=await Promise.all([a4($.path),$$($.path),iW1($.path)]);Q={isGitRepo:!0,repoRoot:W||void 0,defaultBranch:K||void 0,remoteUrl:z||void 0,timestamp:Date.now()}}else Q={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling is-repo request",{error:Y});let Q={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${$.clientId}/response`,Q,X)}}async handleWorktreeGetOrCreateRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Worktree get-or-create request",{clientId:$.clientId,repoPath:$.repoPath,sessionId:$.sessionId});let{worktree:Y,isNew:Q}=await this.worktreeManager.getOrCreateForSession($.sessionId,$.repoPath),W={success:!0,worktreePath:Y.path,branch:Y.branch,isNew:Q,timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${$.clientId}/response`,W,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling worktree get-or-create request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${$.clientId}/response`,Q,X)}}async handleWorktreeGetRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;Z1.debug("[GitService] Worktree get request",{clientId:$.clientId,repoPath:$.repoPath,sessionId:$.sessionId});let Y=await this.worktreeManager.getWorktreeForSession($.sessionId,$.repoPath),Q=Y?{exists:!0,worktreePath:Y.path,branch:Y.branch,timestamp:Date.now()}:{exists:!1,timestamp:Date.now()};await this.publishResponse(`git/worktree/get/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling worktree get request",{error:J})}}async handleWorktreeListRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;Z1.debug("[GitService] Worktree list request",{clientId:$.clientId,repoPath:$.repoPath});let Q={worktrees:await this.worktreeManager.listWorktreesForRepo($.repoPath),timestamp:Date.now()};await this.publishResponse(`git/worktree/list/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z1.error("[GitService] Error handling worktree list request",{error:J})}}async handleStatusRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Status request",{clientId:$.clientId,path:$.path});let Q={success:!0,status:await nT($.path),timestamp:Date.now()};await this.publishResponse(`git/status/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling status request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/status/${$.clientId}/response`,Q,X)}}async handleDiffRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Diff request",{clientId:$.clientId,path:$.path,file:$.file,staged:$.staged});let Y=await hW1($.path,$.file,$.staged),Q={success:!0,diff:Y.diff,isBinary:Y.isBinary,timestamp:Date.now()};await this.publishResponse(`git/diff/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling diff request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/diff/${$.clientId}/response`,Q,X)}}async handleChangesAllRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Changes all request",{clientId:$.clientId,repoPath:$.repoPath});let Y=await this.worktreeManager.listWorktreesForRepo($.repoPath),Q={repoPath:$.repoPath,worktrees:[],totalChanges:0};for(let K of Y)try{let z=await nT(K.path);Q.worktrees.push({worktreePath:K.path,branch:K.branch,sessionId:K.sessionId,changes:z.files,totalCount:z.files.length}),Q.totalChanges+=z.files.length}catch(z){Z1.warn("[GitService] Failed to get status for worktree",{path:K.path,error:z})}let W={success:!0,changes:Q,timestamp:Date.now()};await this.publishResponse(`git/changes/all/${$.clientId}/response`,W,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling changes all request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/changes/all/${$.clientId}/response`,Q,X)}}async handleStageRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Stage request",{clientId:$.clientId,path:$.path,files:$.files}),await fW1($.path,$.files);let Y={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${$.clientId}/response`,Y,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling stage request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/stage/${$.clientId}/response`,Q,X)}}async handleUnstageRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Unstage request",{clientId:$.clientId,path:$.path,files:$.files}),await bW1($.path,$.files);let Y={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${$.clientId}/response`,Y,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling unstage request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unstage/${$.clientId}/response`,Q,X)}}async handleCommitRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Commit request",{clientId:$.clientId,path:$.path,signoff:$.signoff});let Q={success:!0,commit:await gW1($.path,$.message,$.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling commit request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit/${$.clientId}/response`,Q,X)}}async handleUnpushedCommitsRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Unpushed commits request",{clientId:$.clientId,path:$.path});let Y=await VY($.path),Q={success:!0,commits:Y.commits,upstream:Y.upstream,ahead:Y.ahead,timestamp:Date.now()};await this.publishResponse(`git/unpushed/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling unpushed commits request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unpushed/${$.clientId}/response`,Q,X)}}async handlePushRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Push request",{clientId:$.clientId,path:$.path,force:$.force});let Y=await nW1($.path,$.force),Q={success:!0,commitsPushed:Y.commitsPushed,remote:Y.remote,branch:Y.branch,timestamp:Date.now()};await this.publishResponse(`git/push/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling push request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/push/${$.clientId}/response`,Q,X)}}async handleHistoryRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] History request",{clientId:$.clientId,path:$.path,limit:$.limit});let Y=await aW1($.path,$.limit||50),Q={success:!0,commits:Y.commits,totalCount:Y.totalCount,timestamp:Date.now()};await this.publishResponse(`git/history/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling history request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/history/${$.clientId}/response`,Q,X)}}async handleCommitDetailsRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Commit details request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash});let Q={success:!0,commit:await oW1($.path,$.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling commit details request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-details/${$.clientId}/response`,Q,X)}}async handleCommitFileDiffRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Commit file diff request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash,filePath:$.filePath});let Y=await sW1($.path,$.commitHash,$.filePath),Q={success:!0,diff:Y.diff,isBinary:Y.isBinary,timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling commit file diff request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${$.clientId}/response`,Q,X)}}async handleSyncRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Sync request",{clientId:$.clientId,path:$.path});let Y=await rW1($.path),Q=Y.success?{success:!0,action:Y.action,commitsPulled:Y.commitsPulled,commitsPushed:Y.commitsPushed,timestamp:Date.now()}:{success:!1,action:Y.action,commitsPulled:Y.commitsPulled,commitsPushed:Y.commitsPushed,error:Y.error||"Sync failed",conflictedFiles:Y.conflictedFiles,timestamp:Date.now()};await this.publishResponse(`git/sync/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling sync request",{error:Y});let Q={success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/sync/${$.clientId}/response`,Q,X)}}async handleCreatePRRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Create PR request",{clientId:$.clientId,path:$.path,title:$.title,baseBranch:$.baseBranch,draft:$.draft});let Y=await tW1($.path,$.title,$.body,$.baseBranch,$.draft),Q=Y.success?{success:!0,prNumber:Y.prNumber,prUrl:Y.prUrl,timestamp:Date.now()}:{success:!1,error:Y.error||"Failed to create pull request",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling create PR request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${$.clientId}/response`,Q,X)}}async handleDefaultBranchRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Default branch request",{clientId:$.clientId,path:$.path});let Y=await aT($.path),Q=Y?{success:!0,defaultBranch:Y,timestamp:Date.now()}:{success:!1,error:"Could not determine default branch",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling default branch request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${$.clientId}/response`,Q,X)}}async handleExistingPRRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Existing PR request",{clientId:$.clientId,path:$.path});let Y=await eW1($.path),Q={exists:Y.exists,prNumber:Y.prNumber,prUrl:Y.prUrl,title:Y.title,state:Y.state,draft:Y.draft,error:Y.error,timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling existing PR request",{error:Y});let Q={exists:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${$.clientId}/response`,Q,X)}}async handleRemoteBranchesRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Remote branches request",{clientId:$.clientId,path:$.path});let Y=await ZK1($.path),Q={success:!0,branches:Y.branches,defaultBranch:Y.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling remote branches request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${$.clientId}/response`,Q,X)}}async handleCreateBranchRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Create branch request",{clientId:$.clientId,path:$.path,branchName:$.branchName,checkout:$.checkout});let Y=await mW1($.path,$.branchName,$.checkout!==!1),Q=Y.success?{success:!0,branchName:$.branchName,timestamp:Date.now()}:{success:!1,error:Y.error||"Failed to create branch",timestamp:Date.now()};await this.publishResponse(`git/create-branch/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling create branch request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-branch/${$.clientId}/response`,Q,X)}}async handleLocalBranchesRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Local branches request",{clientId:$.clientId,path:$.path});let Y=await dW1($.path),Q={success:!0,branches:Y.branches,currentBranch:Y.currentBranch,timestamp:Date.now()};await this.publishResponse(`git/local-branches/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling local branches request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/local-branches/${$.clientId}/response`,Q,X)}}async handleCheckoutBranchRequest(Z){let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;try{Z1.debug("[GitService] Checkout branch request",{clientId:$.clientId,path:$.path,branchName:$.branchName});let Y=await uW1($.path,$.branchName),Q=Y.success?{success:!0,branchName:$.branchName,timestamp:Date.now()}:{success:!1,error:Y.error||"Failed to checkout branch",timestamp:Date.now()};await this.publishResponse(`git/checkout-branch/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z1.error("[GitService] Error handling checkout branch request",{error:Y});let Q={success:!1,error:Y instanceof Error?Y.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/checkout-branch/${$.clientId}/response`,Q,X)}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,activeWorktrees:this.worktreeManager.getActiveWorktreeCount(),ghAuthenticated:this.ghAuthResult.authenticated,ghInstalled:this.ghAuthResult.installed,ghInPath:this.ghAuthResult.inPath,ghError:this.ghAuthResult.error,ghUsername:this.ghAuthResult.username}}}import*as Oz1 from"path";import*as wF from"path";import*as Bz1 from"os";import*as AF from"fs";var M0=S(),JK=wF.join(Bz1.homedir(),".ccc"),eW=wF.join(JK,"device-tokens.json"),ZK=wF.join(JK,"notification-preferences.json");class Uz1{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if(!AF.existsSync(JK))AF.mkdirSync(JK,{recursive:!0}),M0.debug("[NotificationStorage] Created .ccc directory:",JK)}catch(Z){throw M0.error("[NotificationStorage] Error ensuring directory:",Z),Z}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let Z=Bun.file(eW);if(await Z.exists()){let J=await Z.text(),$=JSON.parse(J);if($&&typeof $==="object"&&Array.isArray($.tokens)){let X=$;return this.tokensCache=X,M0.debug("[NotificationStorage] Loaded tokens:",{count:X.tokens.length}),X}else if($&&typeof $==="object")return M0.warn("[NotificationStorage] Invalid tokens file format, attempting to recover data"),this.tokensCache={tokens:Array.isArray($.tokens)?$.tokens:[]},await this.saveTokens(this.tokensCache),this.tokensCache;else{M0.error("[NotificationStorage] Completely invalid tokens file format, creating backup");let X=`${eW}.backup.${Date.now()}`;await Bun.write(X,J),M0.error("[NotificationStorage] Backup saved to:",X)}}}catch(Z){M0.error("[NotificationStorage] Error loading tokens:",Z);try{let J=Bun.file(eW);if(await J.exists()){let $=await J.text(),X=`${eW}.backup.${Date.now()}`;await Bun.write(X,$),M0.error("[NotificationStorage] Corrupted file backed up to:",X)}}catch{}}return this.tokensCache={tokens:[]},this.tokensCache}async saveTokens(Z){try{await this.ensureDirectory(),await Bun.write(eW,JSON.stringify(Z,null,2)),this.tokensCache=Z,M0.debug("[NotificationStorage] Saved tokens:",{count:Z.tokens.length})}catch(J){throw M0.error("[NotificationStorage] Error saving tokens:",J),J}}async registerToken(Z,J,$,X,Y){let Q=await this.loadTokens(),W=new Date().toISOString(),K=Q.tokens.findIndex((H)=>H.deviceId===Z),z=K>=0?Q.tokens[K]:void 0,G={deviceId:Z,fcmToken:J,expoPushToken:$,platform:X,deviceInfo:Y,createdAt:z?.createdAt??W,lastUsed:W};if(K>=0)Q.tokens[K]=G,M0.debug("[NotificationStorage] Updated device token:",{deviceId:Z,platform:X,hasExpoPushToken:!!$});else Q.tokens.push(G),M0.debug("[NotificationStorage] Registered new device token:",{deviceId:Z,platform:X,hasExpoPushToken:!!$});return await this.saveTokens(Q),G}async unregisterToken(Z){let J=await this.loadTokens(),$=J.tokens.length;if(J.tokens=J.tokens.filter((X)=>X.deviceId!==Z),J.tokens.length<$)return await this.saveTokens(J),M0.debug("[NotificationStorage] Unregistered device token:",{deviceId:Z}),!0;return!1}async getToken(Z){return(await this.loadTokens()).tokens.find(($)=>$.deviceId===Z)}async getAllTokens(){return(await this.loadTokens()).tokens}async getDeviceCount(){return(await this.loadTokens()).tokens.length}async updateLastUsed(Z){let J=await this.loadTokens(),$=J.tokens.find((X)=>X.deviceId===Z);if($)$.lastUsed=new Date().toISOString(),await this.saveTokens(J)}async cleanupOldTokens(Z=90){let J=await this.loadTokens(),$=new Date;$.setDate($.getDate()-Z);let X=$.toISOString(),Y=J.tokens.length;J.tokens=J.tokens.filter((W)=>W.lastUsed>X);let Q=Y-J.tokens.length;if(Q>0)await this.saveTokens(J),M0.debug("[NotificationStorage] Cleaned up old tokens:",{removed:Q,remaining:J.tokens.length});return Q}async loadPreferences(){if(this.preferencesCache)return this.preferencesCache;try{let Z=Bun.file(ZK);if(await Z.exists()){let J=await Z.text(),$=JSON.parse(J);if($&&typeof $==="object"&&typeof $.preferences==="object"&&!Array.isArray($.preferences)){let X=$;return this.preferencesCache=X,M0.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys(X.preferences).length}),X}else if($&&typeof $==="object")return M0.warn("[NotificationStorage] Invalid preferences file format, attempting to recover data"),this.preferencesCache={preferences:$.preferences&&typeof $.preferences==="object"&&!Array.isArray($.preferences)?$.preferences:{}},await this.savePreferences(this.preferencesCache),this.preferencesCache;else{M0.error("[NotificationStorage] Completely invalid preferences file format, creating backup");let X=`${ZK}.backup.${Date.now()}`;await Bun.write(X,J),M0.error("[NotificationStorage] Backup saved to:",X)}}}catch(Z){M0.error("[NotificationStorage] Error loading preferences:",Z);try{let J=Bun.file(ZK);if(await J.exists()){let $=await J.text(),X=`${ZK}.backup.${Date.now()}`;await Bun.write(X,$),M0.error("[NotificationStorage] Corrupted file backed up to:",X)}}catch{}}return this.preferencesCache={preferences:{}},this.preferencesCache}async savePreferences(Z){try{await this.ensureDirectory(),await Bun.write(ZK,JSON.stringify(Z,null,2)),this.preferencesCache=Z,M0.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(Z.preferences).length})}catch(J){throw M0.error("[NotificationStorage] Error saving preferences:",J),J}}getDefaultPreferences(Z){return{deviceId:Z,allMessages:!0,needsAttention:!0,updatedAt:new Date().toISOString()}}async getPreferences(Z){let J=await this.loadPreferences();if(!J.preferences[Z])J.preferences[Z]=this.getDefaultPreferences(Z),await this.savePreferences(J),M0.debug("[NotificationStorage] Created default preferences for device:",{deviceId:Z});return J.preferences[Z]}async updatePreferences(Z,J){let $=await this.loadPreferences(),X=await this.getPreferences(Z);return $.preferences[Z]={...X,...J,deviceId:Z,updatedAt:new Date().toISOString()},await this.savePreferences($),M0.debug("[NotificationStorage] Updated preferences:",{deviceId:Z,updates:J}),$.preferences[Z]}async isNotificationEnabled(Z,J){return(await this.getPreferences(Z))[J]}clearCache(){this.tokensCache=null,this.preferencesCache=null,M0.debug("[NotificationStorage] Cleared cache")}}var v8=new Uz1;import{Expo as RY0}from"expo-server-sdk";function CY0(Z){return typeof Z==="string"&&((Z.startsWith("ExponentPushToken[")||Z.startsWith("ExpoPushToken["))&&Z.endsWith("]")||/^[a-z\d]{8}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{12}$/i.test(Z))}var S6=S();class Lz1{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;getExpo(){if(!this.expo)this.expo=new RY0;return this.expo}isValidToken(Z){return CY0(Z)}async sendNotification(Z,J){if(!this.isValidToken(Z))return S6.warn("[ExpoPushClient] Invalid Expo push token:",{token:Z.substring(0,20)+"..."}),null;let $={to:Z,title:J.title,body:J.body,data:J.data,sound:J.sound||"default",channelId:J.channelId||"default",priority:J.priority||"high",badge:J.badge};try{let Q=(await this.getExpo().sendPushNotificationsAsync([$]))[0];if(this.notificationsSent++,this.lastNotificationAt=new Date,Q.id){let W=Q;this.pendingTickets.set(W.id,{ticketId:W.id,token:Z,createdAt:new Date})}if(Q&&Q.status==="error"){let W=Q;await this.handleTicketError(W,Z)}return S6.debug("[ExpoPushClient] Sent notification:",{token:Z.substring(0,20)+"...",status:Q?.status}),Q??null}catch(X){return S6.error("[ExpoPushClient] Error sending notification:",X),null}}async sendBatchNotifications(Z,J){let $=[];for(let K of Z)if(!this.isValidToken(K))S6.warn("[ExpoPushClient] Skipping invalid token:",{token:K.substring(0,20)+"..."});else $.push(K);if($.length===0)return S6.warn("[ExpoPushClient] No valid tokens to send to"),[];let X=$.map((K)=>({to:K,title:J.title,body:J.body,data:J.data,sound:J.sound||"default",channelId:J.channelId||"default",priority:J.priority||"high",badge:J.badge})),Y=this.getExpo(),Q=Y.chunkPushNotifications(X),W=[];for(let K of Q)try{let z=await Y.sendPushNotificationsAsync(K);W.push(...z);for(let G=0;G<z.length;G++){let H=z[G],V=W.length-z.length+G,F=$[V];if(!H||!F)continue;if(H.id){let B=H;this.pendingTickets.set(B.id,{ticketId:B.id,token:F,createdAt:new Date})}if(H.status==="error")await this.handleTicketError(H,F)}this.notificationsSent+=z.length,this.lastNotificationAt=new Date}catch(z){S6.error("[ExpoPushClient] Error sending batch chunk:",z)}return S6.debug("[ExpoPushClient] Sent batch notifications:",{total:$.length,successful:W.filter((K)=>K.status==="ok").length,failed:W.filter((K)=>K.status==="error").length}),W}async handleTicketError(Z,J){if(S6.warn("[ExpoPushClient] Ticket error:",{message:Z.message,details:Z.details}),Z.details?.error==="DeviceNotRegistered"){S6.debug("[ExpoPushClient] Removing invalid token:",{token:J.substring(0,20)+"..."});let X=(await v8.getAllTokens()).find((Y)=>Y.expoPushToken===J);if(X)await v8.unregisterToken(X.deviceId)}}async checkReceipts(){let Z=new Date;Z.setMinutes(Z.getMinutes()-15);let J=[];for(let[Q,W]of this.pendingTickets.entries())if(W.createdAt<Z)J.push(Q);if(J.length===0)return;S6.debug("[ExpoPushClient] Checking receipts:",{count:J.length});let $=this.getExpo(),X=$.chunkPushNotificationReceiptIds(J);for(let Q of X)try{let W=await $.getPushNotificationReceiptsAsync(Q);for(let[K,z]of Object.entries(W)){let G=this.pendingTickets.get(K),H=z;if(H.status==="ok")S6.debug("[ExpoPushClient] Receipt OK:",{ticketId:K});else if(H.status==="error"){let V=z;if(S6.warn("[ExpoPushClient] Receipt error:",{ticketId:K,message:V.message,details:V.details}),V.details?.error==="DeviceNotRegistered"&&G){let B=(await v8.getAllTokens()).find((U)=>U.expoPushToken===G.token);if(B)S6.debug("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:B.deviceId}),await v8.unregisterToken(B.deviceId)}}this.pendingTickets.delete(K)}}catch(W){S6.error("[ExpoPushClient] Error checking receipts:",W)}let Y=new Date;Y.setHours(Y.getHours()-24);for(let[Q,W]of this.pendingTickets.entries())if(W.createdAt<Y)this.pendingTickets.delete(Q)}getStats(){return{notificationsSent:this.notificationsSent,lastNotificationAt:this.lastNotificationAt,pendingReceipts:this.pendingTickets.size}}}var $K=new Lz1;var l0=S(),Dz1=200,qY0=900000;class TF extends Q0{name="Notification Service";get logPrefix(){return"[Notification]"}claudeAgentService=null;openCodeAgentService=null;codexAgentService=null;piAgentService=null;receiptCheckInterval;setClaudeAgentService(Z){this.claudeAgentService=Z}setOpenCodeAgentService(Z){this.openCodeAgentService=Z}setCodexAgentService(Z){this.codexAgentService=Z}setPiAgentService(Z){this.piAgentService=Z}async onStart(){this.receiptCheckInterval=setInterval(()=>{$K.checkReceipts().catch((Z)=>{l0.error("[Notification] Error checking receipts:",Z)})},qY0),l0.info("[Notification] Ready to send notifications")}async onStop(){if(this.receiptCheckInterval)clearInterval(this.receiptCheckInterval),this.receiptCheckInterval=void 0}registerMQTTHandlers(){this.registerHandler("notifications/register/request",this.handleRegisterToken.bind(this)),this.registerHandler("notifications/preferences/get/request",this.handleGetPreferences.bind(this)),this.registerHandler("notifications/preferences/update/request",this.handleUpdatePreferences.bind(this)),this.registerHandler("claude/+/output/+",this.handleClaudeOutput.bind(this)),this.registerHandler("claude/+/permission/request/+",this.handlePermissionRequest.bind(this)),this.registerHandler("opencode/+/output/+",this.handleClaudeOutput.bind(this)),this.registerHandler("opencode/+/permission/request/+",this.handlePermissionRequest.bind(this)),this.registerHandler("codex/+/output/+",this.handleClaudeOutput.bind(this)),this.registerHandler("codex/+/permission/request/+",this.handlePermissionRequest.bind(this)),this.registerHandler("pi/+/output/+",this.handleClaudeOutput.bind(this)),this.registerHandler("pi/+/permission/request/+",this.handlePermissionRequest.bind(this)),l0.debug("[Notification] MQTT handlers registered")}async handleRegisterToken(Z,J){try{let $=await this.parseMessage(J);if(!$)return;let{data:X,profileId:Y}=$;l0.debug("[Notification] Register token request:",{deviceId:X.deviceId,platform:X.platform,hasExpoPushToken:!!X.expoPushToken,hasFcmToken:!!X.fcmToken}),await v8.registerToken(X.deviceId,X.fcmToken,X.expoPushToken,X.platform,X.deviceInfo);let Q=this.buildResponseTopic("notifications/register",X.clientId||Y,X.requestId),W={requestId:X.requestId,success:!0};await this.publishResponse(Q,W,Y),l0.debug("[Notification] Token registered successfully:",{deviceId:X.deviceId})}catch($){l0.error("[Notification] Error registering token:",$);try{let X=await this.parseMessage(J);if(X?.data?.requestId){let Y=this.buildResponseTopic("notifications/register",X.data.clientId||X.profileId,X.data.requestId),Q={requestId:X.data.requestId,success:!1,error:$ instanceof Error?$.message:"Unknown error"};await this.publishResponse(Y,Q,X.profileId)}}catch{}}}async handleGetPreferences(Z,J){try{let $=await this.parseMessage(J);if(!$)return;let{data:X,profileId:Y}=$;l0.debug("[Notification] Get preferences request:",{deviceId:X.deviceId});let Q=await v8.getPreferences(X.deviceId),W=this.buildResponseTopic("notifications/preferences/get",X.clientId||Y,X.requestId),K={requestId:X.requestId,success:!0,preferences:Q};await this.publishResponse(W,K,Y),l0.debug("[Notification] Sent preferences:",{deviceId:X.deviceId})}catch($){l0.error("[Notification] Error getting preferences:",$);try{let X=await this.parseMessage(J);if(X?.data?.requestId){let Y=this.buildResponseTopic("notifications/preferences/get",X.data.clientId||X.profileId,X.data.requestId),Q={requestId:X.data.requestId,success:!1,error:$ instanceof Error?$.message:"Unknown error"};await this.publishResponse(Y,Q,X.profileId)}}catch{}}}async handleUpdatePreferences(Z,J){try{let $=await this.parseMessage(J);if(!$)return;let{data:X,profileId:Y}=$;l0.debug("[Notification] Update preferences request:",{deviceId:X.deviceId,preferences:X.preferences});let Q=await v8.updatePreferences(X.deviceId,X.preferences),W=this.buildResponseTopic("notifications/preferences/update",X.clientId||Y,X.requestId),K={requestId:X.requestId,success:!0,preferences:Q};await this.publishResponse(W,K,Y),l0.debug("[Notification] Preferences updated:",{deviceId:X.deviceId})}catch($){l0.error("[Notification] Error updating preferences:",$);try{let X=await this.parseMessage(J);if(X?.data?.requestId){let Y=this.buildResponseTopic("notifications/preferences/update",X.data.clientId||X.profileId,X.data.requestId),Q={requestId:X.data.requestId,success:!1,error:$ instanceof Error?$.message:"Unknown error"};await this.publishResponse(Y,Q,X.profileId)}}catch{}}}async handleClaudeOutput(Z,J){try{let $=Z.split("/")[3],X=await this.parseMessage(J);if(!X)return;let Y=X.data;if(Y.type!=="assistant")return;let Q=this.getSessionInfo($??"");if(!Q){l0.debug("[Notification] Session not found for notification:",{sessionId:$});return}let W=this.buildNotificationTitle(Q),K=this.extractMessageBody(Y);if(!K)return;let z={type:"message",projectId:Q.projectPath,sessionId:$??""};await this.sendToDevicesWithPreference("allMessages",{title:W,body:K,data:z,priority:"high",channelId:"messages"}),l0.debug("[Notification] Sent message notification:",{sessionId:$,title:W})}catch($){l0.error("[Notification] Error handling Claude output:",$)}}async handlePermissionRequest(Z,J){try{let $=Z.split("/")[4],X=await this.parseMessage(J);if(!X)return;let Y=X.data,Q=this.getSessionInfo($??"");if(!Q){l0.debug("[Notification] Session not found for permission notification:",{sessionId:$});return}let W=this.buildNotificationTitle(Q),K=this.buildPermissionBody(Y),z={type:"permission",projectId:Q.projectPath,sessionId:$??"",requestId:Y.request_id,action:Y.action};await this.sendToDevicesWithPreference("needsAttention",{title:W,body:K,data:z,priority:"high",channelId:"default"}),l0.debug("[Notification] Sent permission notification:",{sessionId:$,action:Y.action})}catch($){l0.error("[Notification] Error handling permission request:",$)}}getSessionInfo(Z){if(this.claudeAgentService){let $=this.claudeAgentService.getActiveSessions().find((X)=>X.sessionId===Z);if($)return{sessionId:$.sessionId,projectPath:$.projectPath,worktreeBranch:$.worktreeBranch}}if(this.openCodeAgentService){let $=this.openCodeAgentService.getActiveSessions().find((X)=>X.sessionId===Z);if($)return{sessionId:$.sessionId,projectPath:$.projectPath,worktreeBranch:$.worktreeBranch}}if(this.codexAgentService){let $=this.codexAgentService.getActiveSessions().find((X)=>X.threadId===Z||X.tempId===Z);if($)return{sessionId:$.threadId||$.tempId,projectPath:$.directoryPath,worktreeBranch:$.worktreeBranch}}if(this.piAgentService){let $=this.piAgentService.getActiveSessions().find((X)=>X.sessionId===Z||X.tempId===Z);if($)return{sessionId:$.sessionId||$.tempId,projectPath:$.directoryPath,worktreeBranch:$.worktreeBranch}}return null}buildNotificationTitle(Z){let J=Oz1.basename(Z.projectPath);if(Z.worktreeBranch){let $=Z.worktreeBranch.replace("session/","");return`${J} (${$})`}return J}extractMessageBody(Z){let J="",$=Z.message;if($?.content&&Array.isArray($.content))J=$.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).filter(Boolean).join(`
2411
2411
  `);else if(Z.content){if(typeof Z.content==="string")J=Z.content;else if(Array.isArray(Z.content))J=Z.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).filter(Boolean).join(`
2412
2412
  `)}if(!J.trim())return null;if(J.length>Dz1)J=J.substring(0,Dz1)+"...";return J}buildPermissionBody(Z){let J=Z.action||"Unknown tool",$=Z.params||{},X="";switch(J.toLowerCase()){case"bash":case"execute_command":X=$.command||"";break;case"read":case"read_file":X=$.file_path||"";break;case"write":case"write_file":X=$.file_path||"";break;case"edit":X=$.file_path||"";break;case"webfetch":X=$.url||"";break;case"websearch":X=$.query||"";break;default:X=$.file_path||$.command||$.path||""}if(X.length>100)X=X.substring(0,100)+"...";if(X)return`Permission requested: ${J}: ${X}`;return`Permission requested: ${J}`}async sendToDevicesWithPreference(Z,J){try{let $=await v8.getAllTokens();if($.length===0){l0.debug("[Notification] No registered devices");return}let X=[];for(let Y of $){if(!Y.expoPushToken)continue;if((await v8.getPreferences(Y.deviceId))[Z])X.push(Y.expoPushToken)}if(X.length===0){l0.debug("[Notification] No devices with preference enabled:",{preferenceType:Z});return}await $K.sendBatchNotifications(X,J),l0.debug("[Notification] Sent to devices:",{count:X.length,preferenceType:Z})}catch($){l0.error("[Notification] Error sending to devices:",$)}}getStatus(){let Z=$K.getStats();return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,registeredDevices:0,notificationsSent:Z.notificationsSent,lastNotificationAt:Z.lastNotificationAt}}}import*as PZ from"fs/promises";import*as p0 from"path";import*as MF from"os";var{YAML:SY0}=globalThis.Bun;import*as wY from"fs/promises";import*as AY from"path";import*as _z1 from"os";var EY0=S();function PY0(){return AY.join(_z1.homedir(),".config","opencode")}function K9(){return AY.join(PY0(),"opencode.json")}function TY(Z){return AY.join(Z,"opencode.json")}function IY0(Z){let J=Z.replace(/\/\*[\s\S]*?\*\//g,"");return J=J.replace(/(^|[^:])\/\/.*$/gm,"$1"),J}async function K4(Z){try{let J=await wY.readFile(Z,"utf-8"),$=IY0(J);return JSON.parse($)}catch(J){if(J.code==="ENOENT")return{};return EY0.warn("[OpenCodeConfig] Failed to read config",{configPath:Z,error:J instanceof Error?J.message:"Unknown error"}),{}}}async function h8(Z,J){let $=AY.dirname(Z);await wY.mkdir($,{recursive:!0});let Y={...await K4(Z),...J};await wY.writeFile(Z,JSON.stringify(Y,null,2),"utf-8")}var EZ=S();class jF extends Q0{name="Slash Commands Service";get logPrefix(){return"[SlashCommands]"}getStatus(){return{...super.getStatus()}}registerMQTTHandlers(){this.registerHandler("commands/list/request",(Z,J)=>{this.handleListCommandsRequest(J)}),this.registerHandler("commands/read/request",(Z,J)=>{this.handleReadCommandRequest(J)}),this.registerHandler("commands/write/request",(Z,J)=>{this.handleWriteCommandRequest(J)}),this.registerHandler("commands/delete/request",(Z,J)=>{this.handleDeleteCommandRequest(J)}),EZ.debug("[SlashCommands] MQTT handlers registered")}getCommandsDir(Z,J,$){if($==="opencode"){if(Z==="global")return p0.join(MF.homedir(),".config","opencode","commands");if(!J)throw Error("Project path is required for project-scoped commands");return p0.join(J,".opencode","commands")}if($==="codex")throw Error("Codex does not support custom commands (deprecated in favor of skills)");if($==="pi"){if(Z==="global")return p0.join(MF.homedir(),".pi","agent","prompts");if(!J)throw Error("Project path is required for project-scoped commands");return p0.join(J,".pi","prompts")}if(Z==="global")return p0.join(MF.homedir(),".claude","commands");if(!J)throw Error("Project path is required for project-scoped commands");return p0.join(J,".claude","commands")}getOpenCodeConfigPath(Z,J){if(Z==="global")return K9();if(!J)throw Error("Project path is required for project-scoped commands");return TY(J)}async listOpenCodeConfigCommands(Z,J){let $=this.getOpenCodeConfigPath(Z,J),Y=(await K4($)).command||{};return Object.entries(Y).map(([Q,W])=>({name:Q,filename:`${Q}.config`,description:typeof W?.description==="string"?W.description:void 0,argumentHint:typeof W?.arguments==="string"?W.arguments:void 0,scope:Z,provider:"opencode",source:"config",modified:void 0}))}async readOpenCodeConfigCommand(Z,J,$){let X=this.getOpenCodeConfigPath(Z,$),W=((await K4(X)).command||{})[J];if(!W)return null;let K={};if(W.description)K.description=String(W.description);if(W.model)K.model=String(W.model);if(W.agent)K.agent=String(W.agent);if(W.arguments)K["argument-hint"]=String(W.arguments);let z=String(W.prompt||""),G=z;return{name:J,filename:`${J}.config`,description:K.description,argumentHint:K["argument-hint"],scope:Z,content:z,frontmatter:Object.keys(K).length>0?K:void 0,rawContent:G,provider:"opencode",source:"config",modified:void 0}}async writeOpenCodeConfigCommand(Z,J,$,X,Y){let Q=this.getOpenCodeConfigPath(Z,Y),W=await K4(Q),K=W.command||{};K[J]={...X?.description?{description:X.description}:{},...X?.model?{model:X.model}:{},...X?.agent?{agent:X.agent}:{},...X?.["argument-hint"]?{arguments:X["argument-hint"]}:{},prompt:$},await h8(Q,{...W,command:K})}async deleteOpenCodeConfigCommand(Z,J,$){let X=this.getOpenCodeConfigPath(Z,$),Y=await K4(X),Q=Y.command||{};if(!Q[J])return!1;return delete Q[J],await h8(X,{...Y,command:Q}),!0}parseHooksManually(Z){let J={},$=(W,K)=>{let z=new RegExp(`${K}:\\s*\\n`,"m"),G=W.match(z);if(!G||G.index===void 0)return null;let H=G.index+G[0].length,V=W.slice(H),B=V.match(/^ [A-Z]/m)?.index??V.length;return V.slice(0,B)},X=$(Z,"PreToolUse");if(X){let W=this.parseHookItems(X);if(W.length>0)J.PreToolUse=W}let Y=$(Z,"PostToolUse");if(Y){let W=this.parseHookItems(Y);if(W.length>0)J.PostToolUse=W}let Q=$(Z,"Stop");if(Q){let W=[],K=Q.matchAll(/- command:\s*(.+)/g);for(let z of K){let G=(z[1]||"").trim();if(G.startsWith('"')&&G.endsWith('"')||G.startsWith("'")&&G.endsWith("'"))G=G.slice(1,-1);W.push({command:G})}if(W.length>0)J.Stop=W}return Object.keys(J).length>0?J:void 0}parseHookItems(Z){let J=[],$=Z.split(/(?=- matcher:)/);for(let X of $){if(!X.trim())continue;let Y=X.match(/- matcher:\s*(.+)/);if(!Y||!Y[1])continue;let Q=Y[1].trim(),W=[],K=X.matchAll(/- command:\s*(.+)/g);for(let z of K){let G=(z[1]||"").trim();if(G.startsWith('"')&&G.endsWith('"')||G.startsWith("'")&&G.endsWith("'"))G=G.slice(1,-1);W.push({command:G})}if(W.length>0)J.push({matcher:Q,hooks:W})}return J}parseFrontmatter(Z){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/,$=Z.match(J);if(!$)return{body:Z};let X=$[1]||"",Y=$[2]||"";try{let Q;try{Q=SY0.parse(X)}catch(K){EZ.debug("[SlashCommands] YAML parse failed, attempting manual extraction",{yamlError:K});let z={},G=X.match(/^description:\s*["'](.+?)["']\s*$/m);if(G)z.description=G[1];let H=X.match(/^argument-hint:\s*(.+?)\s*$/m);if(H&&H[1]){let L=H[1].trim();if(L.startsWith('"')&&L.endsWith('"')||L.startsWith("'")&&L.endsWith("'"))L=L.slice(1,-1);z["argument-hint"]=L}let V=X.match(/^allowed-tools:\s*(.+?)\s*$/m);if(V&&V[1])z["allowed-tools"]=V[1].trim();let F=X.match(/^context:\s*(fork|inline)\s*$/m);if(F)z.context=F[1];let B=X.match(/^agent:\s*(.+?)\s*$/m);if(B&&B[1])z.agent=B[1].trim();let U=X.match(/^model:\s*(.+?)\s*$/m);if(U&&U[1])z.model=U[1].trim();if(X.includes("hooks:")){let L=X.match(/^hooks:\s*\n([\s\S]*?)(?=^[a-z]|$(?![\s\S]))/m);if(L&&L[1])z.hooks=this.parseHooksManually(L[1]);else{let O=X.indexOf(`hooks:
@@ -2689,4 +2689,4 @@ ${O.description}
2689
2689
 
2690
2690
  This is a built-in style. Built-in styles cannot be edited.`,rawContent:"",keepCodingInstructions:!1,lastModified:new Date().toISOString()},timestamp:Date.now()};await this.publishResponse(Y,A,X),this.requestsHandled++;return}let Q=this.getOutputStylesDir($.scope,$.projectPath),W=R4.join(Q,`${$.styleName}.md`),K=R4.resolve(W).toLowerCase().replace(/\\/g,"/"),z=R4.resolve(Q).toLowerCase().replace(/\\/g,"/");if(!K.startsWith(z))throw f8.warn("[OutputStyles] Path security check failed",{resolvedPath:K,resolvedBase:z,styleName:$.styleName,scope:$.scope}),Error("Invalid style path");let G=await A0(W);if(G===null)throw Error("Style file not found or unreadable");let H=await b8.stat(W),{frontmatter:V,body:F}=this.parseFrontmatter(G),B=await this.readActiveStyle($.scope,$.projectPath),L={style:{name:$.styleName,displayName:V?.name||$.styleName,description:V?.description||"",scope:$.scope,projectPath:$.projectPath,isActive:B===$.styleName,content:F,rawContent:G,keepCodingInstructions:V?.keepCodingInstructions??!1,lastModified:H.mtime.toISOString()},timestamp:Date.now()};await this.publishResponse(Y,L,X)}catch(Q){let W={timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){f8.error("[OutputStyles] Error handling read style request",{error:this.formatError(J)})}}async handleWriteStyleRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("output-styles/write",$.clientId,$.requestId);try{let Q=this.getOutputStylesDir($.scope,$.projectPath);if(!/^[a-z][a-z0-9_-]*$/i.test($.styleName))throw Error("Invalid style name. Use only letters, numbers, hyphens, and underscores.");let W=R4.join(Q,`${$.styleName}.md`),K=R4.resolve(W),z=R4.resolve(Q);if(!K.startsWith(z))throw Error("Invalid style path");await b8.mkdir(Q,{recursive:!0});let H=this.generateFrontmatter({name:$.displayName,description:$.description,keepCodingInstructions:$.keepCodingInstructions})+`
2691
2691
 
2692
- `+$.content;await b8.writeFile(W,H,"utf-8");let V={success:!0,styleName:$.styleName,scope:$.scope,timestamp:Date.now()};await this.publishResponse(Y,V,X)}catch(Q){let W={success:!1,styleName:$.styleName,scope:$.scope,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){f8.error("[OutputStyles] Error handling write style request",{error:this.formatError(J)})}}async handleDeleteStyleRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("output-styles/delete",$.clientId,$.requestId);try{let Q=this.getOutputStylesDir($.scope,$.projectPath),W=R4.join(Q,`${$.styleName}.md`),K=R4.resolve(W),z=R4.resolve(Q);if(!K.startsWith(z))throw Error("Invalid style path");if(await b8.unlink(W),await this.readActiveStyle($.scope,$.projectPath)===$.styleName)await this.setActiveStyle($.scope,"default",$.projectPath);let H={success:!0,styleName:$.styleName,scope:$.scope,timestamp:Date.now()};await this.publishResponse(Y,H,X)}catch(Q){let W={success:!1,styleName:$.styleName,scope:$.scope,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){f8.error("[OutputStyles] Error handling delete style request",{error:this.formatError(J)})}}async handleSetActiveStyleRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("output-styles/set-active",$.clientId,$.requestId);try{await this.setActiveStyle($.scope,$.styleName,$.projectPath);let Q={success:!0,styleName:$.styleName,scope:$.scope,timestamp:Date.now()};await this.publishResponse(Y,Q,X)}catch(Q){let W={success:!1,styleName:$.styleName,scope:$.scope,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){f8.error("[OutputStyles] Error handling set active style request",{error:this.formatError(J)})}}}import*as C4 from"fs/promises";import*as e0 from"path";var{$:F7}=globalThis.Bun;RZ();var i0=S(),KK={name:"claude-plugins-official",source:{source:"github",repo:"anthropics/claude-plugins-official"}};class gF extends Q0{name="Plugins Service";openCodeService;codexService;piService;constructor(Z,J,$){super();this.openCodeService=Z,this.codexService=J,this.piService=$}get logPrefix(){return"[Plugins]"}getStatus(){return{...super.getStatus()}}async onStart(){await this.ensureDirectories()}registerMQTTHandlers(){this.registerHandler("plugins/marketplaces/list/request",(Z,J)=>{this.handleListMarketplacesRequest(J)}),this.registerHandler("plugins/list/request",(Z,J)=>{this.handleListPluginsRequest(J)}),this.registerHandler("plugins/read/request",(Z,J)=>{this.handleReadPluginRequest(J)}),this.registerHandler("plugins/install/request",(Z,J)=>{this.handleInstallPluginRequest(J)}),this.registerHandler("plugins/uninstall/request",(Z,J)=>{this.handleUninstallPluginRequest(J)}),this.registerHandler("plugins/toggle/request",(Z,J)=>{this.handleTogglePluginRequest(J)}),this.registerHandler("plugins/marketplace/add/request",(Z,J)=>{this.handleAddMarketplaceRequest(J)}),this.registerHandler("plugins/marketplace/remove/request",(Z,J)=>{this.handleRemoveMarketplaceRequest(J)}),this.registerHandler("plugins/marketplace/refresh/request",(Z,J)=>{this.handleRefreshMarketplaceRequest(J)}),i0.debug("[Plugins] MQTT handlers registered")}getPluginsDir(){return e9.getPluginsDir("user")}getMarketplaceCacheDir(){return e9.getMarketplaceCacheDir()}getSettingsPath(){return e9.getUserConfigPath("settings")}getInstalledPluginsJsonPath(){return e0.join(this.getPluginsDir(),"installed_plugins.json")}getOpenCodeConfigPath(){return K9()}getPluginCacheDir(){return e0.join(this.getPluginsDir(),"cache")}async ensureDirectories(){let Z=[this.getPluginsDir(),this.getPluginCacheDir(),this.getMarketplaceCacheDir()];for(let J of Z)await C4.mkdir(J,{recursive:!0})}normalizeOpenCodePlugins(Z){return(Array.isArray(Z.plugin)?Z.plugin:Array.isArray(Z.plugins)?Z.plugins:[]).filter(Boolean)}async listOpenCodePlugins(){let Z=this.getOpenCodeConfigPath(),J=await K4(Z);return this.normalizeOpenCodePlugins(J).map((X)=>{if(typeof X==="string")return{name:X,displayName:X,description:"",marketplaceName:"opencode",isInstalled:!0,isEnabled:!0,source:X,provider:"opencode"};let Y=X.name;return{name:Y,displayName:Y,description:X.description||"",version:X.version,author:X.author,category:X.category,tags:X.tags,marketplaceName:"opencode",isInstalled:!0,isEnabled:X.enabled!==!1,source:X.source||Y,provider:"opencode"}}).filter((X)=>!!X.name)}async readOpenCodePlugin(Z){let J=this.getOpenCodeConfigPath(),$=await K4(J),Y=this.normalizeOpenCodePlugins($).find((Q)=>typeof Q==="string"?Q===Z:Q.name===Z);if(!Y)return null;if(typeof Y==="string")return{name:Y,displayName:Y,description:"",marketplaceName:"opencode",isInstalled:!0,isEnabled:!0,source:Y,provider:"opencode",hasCommands:!1,hasSkills:!1,hasAgents:!1,hasHooks:!1,hasMcpServers:!1,hasLspServers:!1};return{name:Y.name,displayName:Y.name,description:Y.description||"",version:Y.version,author:Y.author,category:Y.category,tags:Y.tags,marketplaceName:"opencode",isInstalled:!0,isEnabled:Y.enabled!==!1,source:Y.source||Y.name,provider:"opencode",hasCommands:!1,hasSkills:!1,hasAgents:!1,hasHooks:!1,hasMcpServers:!1,hasLspServers:!1}}async setOpenCodePluginEnabled(Z,J){let $=this.getOpenCodeConfigPath(),X=await K4($),Y=this.normalizeOpenCodePlugins(X),Q=Y.findIndex((W)=>typeof W==="string"?W===Z:W.name===Z);if(J){if(Q===-1)Y.push(Z);else if(typeof Y[Q]!=="string")Y[Q]={...Y[Q],enabled:!0,name:Z}}else if(Q!==-1){let W=Y[Q];if(typeof W==="string")Y.splice(Q,1);else Y[Q]={...W,enabled:!1,name:Z}}await h8($,{...X,plugin:Y})}async readSettings(){return await H7.readConfigOrEmpty(this.getSettingsPath())}async writeSettings(Z){await H7.writeConfig(this.getSettingsPath(),Z)}async getEnabledPlugins(){return(await this.readSettings()).enabledPlugins||{}}async setPluginEnabled(Z,J){let $=await this.readSettings();if(!$.enabledPlugins)$.enabledPlugins={};$.enabledPlugins[Z]=J,await this.writeSettings($)}async getKnownMarketplaces(){let J=(await this.readSettings()).extraKnownMarketplaces||{},$={};for(let[X,Y]of Object.entries(J))if(typeof Y==="object"&&Y!==null&&"source"in Y)$[X]=Y.source;else $[X]=Y;return $}async addKnownMarketplace(Z,J){let $=await this.readSettings();if(!$.extraKnownMarketplaces)$.extraKnownMarketplaces={};$.extraKnownMarketplaces[Z]={source:J},await this.writeSettings($)}async removeKnownMarketplace(Z){let J=await this.readSettings();if(J.extraKnownMarketplaces)delete J.extraKnownMarketplaces[Z],await this.writeSettings(J)}async readInstalledPluginsJson(){let Z=this.getInstalledPluginsJsonPath(),J=await A0(Z);if(!J)return{version:2,plugins:{}};try{let $=JSON.parse(J);return{version:$.version||2,plugins:$.plugins||{}}}catch($){return i0.warn("[Plugins] Failed to parse installed_plugins.json, returning empty",$),{version:2,plugins:{}}}}async writeInstalledPluginsJson(Z){let J=this.getInstalledPluginsJsonPath();await C4.writeFile(J,JSON.stringify(Z,null,2),"utf-8")}async addInstalledPluginRecord(Z,J){let $=await this.readInstalledPluginsJson();if(!$.plugins[Z])$.plugins[Z]=[];let X=$.plugins[Z].findIndex((Y)=>Y.scope===J.scope);if(X>=0)$.plugins[Z][X]=J;else $.plugins[Z].push(J);await this.writeInstalledPluginsJson($)}async removeInstalledPluginRecord(Z,J){let $=await this.readInstalledPluginsJson();if(!$.plugins[Z])return;if(J){if($.plugins[Z]=$.plugins[Z].filter((X)=>X.scope!==J),$.plugins[Z].length===0)delete $.plugins[Z]}else delete $.plugins[Z];await this.writeInstalledPluginsJson($)}async getInstalledPluginRecord(Z){let $=(await this.readInstalledPluginsJson()).plugins[Z];if(!$||$.length===0)return null;return $[0]??null}getMarketplaceCachePath(Z){return e0.join(this.getMarketplaceCacheDir(),Z)}async fetchMarketplace(Z,J){let $=this.getMarketplaceCachePath(Z);try{if(typeof J==="object"&&J.source==="github"){let Q=`https://github.com/${J.repo}.git`,W=J.ref||"main";if(await H6($))await F7`git -C ${$} fetch origin ${W}`.quiet(),await F7`git -C ${$} reset --hard origin/${W}`.quiet();else await F7`git clone --depth 1 --branch ${W} ${Q} ${$}`.quiet()}else if(typeof J==="object"&&J.source==="url"){let Q=J.url,W=J.ref||"main";if(await H6($))await F7`git -C ${$} fetch origin ${W}`.quiet(),await F7`git -C ${$} reset --hard origin/${W}`.quiet();else await F7`git clone --depth 1 --branch ${W} ${Q} ${$}`.quiet()}else if(typeof J==="string")return i0.warn("[Plugins] Relative path source not supported for marketplaces"),null;let X=e0.join($,".claude-plugin","marketplace.json"),Y=await A0(X);if(!Y){let Q=e0.join($,"marketplace.json"),W=await A0(Q);if(W)return JSON.parse(W);return i0.warn(`[Plugins] No marketplace.json found for ${Z}`),null}return JSON.parse(Y)}catch(X){return i0.error(`[Plugins] Failed to fetch marketplace ${Z}`,X),null}}async parseMarketplace(Z){let J=this.getMarketplaceCachePath(Z),$=e0.join(J,".claude-plugin","marketplace.json"),X=await A0($);if(!X)$=e0.join(J,"marketplace.json"),X=await A0($);if(!X)return null;try{return JSON.parse(X)}catch(Y){return i0.error(`[Plugins] Failed to parse marketplace.json for ${Z}`,Y),null}}async marketplacePluginToEntry(Z,J,$,X){let Y=`${Z.name}@${J}`;return{name:Z.name,displayName:Z.name,description:Z.description||"",version:Z.version,author:Z.author?.name,category:Z.category,tags:Z.tags,marketplaceName:J,isInstalled:X.has(Y),isEnabled:$[Y]??!1,source:Z.source,provider:"claude"}}async getAllMarketplaces(){let Z=await this.getKnownMarketplaces(),J=[{name:KK.name,source:KK.source,isOfficial:!0}];for(let[$,X]of Object.entries(Z))J.push({name:$,source:X,isOfficial:!1});return J}async getInstalledPlugins(){let Z=new Set,J=await this.readInstalledPluginsJson();for(let[$,X]of Object.entries(J.plugins)){if(!X||X.length===0)continue;for(let Y of X)if(Y.installPath){if(await H6(Y.installPath)){Z.add($);break}}}return Z}getPluginInstallPath(Z,J,$="1.0.0"){return e0.join(this.getPluginCacheDir(),J,Z,$)}async getPluginInstallPathFromRecord(Z,J){let $=`${Z}@${J}`;return(await this.getInstalledPluginRecord($))?.installPath||null}async getGitCommitSha(Z){try{return(await F7`git -C ${Z} rev-parse HEAD`.quiet()).stdout.toString().trim()||void 0}catch{return}}async installPluginFromMarketplace(Z,J,$="user"){try{let X=await this.parseMarketplace(J);if(!X)return{success:!1,error:"Marketplace not found or not cached"};let Y=X.plugins.find((F)=>F.name===Z);if(!Y)return{success:!1,error:"Plugin not found in marketplace"};let Q=Y.version||"1.0.0",W=this.getPluginInstallPath(Z,J,Q),K=this.getMarketplaceCachePath(J),z=`${Z}@${J}`;await C4.mkdir(e0.dirname(W),{recursive:!0});let G;if(typeof Y.source==="string"){let F=e0.join(K,Y.source);await C4.rm(W,{recursive:!0,force:!0}),await C4.cp(F,W,{recursive:!0}),G=await this.getGitCommitSha(K)}else if(Y.source.source==="github"){let F=`https://github.com/${Y.source.repo}.git`,B=Y.source.ref||"main";await C4.rm(W,{recursive:!0,force:!0}),await F7`git clone --depth 1 --branch ${B} ${F} ${W}`.quiet(),G=await this.getGitCommitSha(W)}else if(Y.source.source==="url"){let F=Y.source.url,B=Y.source.ref||"main";await C4.rm(W,{recursive:!0,force:!0}),await F7`git clone --depth 1 --branch ${B} ${F} ${W}`.quiet(),G=await this.getGitCommitSha(W)}else return{success:!1,error:"Unknown plugin source type"};let H=new Date().toISOString(),V={scope:$,installPath:W,version:Q,installedAt:H,lastUpdated:H,gitCommitSha:G};return await this.addInstalledPluginRecord(z,V),await this.setPluginEnabled(z,!0),i0.debug(`[Plugins] Installed ${z} to ${W}`),{success:!0}}catch(X){return i0.error(`[Plugins] Failed to install plugin ${Z}@${J}`,X),{success:!1,error:X instanceof Error?X.message:"Unknown error"}}}async uninstallPlugin(Z,J,$){try{let X=`${Z}@${J}`,Y=await this.getInstalledPluginRecord(X);if(!Y)return{success:!1,error:"Plugin not installed"};if(Y.installPath&&await H6(Y.installPath))await C4.rm(Y.installPath,{recursive:!0,force:!0});await this.removeInstalledPluginRecord(X,$);let Q=await this.readSettings();if(Q.enabledPlugins&&Q.enabledPlugins[X]!==void 0)delete Q.enabledPlugins[X],await this.writeSettings(Q);return i0.debug(`[Plugins] Uninstalled ${X}`),{success:!0}}catch(X){return i0.error(`[Plugins] Failed to uninstall plugin ${Z}@${J}`,X),{success:!1,error:X instanceof Error?X.message:"Unknown error"}}}async readPluginManifest(Z){let J=e0.join(Z,".claude-plugin","plugin.json"),$=await A0(J);if(!$)return null;try{return JSON.parse($)}catch(X){return null}}async getPluginDetail(Z,J){let $=await this.getEnabledPlugins(),X=await this.getInstalledPlugins(),Y=`${Z}@${J}`,W=(await this.parseMarketplace(J))?.plugins.find((_)=>_.name===Z),K=X.has(Y),G=(K?await this.getInstalledPluginRecord(Y):null)?.installPath,H=K&&G?await this.readPluginManifest(G):null,V=!1,F=!1,B=!1,U=!1,L=!1,O=!1;if(K&&G)V=await H6(e0.join(G,"commands")),F=await H6(e0.join(G,"skills")),B=await H6(e0.join(G,"agents")),U=await H6(e0.join(G,"hooks")),L=await H6(e0.join(G,".mcp.json"))||await C4.access(e0.join(G,".mcp.json")).then(()=>!0).catch(()=>!1),O=await H6(e0.join(G,".lsp.json"))||await C4.access(e0.join(G,".lsp.json")).then(()=>!0).catch(()=>!1);return{name:Z,displayName:H?.name||W?.name||Z,description:H?.description||W?.description||"",version:H?.version||W?.version,author:H?.author?.name||W?.author?.name,category:W?.category,tags:W?.tags,marketplaceName:J,isInstalled:K,isEnabled:$[Y]??!1,source:W?.source||Z,provider:"claude",homepage:H?.homepage,repository:H?.repository,license:H?.license,hasCommands:V,hasSkills:F,hasAgents:B,hasHooks:U,hasMcpServers:L,hasLspServers:O,installPath:K?G:void 0}}async handleListMarketplacesRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/marketplaces/list",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let G={marketplaces:[],timestamp:Date.now(),error:`${Q==="codex"?"Codex":"OpenCode"} does not support marketplaces`};await this.publishResponse(Y,G,X),this.incrementRequestCount();return}let W=await this.getAllMarketplaces(),K=[];for(let{name:G,source:H,isOfficial:V}of W){let F=await this.parseMarketplace(G),B=0,U,L="Unknown";if(F)B=F.plugins.length,U=F.description,L=F.owner.name;K.push({name:G,description:U,owner:L,source:H,pluginCount:B,isOfficial:V})}let z={marketplaces:K,timestamp:Date.now()};await this.publishResponse(Y,z,X)}catch(Q){let W={marketplaces:[],timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling list marketplaces request",{error:this.formatError(J)})}}async handleListPluginsRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/list",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="codex"){if(!this.codexService){await this.publishResponse(Y,{plugins:[],timestamp:Date.now(),error:"Codex service not available"},X),this.incrementRequestCount();return}try{let V=((await this.codexService.getProcessManager().listPlugins(process.cwd()))?.data||[]).map((B)=>({name:B.id||B.name,displayName:B.name||B.id,description:B.description||"",isInstalled:B.isEnabled||!1,isEnabled:B.isEnabled||!1,marketplaceName:"codex",provider:"codex",source:B.installUrl?{source:"url",url:B.installUrl}:{source:"github",repo:""}})),F=$.scope==="installed"?V.filter((B)=>B.isInstalled):V;await this.publishResponse(Y,{plugins:F,marketplaceName:"codex",timestamp:Date.now()},X)}catch(H){await this.publishResponse(Y,{plugins:[],timestamp:Date.now(),error:"Failed to fetch Codex plugins"},X)}this.incrementRequestCount();return}if(Q==="opencode"){if($.scope!=="installed"){let F={plugins:[],marketplaceName:$.marketplaceName,timestamp:Date.now(),error:"OpenCode does not support marketplaces"};await this.publishResponse(Y,F,X),this.incrementRequestCount();return}let V={plugins:await this.listOpenCodePlugins(),marketplaceName:$.marketplaceName,timestamp:Date.now()};await this.publishResponse(Y,V,X),this.incrementRequestCount();return}let W=await this.getEnabledPlugins(),K=await this.getInstalledPlugins(),z=[];if($.scope==="installed")for(let H of K){let V=H.split("@"),F=V[0],B=V[1];if(!F||!B)continue;let U=await this.getPluginDetail(F,B);if(U)z.push({name:U.name,displayName:U.displayName,description:U.description,version:U.version,author:U.author,category:U.category,tags:U.tags,marketplaceName:B,isInstalled:!0,isEnabled:U.isEnabled,source:U.source,provider:Q})}else if($.scope==="marketplace"){let H=await this.getAllMarketplaces(),V=$.marketplaceName?H.filter((F)=>F.name===$.marketplaceName):H;for(let{name:F,source:B}of V){let U=await this.parseMarketplace(F);if(!U&&B)i0.debug(`[Plugins] Marketplace cache not found for ${F}, fetching...`),U=await this.fetchMarketplace(F,B);if(!U)continue;for(let L of U.plugins){let O=await this.marketplacePluginToEntry(L,F,W,K);z.push(O)}}}let G={plugins:z,marketplaceName:$.marketplaceName,timestamp:Date.now()};await this.publishResponse(Y,G,X)}catch(Q){let W={plugins:[],timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling list plugins request",{error:this.formatError(J)})}}async handleReadPluginRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/read",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="codex"){if(!this.codexService){await this.publishResponse(Y,{timestamp:Date.now(),error:"Codex service not available"},X),this.incrementRequestCount();return}try{let z=await this.codexService.getProcessManager().readPlugin(process.cwd(),$.marketplaceName||"",$.pluginName),G=z?{name:z.id||z.name||$.pluginName,displayName:z.name||$.pluginName,description:z.description||"",marketplaceName:$.marketplaceName||"",isInstalled:z.isEnabled||!1,isEnabled:z.isEnabled||!1,source:z.source||"local",provider:"codex",hasCommands:Array.isArray(z.commands)&&z.commands.length>0,hasSkills:Array.isArray(z.skills)&&z.skills.length>0,hasAgents:Array.isArray(z.agents)&&z.agents.length>0,hasHooks:Array.isArray(z.hooks)&&z.hooks.length>0,hasMcpServers:Array.isArray(z.mcpServers)&&z.mcpServers.length>0,hasLspServers:Array.isArray(z.lspServers)&&z.lspServers.length>0}:void 0;await this.publishResponse(Y,{plugin:G,timestamp:Date.now()},X)}catch{await this.publishResponse(Y,{timestamp:Date.now(),error:"Failed to read Codex plugin"},X)}this.incrementRequestCount();return}if(Q==="opencode"){let G={plugin:await this.readOpenCodePlugin($.pluginName)||void 0,timestamp:Date.now()};await this.publishResponse(Y,G,X),this.incrementRequestCount();return}let K={plugin:await this.getPluginDetail($.pluginName,$.marketplaceName)||void 0,timestamp:Date.now()};await this.publishResponse(Y,K,X)}catch(Q){let W={timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling read plugin request",{error:this.formatError(J)})}}async handleInstallPluginRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/install",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let z=await this.installOpenCodePlugin($.pluginName),G={success:z.success,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:z.error,restartRequired:z.success};if(await this.publishResponse(Y,G,X),z.success&&this.openCodeService)this.openCodeService.getProcessManager().restartServer().catch((H)=>{i0.error("[Plugins] Error restarting OpenCode server after plugin install",{error:H instanceof Error?H.message:"Unknown error"})});this.incrementRequestCount();return}let W=await this.installPluginFromMarketplace($.pluginName,$.marketplaceName),K={success:W.success,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:W.error};await this.publishResponse(Y,K,X)}catch(Q){let W={success:!1,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling install plugin request",{error:this.formatError(J)})}}async handleUninstallPluginRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/uninstall",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let z=await this.uninstallOpenCodePlugin($.pluginName),G={success:z.success,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:z.error,restartRequired:z.success};if(await this.publishResponse(Y,G,X),z.success&&this.openCodeService)this.openCodeService.getProcessManager().restartServer().catch((H)=>{i0.error("[Plugins] Error restarting OpenCode server after plugin uninstall",{error:H instanceof Error?H.message:"Unknown error"})});this.incrementRequestCount();return}let W=await this.uninstallPlugin($.pluginName,$.marketplaceName),K={success:W.success,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:W.error};await this.publishResponse(Y,K,X)}catch(Q){let W={success:!1,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling uninstall plugin request",{error:this.formatError(J)})}}async installOpenCodePlugin(Z){try{let J=K9(),$=await K4(J),X=$.plugin||[];if(X.includes(Z))return{success:!0};return X.push(Z),await h8(J,{...$,plugin:X}),{success:!0}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error"}}}async uninstallOpenCodePlugin(Z){try{let J=K9(),$=await K4(J),X=$.plugin||[],Y=X.indexOf(Z);if(Y===-1)return{success:!0};return X.splice(Y,1),await h8(J,{...$,plugin:X}),{success:!0}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error"}}}async handleTogglePluginRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/toggle",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){await this.setOpenCodePluginEnabled($.pluginName,$.enabled);let z={success:!0,pluginName:$.pluginName,marketplaceName:$.marketplaceName,enabled:$.enabled,timestamp:Date.now()};await this.publishResponse(Y,z,X),this.incrementRequestCount();return}let W=`${$.pluginName}@${$.marketplaceName}`;await this.setPluginEnabled(W,$.enabled);let K={success:!0,pluginName:$.pluginName,marketplaceName:$.marketplaceName,enabled:$.enabled,timestamp:Date.now()};await this.publishResponse(Y,K,X)}catch(Q){let W={success:!1,pluginName:$.pluginName,marketplaceName:$.marketplaceName,enabled:$.enabled,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling toggle plugin request",{error:this.formatError(J)})}}async handleAddMarketplaceRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/marketplace/add",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let V={success:!1,timestamp:Date.now(),error:"OpenCode does not support marketplaces"};await this.publishResponse(Y,V,X),this.incrementRequestCount();return}let W="temp_"+Date.now();if(typeof $.source==="object"&&$.source.source==="github")W=$.source.repo.split("/").pop()||W;let K=await this.fetchMarketplace(W,$.source);if(!K){let V={success:!1,timestamp:Date.now(),error:"Failed to fetch or parse marketplace"};await this.publishResponse(Y,V,X);return}let z=K.name;if(W!==z){let V=this.getMarketplaceCachePath(W),F=this.getMarketplaceCachePath(z);await C4.rm(F,{recursive:!0,force:!0}),await C4.rename(V,F)}await this.addKnownMarketplace(z,$.source);let H={success:!0,marketplace:{name:z,description:K.description,owner:K.owner.name,source:$.source,pluginCount:K.plugins.length,isOfficial:!1},timestamp:Date.now()};await this.publishResponse(Y,H,X)}catch(Q){let W={success:!1,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling add marketplace request",{error:this.formatError(J)})}}async handleRemoveMarketplaceRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/marketplace/remove",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let K={success:!1,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:"OpenCode does not support marketplaces"};await this.publishResponse(Y,K,X),this.incrementRequestCount();return}if($.marketplaceName===KK.name){let K={success:!1,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:"Cannot remove official marketplace"};await this.publishResponse(Y,K,X);return}await this.removeKnownMarketplace($.marketplaceName);let W={success:!0,marketplaceName:$.marketplaceName,timestamp:Date.now()};await this.publishResponse(Y,W,X)}catch(Q){let W={success:!1,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling remove marketplace request",{error:this.formatError(J)})}}async handleRefreshMarketplaceRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/marketplace/refresh",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let G={success:!1,marketplaceName:$.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"OpenCode does not support marketplaces"};await this.publishResponse(Y,G,X),this.incrementRequestCount();return}let W=null;if($.marketplaceName===KK.name)W=KK.source;else W=(await this.getKnownMarketplaces())[$.marketplaceName]||null;if(!W){let G={success:!1,marketplaceName:$.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"Marketplace not found"};await this.publishResponse(Y,G,X);return}let K=await this.fetchMarketplace($.marketplaceName,W);if(!K){let G={success:!1,marketplaceName:$.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"Failed to fetch marketplace"};await this.publishResponse(Y,G,X);return}let z={success:!0,marketplaceName:$.marketplaceName,pluginCount:K.plugins.length,timestamp:Date.now()};await this.publishResponse(Y,z,X)}catch(Q){let W={success:!1,marketplaceName:$.marketplaceName,pluginCount:0,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling refresh marketplace request",{error:this.formatError(J)})}}}import*as EM from"path";import*as vz1 from"os";import*as B7 from"fs";var yZ=S(),qM=EM.join(vz1.homedir(),".ccc"),CM=EM.join(qM,"forwarded-ports.json");class mF extends Q0{name="Port Forward Service";get logPrefix(){return"[PortForward]"}ngrokService=null;router=null;forwardedPorts=[];activePort=null;switchQueue=Promise.resolve();setNgrokService(Z){this.ngrokService=Z}setRouter(Z){this.router=Z}async onStart(){let Z=this.loadPersistedData();if(this.forwardedPorts=Z.forwardedPorts,Z.activePort&&this.forwardedPorts.some((J)=>J.projectId===Z.activePort.projectId&&J.port===Z.activePort.port)){let{projectId:J,port:$,ssl:X}=Z.activePort;yZ.debug(`[PortForward] Restoring active port ${$} for project ${J}`),this.doSwitch(J,$,X)}yZ.debug(`[PortForward] Started with ${this.forwardedPorts.length} persisted ports`)}async onStop(){if(this.router)this.router.clearDefaultRoute()}getStatus(){return{...super.getStatus(),forwardedPorts:[...this.forwardedPorts]}}registerMQTTHandlers(){this.registerHandler("ports/forward/request",async(Z,J)=>{let $=await this.parseMessage(J);if(!$)return;this.handleForward($.data,$.profileId)}),this.registerHandler("ports/remove/request",async(Z,J)=>{let $=await this.parseMessage(J);if(!$)return;this.handleRemove($.data,$.profileId)}),this.registerHandler("ports/list/request",async(Z,J)=>{let $=await this.parseMessage(J);if(!$)return;this.handleList($.data,$.profileId)}),this.registerHandler("ports/switch/request",async(Z,J)=>{let $=await this.parseMessage(J);if(!$)return;this.handleSwitch($.data,$.profileId)})}async handleForward(Z,J){let{projectId:$,ports:X,ssl:Y,portSsl:Q,clientId:W,requestId:K}=Z;for(let V of X){let F=Q?.[String(V)]??Y,B=this.forwardedPorts.findIndex((U)=>U.projectId===$&&U.port===V);if(B>=0)this.forwardedPorts[B].ssl=F;else this.forwardedPorts.push({projectId:$,port:V,ssl:F})}if(!this.activePort&&X.length>0){let V=X[0],F=Q?.[String(V)]??Y??!1;this.doSwitch($,V,F)}this.persistData();let z=this.router?.getStatus().port,G=this.buildResponseTopic("ports/forward",W,K),H={projectId:$,ports:X,sharedProxyPort:z,status:"ok",timestamp:Date.now()};await this.publishResponse(G,H,J),yZ.debug(`[PortForward] Forwarded ports ${X.join(", ")} for project ${$}`)}async handleRemove(Z,J){let{projectId:$,ports:X,clientId:Y,requestId:Q}=Z;for(let z of X)this.forwardedPorts=this.forwardedPorts.filter((G)=>!(G.projectId===$&&G.port===z));if(this.activePort&&X.includes(this.activePort.port)&&this.activePort.projectId===$){let z=this.forwardedPorts.filter((G)=>G.projectId===$);if(z.length>0){let G=z[0];this.doSwitch(G.projectId,G.port,G.ssl??!1)}else this.activePort=null,this.router?.clearDefaultRoute()}this.persistData();let W=this.buildResponseTopic("ports/remove",Y,Q),K={projectId:$,ports:X,sharedProxyPort:this.router?.getStatus().port,status:"ok",timestamp:Date.now()};await this.publishResponse(W,K,J),yZ.debug(`[PortForward] Removed ports ${X.join(", ")} for project ${$}`)}async handleList(Z,J){let{projectId:$,clientId:X,requestId:Y}=Z,Q=this.forwardedPorts.filter((z)=>z.projectId===$).map((z)=>z.port),W=this.buildResponseTopic("ports/list",X,Y),K={projectId:$,ports:Q,timestamp:Date.now()};await this.publishResponse(W,K,J)}handleSwitch(Z,J){let{projectId:$,port:X,ssl:Y,clientId:Q,requestId:W}=Z,K=this.buildResponseTopic("ports/switch",Q,W);this.switchQueue=this.switchQueue.then(async()=>{try{let z=Y??this.forwardedPorts.find((H)=>H.projectId===$&&H.port===X)?.ssl??!1;this.doSwitch($,X,z);let G={projectId:$,port:X,proxyPort:this.router?.getStatus().port,devTunnelUrl:this.ngrokService?.getUrl()??void 0,status:"ok",timestamp:Date.now()};await this.publishResponse(K,G,J)}catch(z){yZ.error(`[PortForward] Switch to port ${X} failed`,z);let G={projectId:$,port:X,proxyPort:this.router?.getStatus().port,status:"error",error:z.message||"Switch failed",timestamp:Date.now()};await this.publishResponse(K,G,J)}})}doSwitch(Z,J,$){if(yZ.debug(`[PortForward] Switching to port ${J} (ssl: ${$}) for project ${Z}`),this.router)this.router.setDefaultRoute(`localhost:${J}`,$);this.activePort={projectId:Z,port:J,ssl:$},this.persistData()}loadPersistedData(){try{if(B7.existsSync(CM)){let Z=B7.readFileSync(CM,"utf-8"),J=JSON.parse(Z);if(Array.isArray(J))return{forwardedPorts:J};return{forwardedPorts:J.forwardedPorts||[],activePort:J.activePort||void 0}}}catch(Z){yZ.warn("[PortForward] Failed to load persisted ports, starting fresh",Z)}return{forwardedPorts:[]}}persistData(){try{if(!B7.existsSync(qM))B7.mkdirSync(qM,{recursive:!0});let Z={forwardedPorts:this.forwardedPorts,activePort:this.activePort??void 0};B7.writeFileSync(CM,JSON.stringify(Z,null,2))}catch(Z){yZ.error("[PortForward] Failed to persist ports",Z)}}}var U7=S(),L7="[MQTTHandshake]";class PM{mqttClient;constructor(Z){this.mqttClient=Z}async start(){await M1.generateKeyPair(),this.mqttClient.subscribe("crypto/+/key-exchange",async(Z,J)=>{let X=Z.split("/")[1];try{let{encryptedKey:Y,profileId:Q}=JSON.parse(J.toString());if(!Y){U7.warn(`${L7} Key exchange missing encryptedKey from ${X}`);return}if(!Q){U7.warn(`${L7} Key exchange missing profileId from ${X}`);return}await M1.receiveClientKey(Q,Y),await this.mqttClient.publish(`crypto/${X}/ready`,JSON.stringify({ready:!0}),{qos:1}),U7.debug(`${L7} Handshake complete \u2014 key stored under profileId: ${Q} (mqtt: ${X})`)}catch(Y){U7.error(`${L7} Handshake failed for ${X}`,{error:Y instanceof Error?Y.message:String(Y)})}}),this.mqttClient.subscribe("crypto/+/handshake/request",(Z)=>{let J=Z.split("/")[1]||"";U7.debug(`${L7} Handshake requested by ${J}`),this.publishPublicKey(J)}),M1.setRekeyCallback(()=>{this.mqttClient.publish("crypto/rekey",JSON.stringify({reason:"missing_key",timestamp:Date.now()}),{qos:1}).catch(()=>{})}),U7.info(`${L7} Handshake service started`),setTimeout(()=>{this.mqttClient.publish("crypto/rekey",JSON.stringify({reason:"backend_restart",timestamp:Date.now()}),{qos:1}).catch(()=>{})},1000)}publishPublicKey(Z){let J=M1.getRSAPublicKeyPem();if(!J){U7.warn(`${L7} RSA keypair not ready, cannot send public key to ${Z}`);return}this.mqttClient.publish(`crypto/${Z}/handshake`,JSON.stringify({publicKey:J,backendVersion:O0()}),{qos:1}).then(()=>{U7.debug(`${L7} Published RSA public key to ${Z}`)}).catch(($)=>{U7.error(`${L7} Failed to publish public key to ${Z}`,{error:$ instanceof Error?$.message:String($)})})}}class IM{services=[];startedServices=[];logger=S();addService(Z){this.services.push(Z)}addOptionalService(Z,J){if(J)this.services.push(Z)}getServiceByName(Z){return this.services.find((J)=>J.name===Z)}async startAll(){for(let Z of this.services)try{this.logger.debug(`Starting ${Z.name}...`),await Z.start(),this.startedServices.push(Z)}catch(J){throw this.logger.error(`Failed to start ${Z.name}`,J),await this.stopAll(),J}this.logger.info("All services started successfully")}async stopAll(){for(let Z=this.startedServices.length-1;Z>=0;Z--){let J=this.startedServices[Z];try{this.logger.debug(`Stopping ${J?.name}...`),await J?.stop()}catch($){this.logger.error(`Failed to stop ${J?.name}`,$)}}this.startedServices=[],this.logger.info("All services stopped")}getStatus(){return this.services.map((Z)=>Z.getStatus())}printStatus(){let Z=this.getStatus();this.logger.info("=== Backend Status ===");for(let J of Z){let $=J.running?"\u2713":"\u2717";if(this.logger.info(`${$} ${J.name}`),"port"in J&&J.port)this.logger.info(` Port: ${J.port}`);if("routes"in J&&J.routes)this.logger.info(` Routes: ${J.routes.map((X)=>`${X.path}->${X.target}`).join(", ")}`);if(J.startedAt)this.logger.info(` Started: ${J.startedAt.toISOString()}`);if(J.error)this.logger.info(` Error: ${J.error}`)}this.logger.info("=====================")}}import hz1 from"os";function fz1(){let Z=hz1.networkInterfaces(),J=/^(wlan|wlp|wifi|wi-fi|en0)/i,$=/^(eth|enp|en1|ethernet)/i;for(let[X,Y]of Object.entries(Z))if(J.test(X)&&Y){let Q=Y.find((W)=>W.family==="IPv4"&&!W.internal);if(Q)return Q.address}for(let[X,Y]of Object.entries(Z))if($.test(X)&&Y){let Q=Y.find((W)=>W.family==="IPv4"&&!W.internal);if(Q)return Q.address}for(let X of Object.values(Z))if(X){let Y=X.find((Q)=>Q.family==="IPv4"&&!Q.internal);if(Y)return Y.address}return null}function bz1(){let Z=hz1.hostname().toLowerCase();if(Z.endsWith(".local"))Z=Z.slice(0,-6);return Z=Z.replace(/\./g,"-"),Z||"ccc-server"}var gz1=process.argv.slice(2);if(gz1.includes("--version")||gz1.includes("-v"))console.log(`ccc v${O0()}`),process.exit(0);function sY0(Z){let J=S();try{if(process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",($)=>{let X=$.toString().toLowerCase();if(X==="q")Z.display();if(X==="\x03")process.emit("SIGINT")}),J.debug('Keypress listener enabled (press "q" to redisplay QR codes)')}catch($){J.warn("Could not setup keypress listener",$)}}async function tY0(){let Z=null;try{V41();let J=Q41();K41(J.debug);let $=S();$.info("Backend v3 starting...");let X=W41(J);if(J.debug){let P={...X,mqtt:{...X.mqtt,auth:X.mqtt.auth?{username:X.mqtt.auth.username?"[REDACTED]":void 0,password:X.mqtt.auth.password?"[REDACTED]":void 0}:void 0},ngrok:X.ngrok?{...X.ngrok,authToken:X.ngrok.authToken?"[REDACTED]":void 0}:void 0,qrcode:{...X.qrcode,username:X.qrcode.username?"[REDACTED]":void 0,password:X.qrcode.password?"[REDACTED]":void 0}};$.debug("Configuration",P)}let Y=new GV(X.mqtt),Q=new kV({host:"localhost",port:X.mqtt.port,username:X.mqtt.auth?.username,password:X.mqtt.auth?.password}),W=new vV(X.terminal),K=new fW(X.router),z=new pV(X.autoUpdate),G=new oV,H=new rV,V=new tV(W),F=new UY(X.claudeAgent),B=new oW(X.opencodeAgent),U=new rW(X.codexAgent),L=new tW(X.piAgent),O=new OF,_=new _F,w=new TF,A=new jF,j=new SF(B,U,L),T=new xF,N=new vF,E=new hF,m=new bF,f=new gF(B,U,L),Y1=new yF,C1=new mF,Q1=new PM(Q);Y.setHandshakeService(Q1),Z=new IM,Z.addService(Y),Z.addService(Q),Z.addService(W),Z.addService(K),Z.addService(z),Z.addService(G),Z.addService(H),Z.addService(V),Z.addService(F),Z.addService(B),Z.addService(U),Z.addService(L),Z.addService(O),Z.addService(_),Z.addService(w),Z.addService(A),Z.addService(j),Z.addService(T),Z.addService(N),Z.addService(E),Z.addService(m),Z.addService(f),Z.addService(Y1),Z.addService(C1);let $1;if(X.ngrok)$1=new hV(X.ngrok),Z.addOptionalService($1,!0);if(G.setMQTTClient(Q),G.setClaudeAgentService(F),G.setOpenCodeAgentService(B),G.setCodexAgentService(U),G.setPiAgentService(L),H.setMQTTClient(Q),V.setMQTTClient(Q),F.setMQTTClient(Q),F.setSessionsService(G),B.setMQTTClient(Q),B.setSessionsService(G),U.setMQTTClient(Q),U.setSessionsService(G),L.setMQTTClient(Q),L.setSessionsService(G),O.setMQTTClient(Q),_.setMQTTClient(Q),w.setMQTTClient(Q),w.setClaudeAgentService(F),w.setOpenCodeAgentService(B),w.setCodexAgentService(U),w.setPiAgentService(L),A.setMQTTClient(Q),j.setMQTTClient(Q),T.setMQTTClient(Q),N.setMQTTClient(Q),N.setCodexAgentService(U),N.setPiAgentService(L),E.setMQTTClient(Q),m.setMQTTClient(Q),f.setMQTTClient(Q),Y1.setMQTTClient(Q),C1.setMQTTClient(Q),C1.setRouter(K),$1)C1.setNgrokService($1);await Z.startAll(),await Q1.start();let w1=Z.getServiceByName("CCC Ngrok Service"),F1,J0=fz1(),n1=J0?`${J0}:${X.router.port}`:void 0;if(w1&&w1.getStatus().active)F1=w1.getUrl()||void 0;let q4=bz1(),W0={...X.qrcode,profileName:q4,ipBasedUrl:n1,ngrokUrl:F1},z9=new mV(W0);if(Z.addService(z9),await z9.start(),Z.printStatus(),n1&&!F1)console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m SECURITY NOTICE: HTTP Connection (Unencrypted)\x1B[0m"),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""),console.log("\x1B[32m SAFE if you are on:\x1B[0m"),console.log(" - Your home/private network"),console.log(" - A trusted VPN connection"),console.log(" - localhost only"),console.log(""),console.log("\x1B[31m NOT SAFE if:\x1B[0m"),console.log(" - You are on public WiFi (coffee shop, airport, etc.)"),console.log(" - The network has untrusted users"),console.log(""),console.log(" For secure public access:"),console.log(" - Use built-in ngrok (\x1B[36m--ngrok-token\x1B[0m) for automatic HTTPS"),console.log(" - Or use Cloudflare Tunnels, Tailscale, or similar solutions"),console.log(" - Enable \x1B[36mUse SSL\x1B[0m in the mobile app with a domain-based URL"),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("");else if(F1)console.log(""),console.log("\x1B[32m Secure HTTPS connection via ngrok is active.\x1B[0m"),console.log("\x1B[32m Your traffic is encrypted end-to-end.\x1B[0m"),console.log("");$.info("Backend v3 is ready"),sY0(z9);let q0=!1,q=async(P)=>{if(q0){$.warn("Shutdown already in progress, ignoring signal");return}q0=!0,$.info(`Received ${P}, shutting down...`),Q.markShuttingDown();try{await Z.stopAll(),process.exit(0)}catch(M){$.error("Error during shutdown",M),process.exit(1)}};process.once("SIGINT",()=>q("SIGINT")),process.once("SIGTERM",()=>q("SIGTERM")),process.on("uncaughtException",async(P)=>{if(P&&P.code==="ERR_SOCKET_CLOSED"){$.debug("Ignoring socket closed error (expected during PTY cleanup)");return}$.error("Uncaught exception",P);try{Q?.markShuttingDown(),await Z?.stopAll()}catch{}process.exit(1)}),process.on("unhandledRejection",(P)=>{$.error("Unhandled rejection",P)})}catch(J){if(S().error("Fatal error",J),Z)try{await Z.stopAll()}catch{}process.exit(1)}}tY0();
2692
+ `+$.content;await b8.writeFile(W,H,"utf-8");let V={success:!0,styleName:$.styleName,scope:$.scope,timestamp:Date.now()};await this.publishResponse(Y,V,X)}catch(Q){let W={success:!1,styleName:$.styleName,scope:$.scope,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){f8.error("[OutputStyles] Error handling write style request",{error:this.formatError(J)})}}async handleDeleteStyleRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("output-styles/delete",$.clientId,$.requestId);try{let Q=this.getOutputStylesDir($.scope,$.projectPath),W=R4.join(Q,`${$.styleName}.md`),K=R4.resolve(W),z=R4.resolve(Q);if(!K.startsWith(z))throw Error("Invalid style path");if(await b8.unlink(W),await this.readActiveStyle($.scope,$.projectPath)===$.styleName)await this.setActiveStyle($.scope,"default",$.projectPath);let H={success:!0,styleName:$.styleName,scope:$.scope,timestamp:Date.now()};await this.publishResponse(Y,H,X)}catch(Q){let W={success:!1,styleName:$.styleName,scope:$.scope,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){f8.error("[OutputStyles] Error handling delete style request",{error:this.formatError(J)})}}async handleSetActiveStyleRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("output-styles/set-active",$.clientId,$.requestId);try{await this.setActiveStyle($.scope,$.styleName,$.projectPath);let Q={success:!0,styleName:$.styleName,scope:$.scope,timestamp:Date.now()};await this.publishResponse(Y,Q,X)}catch(Q){let W={success:!1,styleName:$.styleName,scope:$.scope,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){f8.error("[OutputStyles] Error handling set active style request",{error:this.formatError(J)})}}}import*as C4 from"fs/promises";import*as e0 from"path";var{$:F7}=globalThis.Bun;RZ();var i0=S(),KK={name:"claude-plugins-official",source:{source:"github",repo:"anthropics/claude-plugins-official"}};class gF extends Q0{name="Plugins Service";openCodeService;codexService;piService;constructor(Z,J,$){super();this.openCodeService=Z,this.codexService=J,this.piService=$}get logPrefix(){return"[Plugins]"}getStatus(){return{...super.getStatus()}}async onStart(){await this.ensureDirectories()}registerMQTTHandlers(){this.registerHandler("plugins/marketplaces/list/request",(Z,J)=>{this.handleListMarketplacesRequest(J)}),this.registerHandler("plugins/list/request",(Z,J)=>{this.handleListPluginsRequest(J)}),this.registerHandler("plugins/read/request",(Z,J)=>{this.handleReadPluginRequest(J)}),this.registerHandler("plugins/install/request",(Z,J)=>{this.handleInstallPluginRequest(J)}),this.registerHandler("plugins/uninstall/request",(Z,J)=>{this.handleUninstallPluginRequest(J)}),this.registerHandler("plugins/toggle/request",(Z,J)=>{this.handleTogglePluginRequest(J)}),this.registerHandler("plugins/marketplace/add/request",(Z,J)=>{this.handleAddMarketplaceRequest(J)}),this.registerHandler("plugins/marketplace/remove/request",(Z,J)=>{this.handleRemoveMarketplaceRequest(J)}),this.registerHandler("plugins/marketplace/refresh/request",(Z,J)=>{this.handleRefreshMarketplaceRequest(J)}),i0.debug("[Plugins] MQTT handlers registered")}getPluginsDir(){return e9.getPluginsDir("user")}getMarketplaceCacheDir(){return e9.getMarketplaceCacheDir()}getSettingsPath(){return e9.getUserConfigPath("settings")}getInstalledPluginsJsonPath(){return e0.join(this.getPluginsDir(),"installed_plugins.json")}getOpenCodeConfigPath(){return K9()}getPluginCacheDir(){return e0.join(this.getPluginsDir(),"cache")}async ensureDirectories(){let Z=[this.getPluginsDir(),this.getPluginCacheDir(),this.getMarketplaceCacheDir()];for(let J of Z)await C4.mkdir(J,{recursive:!0})}normalizeOpenCodePlugins(Z){return(Array.isArray(Z.plugin)?Z.plugin:Array.isArray(Z.plugins)?Z.plugins:[]).filter(Boolean)}async listOpenCodePlugins(){let Z=this.getOpenCodeConfigPath(),J=await K4(Z);return this.normalizeOpenCodePlugins(J).map((X)=>{if(typeof X==="string")return{name:X,displayName:X,description:"",marketplaceName:"opencode",isInstalled:!0,isEnabled:!0,source:X,provider:"opencode"};let Y=X.name;return{name:Y,displayName:Y,description:X.description||"",version:X.version,author:X.author,category:X.category,tags:X.tags,marketplaceName:"opencode",isInstalled:!0,isEnabled:X.enabled!==!1,source:X.source||Y,provider:"opencode"}}).filter((X)=>!!X.name)}async readOpenCodePlugin(Z){let J=this.getOpenCodeConfigPath(),$=await K4(J),Y=this.normalizeOpenCodePlugins($).find((Q)=>typeof Q==="string"?Q===Z:Q.name===Z);if(!Y)return null;if(typeof Y==="string")return{name:Y,displayName:Y,description:"",marketplaceName:"opencode",isInstalled:!0,isEnabled:!0,source:Y,provider:"opencode",hasCommands:!1,hasSkills:!1,hasAgents:!1,hasHooks:!1,hasMcpServers:!1,hasLspServers:!1};return{name:Y.name,displayName:Y.name,description:Y.description||"",version:Y.version,author:Y.author,category:Y.category,tags:Y.tags,marketplaceName:"opencode",isInstalled:!0,isEnabled:Y.enabled!==!1,source:Y.source||Y.name,provider:"opencode",hasCommands:!1,hasSkills:!1,hasAgents:!1,hasHooks:!1,hasMcpServers:!1,hasLspServers:!1}}async setOpenCodePluginEnabled(Z,J){let $=this.getOpenCodeConfigPath(),X=await K4($),Y=this.normalizeOpenCodePlugins(X),Q=Y.findIndex((W)=>typeof W==="string"?W===Z:W.name===Z);if(J){if(Q===-1)Y.push(Z);else if(typeof Y[Q]!=="string")Y[Q]={...Y[Q],enabled:!0,name:Z}}else if(Q!==-1){let W=Y[Q];if(typeof W==="string")Y.splice(Q,1);else Y[Q]={...W,enabled:!1,name:Z}}await h8($,{...X,plugin:Y})}async readSettings(){return await H7.readConfigOrEmpty(this.getSettingsPath())}async writeSettings(Z){await H7.writeConfig(this.getSettingsPath(),Z)}async getEnabledPlugins(){return(await this.readSettings()).enabledPlugins||{}}async setPluginEnabled(Z,J){let $=await this.readSettings();if(!$.enabledPlugins)$.enabledPlugins={};$.enabledPlugins[Z]=J,await this.writeSettings($)}async getKnownMarketplaces(){let J=(await this.readSettings()).extraKnownMarketplaces||{},$={};for(let[X,Y]of Object.entries(J))if(typeof Y==="object"&&Y!==null&&"source"in Y)$[X]=Y.source;else $[X]=Y;return $}async addKnownMarketplace(Z,J){let $=await this.readSettings();if(!$.extraKnownMarketplaces)$.extraKnownMarketplaces={};$.extraKnownMarketplaces[Z]={source:J},await this.writeSettings($)}async removeKnownMarketplace(Z){let J=await this.readSettings();if(J.extraKnownMarketplaces)delete J.extraKnownMarketplaces[Z],await this.writeSettings(J)}async readInstalledPluginsJson(){let Z=this.getInstalledPluginsJsonPath(),J=await A0(Z);if(!J)return{version:2,plugins:{}};try{let $=JSON.parse(J);return{version:$.version||2,plugins:$.plugins||{}}}catch($){return i0.warn("[Plugins] Failed to parse installed_plugins.json, returning empty",$),{version:2,plugins:{}}}}async writeInstalledPluginsJson(Z){let J=this.getInstalledPluginsJsonPath();await C4.writeFile(J,JSON.stringify(Z,null,2),"utf-8")}async addInstalledPluginRecord(Z,J){let $=await this.readInstalledPluginsJson();if(!$.plugins[Z])$.plugins[Z]=[];let X=$.plugins[Z].findIndex((Y)=>Y.scope===J.scope);if(X>=0)$.plugins[Z][X]=J;else $.plugins[Z].push(J);await this.writeInstalledPluginsJson($)}async removeInstalledPluginRecord(Z,J){let $=await this.readInstalledPluginsJson();if(!$.plugins[Z])return;if(J){if($.plugins[Z]=$.plugins[Z].filter((X)=>X.scope!==J),$.plugins[Z].length===0)delete $.plugins[Z]}else delete $.plugins[Z];await this.writeInstalledPluginsJson($)}async getInstalledPluginRecord(Z){let $=(await this.readInstalledPluginsJson()).plugins[Z];if(!$||$.length===0)return null;return $[0]??null}getMarketplaceCachePath(Z){return e0.join(this.getMarketplaceCacheDir(),Z)}async fetchMarketplace(Z,J){let $=this.getMarketplaceCachePath(Z);try{if(typeof J==="object"&&J.source==="github"){let Q=`https://github.com/${J.repo}.git`,W=J.ref||"main";if(await H6($))await F7`git -C ${$} fetch origin ${W}`.quiet(),await F7`git -C ${$} reset --hard origin/${W}`.quiet();else await F7`git clone --depth 1 --branch ${W} ${Q} ${$}`.quiet()}else if(typeof J==="object"&&J.source==="url"){let Q=J.url,W=J.ref||"main";if(await H6($))await F7`git -C ${$} fetch origin ${W}`.quiet(),await F7`git -C ${$} reset --hard origin/${W}`.quiet();else await F7`git clone --depth 1 --branch ${W} ${Q} ${$}`.quiet()}else if(typeof J==="string")return i0.warn("[Plugins] Relative path source not supported for marketplaces"),null;let X=e0.join($,".claude-plugin","marketplace.json"),Y=await A0(X);if(!Y){let Q=e0.join($,"marketplace.json"),W=await A0(Q);if(W)return JSON.parse(W);return i0.warn(`[Plugins] No marketplace.json found for ${Z}`),null}return JSON.parse(Y)}catch(X){return i0.error(`[Plugins] Failed to fetch marketplace ${Z}`,X),null}}async parseMarketplace(Z){let J=this.getMarketplaceCachePath(Z),$=e0.join(J,".claude-plugin","marketplace.json"),X=await A0($);if(!X)$=e0.join(J,"marketplace.json"),X=await A0($);if(!X)return null;try{return JSON.parse(X)}catch(Y){return i0.error(`[Plugins] Failed to parse marketplace.json for ${Z}`,Y),null}}async marketplacePluginToEntry(Z,J,$,X){let Y=`${Z.name}@${J}`;return{name:Z.name,displayName:Z.name,description:Z.description||"",version:Z.version,author:Z.author?.name,category:Z.category,tags:Z.tags,marketplaceName:J,isInstalled:X.has(Y),isEnabled:$[Y]??!1,source:Z.source,provider:"claude"}}async getAllMarketplaces(){let Z=await this.getKnownMarketplaces(),J=[{name:KK.name,source:KK.source,isOfficial:!0}];for(let[$,X]of Object.entries(Z))J.push({name:$,source:X,isOfficial:!1});return J}async getInstalledPlugins(){let Z=new Set,J=await this.readInstalledPluginsJson();for(let[$,X]of Object.entries(J.plugins)){if(!X||X.length===0)continue;for(let Y of X)if(Y.installPath){if(await H6(Y.installPath)){Z.add($);break}}}return Z}getPluginInstallPath(Z,J,$="1.0.0"){return e0.join(this.getPluginCacheDir(),J,Z,$)}async getPluginInstallPathFromRecord(Z,J){let $=`${Z}@${J}`;return(await this.getInstalledPluginRecord($))?.installPath||null}async getGitCommitSha(Z){try{return(await F7`git -C ${Z} rev-parse HEAD`.quiet()).stdout.toString().trim()||void 0}catch{return}}async installPluginFromMarketplace(Z,J,$="user"){try{let X=await this.parseMarketplace(J);if(!X)return{success:!1,error:"Marketplace not found or not cached"};let Y=X.plugins.find((F)=>F.name===Z);if(!Y)return{success:!1,error:"Plugin not found in marketplace"};let Q=Y.version||"1.0.0",W=this.getPluginInstallPath(Z,J,Q),K=this.getMarketplaceCachePath(J),z=`${Z}@${J}`;await C4.mkdir(e0.dirname(W),{recursive:!0});let G;if(typeof Y.source==="string"){let F=e0.join(K,Y.source);await C4.rm(W,{recursive:!0,force:!0}),await C4.cp(F,W,{recursive:!0}),G=await this.getGitCommitSha(K)}else if(Y.source.source==="github"){let F=`https://github.com/${Y.source.repo}.git`,B=Y.source.ref||"main";await C4.rm(W,{recursive:!0,force:!0}),await F7`git clone --depth 1 --branch ${B} ${F} ${W}`.quiet(),G=await this.getGitCommitSha(W)}else if(Y.source.source==="url"){let F=Y.source.url,B=Y.source.ref||"main";await C4.rm(W,{recursive:!0,force:!0}),await F7`git clone --depth 1 --branch ${B} ${F} ${W}`.quiet(),G=await this.getGitCommitSha(W)}else return{success:!1,error:"Unknown plugin source type"};let H=new Date().toISOString(),V={scope:$,installPath:W,version:Q,installedAt:H,lastUpdated:H,gitCommitSha:G};return await this.addInstalledPluginRecord(z,V),await this.setPluginEnabled(z,!0),i0.debug(`[Plugins] Installed ${z} to ${W}`),{success:!0}}catch(X){return i0.error(`[Plugins] Failed to install plugin ${Z}@${J}`,X),{success:!1,error:X instanceof Error?X.message:"Unknown error"}}}async uninstallPlugin(Z,J,$){try{let X=`${Z}@${J}`,Y=await this.getInstalledPluginRecord(X);if(!Y)return{success:!1,error:"Plugin not installed"};if(Y.installPath&&await H6(Y.installPath))await C4.rm(Y.installPath,{recursive:!0,force:!0});await this.removeInstalledPluginRecord(X,$);let Q=await this.readSettings();if(Q.enabledPlugins&&Q.enabledPlugins[X]!==void 0)delete Q.enabledPlugins[X],await this.writeSettings(Q);return i0.debug(`[Plugins] Uninstalled ${X}`),{success:!0}}catch(X){return i0.error(`[Plugins] Failed to uninstall plugin ${Z}@${J}`,X),{success:!1,error:X instanceof Error?X.message:"Unknown error"}}}async readPluginManifest(Z){let J=e0.join(Z,".claude-plugin","plugin.json"),$=await A0(J);if(!$)return null;try{return JSON.parse($)}catch(X){return null}}async getPluginDetail(Z,J){let $=await this.getEnabledPlugins(),X=await this.getInstalledPlugins(),Y=`${Z}@${J}`,W=(await this.parseMarketplace(J))?.plugins.find((_)=>_.name===Z),K=X.has(Y),G=(K?await this.getInstalledPluginRecord(Y):null)?.installPath,H=K&&G?await this.readPluginManifest(G):null,V=!1,F=!1,B=!1,U=!1,L=!1,O=!1;if(K&&G)V=await H6(e0.join(G,"commands")),F=await H6(e0.join(G,"skills")),B=await H6(e0.join(G,"agents")),U=await H6(e0.join(G,"hooks")),L=await H6(e0.join(G,".mcp.json"))||await C4.access(e0.join(G,".mcp.json")).then(()=>!0).catch(()=>!1),O=await H6(e0.join(G,".lsp.json"))||await C4.access(e0.join(G,".lsp.json")).then(()=>!0).catch(()=>!1);return{name:Z,displayName:H?.name||W?.name||Z,description:H?.description||W?.description||"",version:H?.version||W?.version,author:H?.author?.name||W?.author?.name,category:W?.category,tags:W?.tags,marketplaceName:J,isInstalled:K,isEnabled:$[Y]??!1,source:W?.source||Z,provider:"claude",homepage:H?.homepage,repository:H?.repository,license:H?.license,hasCommands:V,hasSkills:F,hasAgents:B,hasHooks:U,hasMcpServers:L,hasLspServers:O,installPath:K?G:void 0}}async handleListMarketplacesRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/marketplaces/list",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let G={marketplaces:[],timestamp:Date.now(),error:`${Q==="codex"?"Codex":"OpenCode"} does not support marketplaces`};await this.publishResponse(Y,G,X),this.incrementRequestCount();return}let W=await this.getAllMarketplaces(),K=[];for(let{name:G,source:H,isOfficial:V}of W){let F=await this.parseMarketplace(G),B=0,U,L="Unknown";if(F)B=F.plugins.length,U=F.description,L=F.owner.name;K.push({name:G,description:U,owner:L,source:H,pluginCount:B,isOfficial:V})}let z={marketplaces:K,timestamp:Date.now()};await this.publishResponse(Y,z,X)}catch(Q){let W={marketplaces:[],timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling list marketplaces request",{error:this.formatError(J)})}}async handleListPluginsRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/list",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="codex"){if(!this.codexService){await this.publishResponse(Y,{plugins:[],timestamp:Date.now(),error:"Codex service not available"},X),this.incrementRequestCount();return}try{let V=((await this.codexService.getProcessManager().listPlugins(process.cwd()))?.data||[]).map((B)=>({name:B.id||B.name,displayName:B.name||B.id,description:B.description||"",isInstalled:B.isEnabled||!1,isEnabled:B.isEnabled||!1,marketplaceName:"codex",provider:"codex",source:B.installUrl?{source:"url",url:B.installUrl}:{source:"github",repo:""}})),F=$.scope==="installed"?V.filter((B)=>B.isInstalled):V;await this.publishResponse(Y,{plugins:F,marketplaceName:"codex",timestamp:Date.now()},X)}catch(H){await this.publishResponse(Y,{plugins:[],timestamp:Date.now(),error:"Failed to fetch Codex plugins"},X)}this.incrementRequestCount();return}if(Q==="opencode"){if($.scope!=="installed"){let F={plugins:[],marketplaceName:$.marketplaceName,timestamp:Date.now(),error:"OpenCode does not support marketplaces"};await this.publishResponse(Y,F,X),this.incrementRequestCount();return}let V={plugins:await this.listOpenCodePlugins(),marketplaceName:$.marketplaceName,timestamp:Date.now()};await this.publishResponse(Y,V,X),this.incrementRequestCount();return}let W=await this.getEnabledPlugins(),K=await this.getInstalledPlugins(),z=[];if($.scope==="installed")for(let H of K){let V=H.split("@"),F=V[0],B=V[1];if(!F||!B)continue;let U=await this.getPluginDetail(F,B);if(U)z.push({name:U.name,displayName:U.displayName,description:U.description,version:U.version,author:U.author,category:U.category,tags:U.tags,marketplaceName:B,isInstalled:!0,isEnabled:U.isEnabled,source:U.source,provider:Q})}else if($.scope==="marketplace"){let H=await this.getAllMarketplaces(),V=$.marketplaceName?H.filter((F)=>F.name===$.marketplaceName):H;for(let{name:F,source:B}of V){let U=await this.parseMarketplace(F);if(!U&&B)i0.debug(`[Plugins] Marketplace cache not found for ${F}, fetching...`),U=await this.fetchMarketplace(F,B);if(!U)continue;for(let L of U.plugins){let O=await this.marketplacePluginToEntry(L,F,W,K);z.push(O)}}}let G={plugins:z,marketplaceName:$.marketplaceName,timestamp:Date.now()};await this.publishResponse(Y,G,X)}catch(Q){let W={plugins:[],timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling list plugins request",{error:this.formatError(J)})}}async handleReadPluginRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/read",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="codex"){if(!this.codexService){await this.publishResponse(Y,{timestamp:Date.now(),error:"Codex service not available"},X),this.incrementRequestCount();return}try{let z=await this.codexService.getProcessManager().readPlugin(process.cwd(),$.marketplaceName||"",$.pluginName),G=z?{name:z.id||z.name||$.pluginName,displayName:z.name||$.pluginName,description:z.description||"",marketplaceName:$.marketplaceName||"",isInstalled:z.isEnabled||!1,isEnabled:z.isEnabled||!1,source:z.source||"local",provider:"codex",hasCommands:Array.isArray(z.commands)&&z.commands.length>0,hasSkills:Array.isArray(z.skills)&&z.skills.length>0,hasAgents:Array.isArray(z.agents)&&z.agents.length>0,hasHooks:Array.isArray(z.hooks)&&z.hooks.length>0,hasMcpServers:Array.isArray(z.mcpServers)&&z.mcpServers.length>0,hasLspServers:Array.isArray(z.lspServers)&&z.lspServers.length>0}:void 0;await this.publishResponse(Y,{plugin:G,timestamp:Date.now()},X)}catch{await this.publishResponse(Y,{timestamp:Date.now(),error:"Failed to read Codex plugin"},X)}this.incrementRequestCount();return}if(Q==="opencode"){let G={plugin:await this.readOpenCodePlugin($.pluginName)||void 0,timestamp:Date.now()};await this.publishResponse(Y,G,X),this.incrementRequestCount();return}let K={plugin:await this.getPluginDetail($.pluginName,$.marketplaceName)||void 0,timestamp:Date.now()};await this.publishResponse(Y,K,X)}catch(Q){let W={timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling read plugin request",{error:this.formatError(J)})}}async handleInstallPluginRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/install",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let z=await this.installOpenCodePlugin($.pluginName),G={success:z.success,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:z.error,restartRequired:z.success};if(await this.publishResponse(Y,G,X),z.success&&this.openCodeService)this.openCodeService.getProcessManager().restartServer().catch((H)=>{i0.error("[Plugins] Error restarting OpenCode server after plugin install",{error:H instanceof Error?H.message:"Unknown error"})});this.incrementRequestCount();return}let W=await this.installPluginFromMarketplace($.pluginName,$.marketplaceName),K={success:W.success,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:W.error};await this.publishResponse(Y,K,X)}catch(Q){let W={success:!1,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling install plugin request",{error:this.formatError(J)})}}async handleUninstallPluginRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/uninstall",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let z=await this.uninstallOpenCodePlugin($.pluginName),G={success:z.success,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:z.error,restartRequired:z.success};if(await this.publishResponse(Y,G,X),z.success&&this.openCodeService)this.openCodeService.getProcessManager().restartServer().catch((H)=>{i0.error("[Plugins] Error restarting OpenCode server after plugin uninstall",{error:H instanceof Error?H.message:"Unknown error"})});this.incrementRequestCount();return}let W=await this.uninstallPlugin($.pluginName,$.marketplaceName),K={success:W.success,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:W.error};await this.publishResponse(Y,K,X)}catch(Q){let W={success:!1,pluginName:$.pluginName,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling uninstall plugin request",{error:this.formatError(J)})}}async installOpenCodePlugin(Z){try{let J=K9(),$=await K4(J),X=$.plugin||[];if(X.includes(Z))return{success:!0};return X.push(Z),await h8(J,{...$,plugin:X}),{success:!0}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error"}}}async uninstallOpenCodePlugin(Z){try{let J=K9(),$=await K4(J),X=$.plugin||[],Y=X.indexOf(Z);if(Y===-1)return{success:!0};return X.splice(Y,1),await h8(J,{...$,plugin:X}),{success:!0}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Unknown error"}}}async handleTogglePluginRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/toggle",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){await this.setOpenCodePluginEnabled($.pluginName,$.enabled);let z={success:!0,pluginName:$.pluginName,marketplaceName:$.marketplaceName,enabled:$.enabled,timestamp:Date.now()};await this.publishResponse(Y,z,X),this.incrementRequestCount();return}let W=`${$.pluginName}@${$.marketplaceName}`;await this.setPluginEnabled(W,$.enabled);let K={success:!0,pluginName:$.pluginName,marketplaceName:$.marketplaceName,enabled:$.enabled,timestamp:Date.now()};await this.publishResponse(Y,K,X)}catch(Q){let W={success:!1,pluginName:$.pluginName,marketplaceName:$.marketplaceName,enabled:$.enabled,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling toggle plugin request",{error:this.formatError(J)})}}async handleAddMarketplaceRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/marketplace/add",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let V={success:!1,timestamp:Date.now(),error:"OpenCode does not support marketplaces"};await this.publishResponse(Y,V,X),this.incrementRequestCount();return}let W="temp_"+Date.now();if(typeof $.source==="object"&&$.source.source==="github")W=$.source.repo.split("/").pop()||W;let K=await this.fetchMarketplace(W,$.source);if(!K){let V={success:!1,timestamp:Date.now(),error:"Failed to fetch or parse marketplace"};await this.publishResponse(Y,V,X);return}let z=K.name;if(W!==z){let V=this.getMarketplaceCachePath(W),F=this.getMarketplaceCachePath(z);await C4.rm(F,{recursive:!0,force:!0}),await C4.rename(V,F)}await this.addKnownMarketplace(z,$.source);let H={success:!0,marketplace:{name:z,description:K.description,owner:K.owner.name,source:$.source,pluginCount:K.plugins.length,isOfficial:!1},timestamp:Date.now()};await this.publishResponse(Y,H,X)}catch(Q){let W={success:!1,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling add marketplace request",{error:this.formatError(J)})}}async handleRemoveMarketplaceRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/marketplace/remove",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let K={success:!1,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:"OpenCode does not support marketplaces"};await this.publishResponse(Y,K,X),this.incrementRequestCount();return}if($.marketplaceName===KK.name){let K={success:!1,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:"Cannot remove official marketplace"};await this.publishResponse(Y,K,X);return}await this.removeKnownMarketplace($.marketplaceName);let W={success:!0,marketplaceName:$.marketplaceName,timestamp:Date.now()};await this.publishResponse(Y,W,X)}catch(Q){let W={success:!1,marketplaceName:$.marketplaceName,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling remove marketplace request",{error:this.formatError(J)})}}async handleRefreshMarketplaceRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J,Y=this.buildResponseTopic("plugins/marketplace/refresh",$.clientId,$.requestId);try{let Q=$.provider||"claude";if(Q==="opencode"||Q==="codex"){let G={success:!1,marketplaceName:$.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"OpenCode does not support marketplaces"};await this.publishResponse(Y,G,X),this.incrementRequestCount();return}let W=null;if($.marketplaceName===KK.name)W=KK.source;else W=(await this.getKnownMarketplaces())[$.marketplaceName]||null;if(!W){let G={success:!1,marketplaceName:$.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"Marketplace not found"};await this.publishResponse(Y,G,X);return}let K=await this.fetchMarketplace($.marketplaceName,W);if(!K){let G={success:!1,marketplaceName:$.marketplaceName,pluginCount:0,timestamp:Date.now(),error:"Failed to fetch marketplace"};await this.publishResponse(Y,G,X);return}let z={success:!0,marketplaceName:$.marketplaceName,pluginCount:K.plugins.length,timestamp:Date.now()};await this.publishResponse(Y,z,X)}catch(Q){let W={success:!1,marketplaceName:$.marketplaceName,pluginCount:0,timestamp:Date.now(),error:this.formatError(Q)};await this.publishResponse(Y,W,X)}this.incrementRequestCount()}catch(J){i0.error("[Plugins] Error handling refresh marketplace request",{error:this.formatError(J)})}}}import*as EM from"path";import*as vz1 from"os";import*as B7 from"fs";var yZ=S(),qM=EM.join(vz1.homedir(),".ccc"),CM=EM.join(qM,"forwarded-ports.json");class mF extends Q0{name="Port Forward Service";get logPrefix(){return"[PortForward]"}ngrokService=null;router=null;forwardedPorts=[];activePort=null;switchQueue=Promise.resolve();setNgrokService(Z){this.ngrokService=Z}setRouter(Z){this.router=Z}async onStart(){let Z=this.loadPersistedData();this.forwardedPorts=Z.forwardedPorts;let J=new Set;for(let $ of this.forwardedPorts){if(J.has($.port))continue;J.add($.port),this.router?.mountForwardedPort($.port,$.ssl??!1)}if(Z.activePort&&this.forwardedPorts.some(($)=>$.projectId===Z.activePort.projectId&&$.port===Z.activePort.port)){let{projectId:$,port:X,ssl:Y}=Z.activePort;yZ.debug(`[PortForward] Restoring active port ${X} for project ${$}`),this.doSwitch($,X,Y)}yZ.debug(`[PortForward] Started with ${this.forwardedPorts.length} persisted ports`)}async onStop(){if(this.router)this.router.clearDefaultRoute()}getStatus(){return{...super.getStatus(),forwardedPorts:[...this.forwardedPorts]}}registerMQTTHandlers(){this.registerHandler("ports/forward/request",async(Z,J)=>{let $=await this.parseMessage(J);if(!$)return;this.handleForward($.data,$.profileId)}),this.registerHandler("ports/remove/request",async(Z,J)=>{let $=await this.parseMessage(J);if(!$)return;this.handleRemove($.data,$.profileId)}),this.registerHandler("ports/list/request",async(Z,J)=>{let $=await this.parseMessage(J);if(!$)return;this.handleList($.data,$.profileId)}),this.registerHandler("ports/switch/request",async(Z,J)=>{let $=await this.parseMessage(J);if(!$)return;this.handleSwitch($.data,$.profileId)})}async handleForward(Z,J){let{projectId:$,ports:X,ssl:Y,portSsl:Q,clientId:W,requestId:K}=Z;for(let V of X){let F=Q?.[String(V)]??Y,B=this.forwardedPorts.findIndex((U)=>U.projectId===$&&U.port===V);if(B>=0)this.forwardedPorts[B].ssl=F;else this.forwardedPorts.push({projectId:$,port:V,ssl:F});this.router?.mountForwardedPort(V,F??!1)}if(!this.activePort&&X.length>0){let V=X[0],F=Q?.[String(V)]??Y??!1;this.doSwitch($,V,F)}this.persistData();let z=this.router?.getStatus().port,G=this.buildResponseTopic("ports/forward",W,K),H={projectId:$,ports:X,sharedProxyPort:z,status:"ok",timestamp:Date.now()};await this.publishResponse(G,H,J),yZ.debug(`[PortForward] Forwarded ports ${X.join(", ")} for project ${$}`)}async handleRemove(Z,J){let{projectId:$,ports:X,clientId:Y,requestId:Q}=Z;for(let z of X)if(this.forwardedPorts=this.forwardedPorts.filter((H)=>!(H.projectId===$&&H.port===z)),!this.forwardedPorts.some((H)=>H.port===z))this.router?.unmountForwardedPort(z);if(this.activePort&&X.includes(this.activePort.port)&&this.activePort.projectId===$){let z=this.forwardedPorts.filter((G)=>G.projectId===$);if(z.length>0){let G=z[0];this.doSwitch(G.projectId,G.port,G.ssl??!1)}else this.activePort=null,this.router?.clearDefaultRoute()}this.persistData();let W=this.buildResponseTopic("ports/remove",Y,Q),K={projectId:$,ports:X,sharedProxyPort:this.router?.getStatus().port,status:"ok",timestamp:Date.now()};await this.publishResponse(W,K,J),yZ.debug(`[PortForward] Removed ports ${X.join(", ")} for project ${$}`)}async handleList(Z,J){let{projectId:$,clientId:X,requestId:Y}=Z,Q=this.forwardedPorts.filter((z)=>z.projectId===$).map((z)=>z.port),W=this.buildResponseTopic("ports/list",X,Y),K={projectId:$,ports:Q,timestamp:Date.now()};await this.publishResponse(W,K,J)}handleSwitch(Z,J){let{projectId:$,port:X,ssl:Y,clientId:Q,requestId:W}=Z,K=this.buildResponseTopic("ports/switch",Q,W);this.switchQueue=this.switchQueue.then(async()=>{try{let z=Y??this.forwardedPorts.find((H)=>H.projectId===$&&H.port===X)?.ssl??!1;this.doSwitch($,X,z);let G={projectId:$,port:X,proxyPort:this.router?.getStatus().port,devTunnelUrl:this.ngrokService?.getUrl()??void 0,status:"ok",timestamp:Date.now()};await this.publishResponse(K,G,J)}catch(z){yZ.error(`[PortForward] Switch to port ${X} failed`,z);let G={projectId:$,port:X,proxyPort:this.router?.getStatus().port,status:"error",error:z.message||"Switch failed",timestamp:Date.now()};await this.publishResponse(K,G,J)}})}doSwitch(Z,J,$){if(yZ.debug(`[PortForward] Switching to port ${J} (ssl: ${$}) for project ${Z}`),this.router)this.router.setDefaultRoute(`localhost:${J}`,$);this.activePort={projectId:Z,port:J,ssl:$},this.persistData()}loadPersistedData(){try{if(B7.existsSync(CM)){let Z=B7.readFileSync(CM,"utf-8"),J=JSON.parse(Z);if(Array.isArray(J))return{forwardedPorts:J};return{forwardedPorts:J.forwardedPorts||[],activePort:J.activePort||void 0}}}catch(Z){yZ.warn("[PortForward] Failed to load persisted ports, starting fresh",Z)}return{forwardedPorts:[]}}persistData(){try{if(!B7.existsSync(qM))B7.mkdirSync(qM,{recursive:!0});let Z={forwardedPorts:this.forwardedPorts,activePort:this.activePort??void 0};B7.writeFileSync(CM,JSON.stringify(Z,null,2))}catch(Z){yZ.error("[PortForward] Failed to persist ports",Z)}}}var U7=S(),L7="[MQTTHandshake]";class PM{mqttClient;constructor(Z){this.mqttClient=Z}async start(){await M1.generateKeyPair(),this.mqttClient.subscribe("crypto/+/key-exchange",async(Z,J)=>{let X=Z.split("/")[1];try{let{encryptedKey:Y,profileId:Q}=JSON.parse(J.toString());if(!Y){U7.warn(`${L7} Key exchange missing encryptedKey from ${X}`);return}if(!Q){U7.warn(`${L7} Key exchange missing profileId from ${X}`);return}await M1.receiveClientKey(Q,Y),await this.mqttClient.publish(`crypto/${X}/ready`,JSON.stringify({ready:!0}),{qos:1}),U7.debug(`${L7} Handshake complete \u2014 key stored under profileId: ${Q} (mqtt: ${X})`)}catch(Y){U7.error(`${L7} Handshake failed for ${X}`,{error:Y instanceof Error?Y.message:String(Y)})}}),this.mqttClient.subscribe("crypto/+/handshake/request",(Z)=>{let J=Z.split("/")[1]||"";U7.debug(`${L7} Handshake requested by ${J}`),this.publishPublicKey(J)}),M1.setRekeyCallback(()=>{this.mqttClient.publish("crypto/rekey",JSON.stringify({reason:"missing_key",timestamp:Date.now()}),{qos:1}).catch(()=>{})}),U7.info(`${L7} Handshake service started`),setTimeout(()=>{this.mqttClient.publish("crypto/rekey",JSON.stringify({reason:"backend_restart",timestamp:Date.now()}),{qos:1}).catch(()=>{})},1000)}publishPublicKey(Z){let J=M1.getRSAPublicKeyPem();if(!J){U7.warn(`${L7} RSA keypair not ready, cannot send public key to ${Z}`);return}this.mqttClient.publish(`crypto/${Z}/handshake`,JSON.stringify({publicKey:J,backendVersion:O0()}),{qos:1}).then(()=>{U7.debug(`${L7} Published RSA public key to ${Z}`)}).catch(($)=>{U7.error(`${L7} Failed to publish public key to ${Z}`,{error:$ instanceof Error?$.message:String($)})})}}class IM{services=[];startedServices=[];logger=S();addService(Z){this.services.push(Z)}addOptionalService(Z,J){if(J)this.services.push(Z)}getServiceByName(Z){return this.services.find((J)=>J.name===Z)}async startAll(){for(let Z of this.services)try{this.logger.debug(`Starting ${Z.name}...`),await Z.start(),this.startedServices.push(Z)}catch(J){throw this.logger.error(`Failed to start ${Z.name}`,J),await this.stopAll(),J}this.logger.info("All services started successfully")}async stopAll(){for(let Z=this.startedServices.length-1;Z>=0;Z--){let J=this.startedServices[Z];try{this.logger.debug(`Stopping ${J?.name}...`),await J?.stop()}catch($){this.logger.error(`Failed to stop ${J?.name}`,$)}}this.startedServices=[],this.logger.info("All services stopped")}getStatus(){return this.services.map((Z)=>Z.getStatus())}printStatus(){let Z=this.getStatus();this.logger.info("=== Backend Status ===");for(let J of Z){let $=J.running?"\u2713":"\u2717";if(this.logger.info(`${$} ${J.name}`),"port"in J&&J.port)this.logger.info(` Port: ${J.port}`);if("routes"in J&&J.routes)this.logger.info(` Routes: ${J.routes.map((X)=>`${X.path}->${X.target}`).join(", ")}`);if(J.startedAt)this.logger.info(` Started: ${J.startedAt.toISOString()}`);if(J.error)this.logger.info(` Error: ${J.error}`)}this.logger.info("=====================")}}import hz1 from"os";function fz1(){let Z=hz1.networkInterfaces(),J=/^(wlan|wlp|wifi|wi-fi|en0)/i,$=/^(eth|enp|en1|ethernet)/i;for(let[X,Y]of Object.entries(Z))if(J.test(X)&&Y){let Q=Y.find((W)=>W.family==="IPv4"&&!W.internal);if(Q)return Q.address}for(let[X,Y]of Object.entries(Z))if($.test(X)&&Y){let Q=Y.find((W)=>W.family==="IPv4"&&!W.internal);if(Q)return Q.address}for(let X of Object.values(Z))if(X){let Y=X.find((Q)=>Q.family==="IPv4"&&!Q.internal);if(Y)return Y.address}return null}function bz1(){let Z=hz1.hostname().toLowerCase();if(Z.endsWith(".local"))Z=Z.slice(0,-6);return Z=Z.replace(/\./g,"-"),Z||"ccc-server"}var gz1=process.argv.slice(2);if(gz1.includes("--version")||gz1.includes("-v"))console.log(`ccc v${O0()}`),process.exit(0);function sY0(Z){let J=S();try{if(process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",($)=>{let X=$.toString().toLowerCase();if(X==="q")Z.display();if(X==="\x03")process.emit("SIGINT")}),J.debug('Keypress listener enabled (press "q" to redisplay QR codes)')}catch($){J.warn("Could not setup keypress listener",$)}}async function tY0(){let Z=null;try{V41();let J=Q41();K41(J.debug);let $=S();$.info("Backend v3 starting...");let X=W41(J);if(J.debug){let P={...X,mqtt:{...X.mqtt,auth:X.mqtt.auth?{username:X.mqtt.auth.username?"[REDACTED]":void 0,password:X.mqtt.auth.password?"[REDACTED]":void 0}:void 0},ngrok:X.ngrok?{...X.ngrok,authToken:X.ngrok.authToken?"[REDACTED]":void 0}:void 0,qrcode:{...X.qrcode,username:X.qrcode.username?"[REDACTED]":void 0,password:X.qrcode.password?"[REDACTED]":void 0}};$.debug("Configuration",P)}let Y=new GV(X.mqtt),Q=new kV({host:"localhost",port:X.mqtt.port,username:X.mqtt.auth?.username,password:X.mqtt.auth?.password}),W=new vV(X.terminal),K=new fW(X.router),z=new pV(X.autoUpdate),G=new oV,H=new rV,V=new tV(W),F=new UY(X.claudeAgent),B=new oW(X.opencodeAgent),U=new rW(X.codexAgent),L=new tW(X.piAgent),O=new OF,_=new _F,w=new TF,A=new jF,j=new SF(B,U,L),T=new xF,N=new vF,E=new hF,m=new bF,f=new gF(B,U,L),Y1=new yF,C1=new mF,Q1=new PM(Q);Y.setHandshakeService(Q1),Z=new IM,Z.addService(Y),Z.addService(Q),Z.addService(W),Z.addService(K),Z.addService(z),Z.addService(G),Z.addService(H),Z.addService(V),Z.addService(F),Z.addService(B),Z.addService(U),Z.addService(L),Z.addService(O),Z.addService(_),Z.addService(w),Z.addService(A),Z.addService(j),Z.addService(T),Z.addService(N),Z.addService(E),Z.addService(m),Z.addService(f),Z.addService(Y1),Z.addService(C1);let $1;if(X.ngrok)$1=new hV(X.ngrok),Z.addOptionalService($1,!0);if(G.setMQTTClient(Q),G.setClaudeAgentService(F),G.setOpenCodeAgentService(B),G.setCodexAgentService(U),G.setPiAgentService(L),H.setMQTTClient(Q),V.setMQTTClient(Q),F.setMQTTClient(Q),F.setSessionsService(G),B.setMQTTClient(Q),B.setSessionsService(G),U.setMQTTClient(Q),U.setSessionsService(G),L.setMQTTClient(Q),L.setSessionsService(G),O.setMQTTClient(Q),_.setMQTTClient(Q),w.setMQTTClient(Q),w.setClaudeAgentService(F),w.setOpenCodeAgentService(B),w.setCodexAgentService(U),w.setPiAgentService(L),A.setMQTTClient(Q),j.setMQTTClient(Q),T.setMQTTClient(Q),N.setMQTTClient(Q),N.setCodexAgentService(U),N.setPiAgentService(L),E.setMQTTClient(Q),m.setMQTTClient(Q),f.setMQTTClient(Q),Y1.setMQTTClient(Q),C1.setMQTTClient(Q),C1.setRouter(K),$1)C1.setNgrokService($1);await Z.startAll(),await Q1.start();let w1=Z.getServiceByName("CCC Ngrok Service"),F1,J0=fz1(),n1=J0?`${J0}:${X.router.port}`:void 0;if(w1&&w1.getStatus().active)F1=w1.getUrl()||void 0;let q4=bz1(),W0={...X.qrcode,profileName:q4,ipBasedUrl:n1,ngrokUrl:F1},z9=new mV(W0);if(Z.addService(z9),await z9.start(),Z.printStatus(),n1&&!F1)console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m SECURITY NOTICE: HTTP Connection (Unencrypted)\x1B[0m"),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""),console.log("\x1B[32m SAFE if you are on:\x1B[0m"),console.log(" - Your home/private network"),console.log(" - A trusted VPN connection"),console.log(" - localhost only"),console.log(""),console.log("\x1B[31m NOT SAFE if:\x1B[0m"),console.log(" - You are on public WiFi (coffee shop, airport, etc.)"),console.log(" - The network has untrusted users"),console.log(""),console.log(" For secure public access:"),console.log(" - Use built-in ngrok (\x1B[36m--ngrok-token\x1B[0m) for automatic HTTPS"),console.log(" - Or use Cloudflare Tunnels, Tailscale, or similar solutions"),console.log(" - Enable \x1B[36mUse SSL\x1B[0m in the mobile app with a domain-based URL"),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("");else if(F1)console.log(""),console.log("\x1B[32m Secure HTTPS connection via ngrok is active.\x1B[0m"),console.log("\x1B[32m Your traffic is encrypted end-to-end.\x1B[0m"),console.log("");$.info("Backend v3 is ready"),sY0(z9);let q0=!1,q=async(P)=>{if(q0){$.warn("Shutdown already in progress, ignoring signal");return}q0=!0,$.info(`Received ${P}, shutting down...`),Q.markShuttingDown();try{await Z.stopAll(),process.exit(0)}catch(M){$.error("Error during shutdown",M),process.exit(1)}};process.once("SIGINT",()=>q("SIGINT")),process.once("SIGTERM",()=>q("SIGTERM")),process.on("uncaughtException",async(P)=>{if(P&&P.code==="ERR_SOCKET_CLOSED"){$.debug("Ignoring socket closed error (expected during PTY cleanup)");return}$.error("Uncaught exception",P);try{Q?.markShuttingDown(),await Z?.stopAll()}catch{}process.exit(1)}),process.on("unhandledRejection",(P)=>{$.error("Unhandled rejection",P)})}catch(J){if(S().error("Fatal error",J),Z)try{await Z.stopAll()}catch{}process.exit(1)}}tY0();