@naarang/ccc 3.1.0-beta.6 → 3.1.0-beta.7

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.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -50,7 +50,7 @@ Event: ${X7(Z)}`),!0}return!1}function VE0(Z,J){if(!J?.length)return!1;return hK
50
50
  `;let K=tl(X);X.write(`${W}\r
51
51
  `);let{connect:z,buffered:G}=await K;if(Z.emit("proxyConnect",z),this.emit("proxyConnect",z,Z),z.statusCode===200){if(Z.once("socket",ex0),J.secureEndpoint){T3("Upgrading socket connection to TLS");let V=J.servername||J.host;return b2.connect({...el(J,"host","path","port"),socket:X,servername:z9.isIP(V)?void 0:V})}return X}X.destroy();let H=new z9.Socket({writable:!1});return H.readable=!0,Z.once("socket",(V)=>{T3("Replaying proxy buffer for failed request"),V.push(G),V.push(null)}),H}}Iz.__initStatic();function ex0(Z){Z.resume()}function el(Z,...J){let $={},X;for(X in Z)if(!J.includes(X))$[X]=Z[X];return $}var Yv0=32768;function Qv0(Z){return new $v0({read(){this.push(Z),this.push(null)}})}function g2(Z){let J;try{J=new URL(Z.url)}catch(z){return m1(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),mZ(Z,()=>Promise.resolve({}))}let $=J.protocol==="https:",X=Wv0(J,Z.proxy||($?process.env.https_proxy:void 0)||process.env.http_proxy),Y=$?Jv0:Zv0,Q=Z.keepAlive===void 0?!1:Z.keepAlive,W=X?new Iz(X):new Y.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),K=Kv0(Z,Z.httpModule??Y,W);return mZ(Z,K)}function Wv0(Z,J){let{no_proxy:$}=process.env;if($?.split(",").some((Y)=>Z.host.endsWith(Y)||Z.hostname.endsWith(Y)))return;else return J}function Kv0(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)=>{H7(()=>{let F=Qv0(G.body),B={...Z.headers};if(G.body.length>Yv0)B["content-encoding"]="gzip",F=F.pipe(Xv0());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 zv0=new Set(["false","f","n","no","off","0"]),Gv0=new Set(["true","t","y","yes","on","1"]);function Sz(Z,J){let $=String(Z).toLowerCase();if(zv0.has($))return!1;if(Gv0.has($))return!0;return J?.strict?null:Boolean(Z)}import{posix as Hv0,sep as Vv0}from"path";function Zp(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function m2(Z=process.argv[1]?BL(process.argv[1]):process.cwd(),J=Vv0==="\\"){let $=J?Zp(Z):Z;return(X)=>{if(!X)return;let Y=J?Zp(X):X,{dir:Q,base:W,ext:K}=Hv0.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 u2(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(z0.SENTRY_RELEASE?.id)return z0.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 d2=LK(fL(m2()));var $p=v(m(),1),Xp=v(U0(),1);import*as Jp from"os";import{threadId as Fv0,isMainThread as Bv0}from"worker_threads";var Uv0=60000;class yz extends gK{constructor(Z){let J=Z.includeServerName===!1?void 0:Z.serverName||global.process.env.SENTRY_NAME||Jp.hostname(),$={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)Xp.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});$9($,"node"),A.log(`Initializing Sentry: process: ${process.pid}, thread: ${Bv0?"main":`worker-${Fv0}`}.`);super($);if(this.getOptions().enableLogs){if(this._logOnExitFlushListener=()=>{cY(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=y0,$=$p.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(()=>{A0&&A.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??Uv0).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_setupIntegrations(){WL(),super._setupIntegrations()}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return nc(this,Z)}}var Yp=v(iB(),1);import*as Qp from"module";function c2(){if(!Pl())return;if(!z0._sentryEsmLoaderHookRegistered){z0._sentryEsmLoaderHookRegistered=!0;try{let{addHookMessagePort:Z}=Yp.createAddHookMessageChannel();Qp.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:Z,include:[]},transferList:[Z]})}catch(Z){A.warn("Failed to register 'import-in-the-middle' hook",Z)}}}function kz(){return[w$(),_$(),j$(),M$(),I2(),A$(),ol(),rl(),i$(),n$(),l$(),q2(),c$(),y2(),sl(),p$()]}function l2(Z={}){return Lv0(Z,kz)}function Lv0(Z={},J){let $=Dv0(Z,J);if($.debug===!0)if(A0)A.enable();else m1(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if($.registerEsmLoaderHooks!==!1)c2();if(rc(),o0().update($.initialScope),$.spotlight&&!$.integrations.some(({name:Q})=>Q===E2))$.integrations.push(P2({sidecarUrl:typeof $.spotlight==="string"?$.spotlight:void 0}));$9($,"node-core");let Y=new yz($);if(o0().setClient(Y),Y.init(),z0._sentryInjectLoaderHookRegister?.(),A.log(`SDK initialized from ${_3()?"CommonJS":"ESM"}`),Y.startClientReportTracking(),wv0(),xc(Y),oc(Y),process.env.VERCEL)process.on("SIGTERM",async()=>{await Y.flush(200)});return Y}function xz(){if(!A0)return;let Z=bc(),J=["SentryContextManager","SentryPropagator"];if(A1())J.push("SentrySpanProcessor");for(let $ of J)if(!Z.includes($))A.error(`You have to set up the ${$}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))A.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 Dv0(Z,J){let $=Ov0(Z.release),X;if(Z.spotlight===!1)X=!1;else if(typeof Z.spotlight==="string")X=Z.spotlight;else{let z=Sz(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=_v0(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??g2,stackParser:_U(Z.stackParser||d2),release:$,tracesSampleRate:Y,spotlight:X,debug:Sz(Z.debug??process.env.SENTRY_DEBUG)},W=Z.integrations,K=Z.defaultIntegrations??J(Q);return{...Q,integrations:aU({defaultIntegrations:K,integrations:W})}}function Ov0(Z){if(Z!==void 0)return Z;let J=u2();if(J!==void 0)return J;return}function _v0(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 wv0(){if(Sz(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,$=xZ(Z,J);o0().setPropagationContext($)}}function Z1(Z,J){Z.setAttribute(Q0,J)}var p2="Http",Wp="@opentelemetry_sentry-patched/instrumentation-http",jv0=s(`${p2}.sentry`,(Z)=>{return new m$(Z)}),Mv0=s(p2,(Z)=>{let J=new zp.HttpInstrumentation({...Z,disableIncomingRequestInstrumentation:!0});try{J._diag=Kp.diag.createComponentLogger({namespace:Wp}),J.instrumentationName=Wp}catch{}return J});function Av0(Z,J={}){if(typeof Z.spans==="boolean")return Z.spans;if(J.skipOpenTelemetrySetup)return!1;if(!A1(J)&&E7.major>=22)return!1;return!0}var N3=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=I$(X),W=S$(Y),K=J&&!$;return{name:p2,setup(z){let G=z.getOptions();if(K&&A1(G))W.setup(z)},setupOnce(){let z=p()?.getOptions()||{},G=Av0(Z,z);Q.setupOnce();let H={breadcrumbs:Z.breadcrumbs,propagateTraceInOutgoingRequests:!G,ignoreOutgoingRequests:Z.ignoreOutgoingRequests};if(jv0(H),G){let V=Tv0(Z);Mv0(V)}},processEvent(z){return W.processEvent(z)}}});function Tv0(Z={}){return{ignoreOutgoingRequestHook:($)=>{let X=K3($);if(!X)return!1;let Y=Z.ignoreOutgoingRequests;if(Y?.(X,$))return!0;return!1},requireParentforOutgoingSpans:!1,requestHook:($,X)=>{Z1($,"auto.http.otel.http"),Z.instrumentation?.requestHook?.($,X)},responseHook:($,X)=>{Z.instrumentation?.responseHook?.($,X)},applyCustomAttributesOnSpan:($,X,Y)=>{Z.instrumentation?.applyCustomAttributesOnSpan?.($,X,Y)}}}var _p=v(Op(),1);var wp="NodeFetch",Ev0=s(wp,_p.UndiciInstrumentation,(Z)=>{return kv0(Z)}),Pv0=s(`${wp}.sentry`,d$,(Z)=>{return Z}),Iv0=(Z={})=>{return{name:"NodeFetch",setupOnce(){if(yv0(Z,p()?.getOptions()))Ev0(Z);Pv0(Z)}}},q3=k(Iv0);function Sv0(Z,J="/"){let $=`${Z}`;if($.endsWith("/")&&J.startsWith("/"))return`${$}${J.slice(1)}`;if(!$.endsWith("/")&&!J.startsWith("/"))return`${$}/${J.slice(1)}`;return`${$}${J}`}function yv0(Z,J={}){return typeof Z.spans==="boolean"?Z.spans:!J.skipOpenTelemetrySetup&&A1(J)}function kv0(Z={}){return{requireParentforSpans:!1,ignoreRequestHook:($)=>{let X=Sv0($.origin,$.path),Y=Z.ignoreOutgoingRequests;return!!(Y&&X&&Y(X))},startSpanHook:()=>{return{[Q0]:"auto.http.otel.node_fetch"}},requestHook:Z.requestHook,responseHook:Z.responseHook}}var up=v(mp(),1);var k1=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var dp="Express";function Yh0(Z){Z1(Z,"auto.http.otel.express");let J=$0(Z).data,$=J["express.type"];if($)Z.setAttribute(V0,`${$}.express`);let X=J["express.name"];if(typeof X==="string")Z.updateName(X)}function Qh0(Z,J){if(x0()===A6())return k1&&A.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";x0().setTransactionName(`${X} ${Z.route}`)}return J}var cp=s(dp,()=>new up.ExpressInstrumentation({requestHook:(Z)=>Yh0(Z),spanNameHook:(Z,J)=>Qh0(Z,J)})),Wh0=()=>{return{name:dp,setupOnce(){cp()}}},lp=k(Wh0);import*as WD from"diagnostics_channel";var d1=v(m(),1),dz=v(_1(),1),Mi=v(U0(),1),o1=v(e0(),1);import Di from"diagnostics_channel";var Vi=v(Xi(),1);var P3=(Z)=>{if(typeof Z!=="string")throw TypeError("invalid pattern");if(Z.length>65536)throw TypeError("pattern is too long")};var Uh0={"[: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]},I3=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),Lh0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Yi=(Z)=>Z.join(""),Qi=(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,j]]of Object.entries(Uh0))if(Z.startsWith(O,Q)){if(V)return["$.",!1,Z.length-$,!0];if(Q+=O.length,j)Y.push(_);else X.push(_);K=K||w;continue Z}}if(z=!1,V){if(L>V)X.push(I3(V)+"-"+I3(L));else if(L===V)X.push(I3(L));V="",Q++;continue}if(Z.startsWith("-]",Q+1)){X.push(I3(L+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){V=L,Q+=2;continue}X.push(I3(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[Lh0(L),!1,H-$,!1]}let F="["+(G?"^":"")+Yi(X)+"]",B="["+(G?"":"^")+Yi(Y)+"]";return[X.length&&Y.length?"("+F+"|"+B+")":X.length?F:B,K,H-$,!0]};var P7=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var Dh0=new Set(["!","?","+","*","@"]),Wi=(Z)=>Dh0.has(Z),Oh0="(?!(?:^|/)\\.\\.?(?:$|/))",mz="(?!\\.)",_h0=new Set(["[","."]),wh0=new Set(["..","."]),jh0=new Set("().*{}+?[]^$\\!"),Mh0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),JD="[^/]",Ki=JD+"*?",zi=JD+"+?";class w4{type;#J;#$;#G=!1;#X=[];#Y;#B;#Q;#H=!1;#K;#W;#Z=!1;constructor(Z,J,$={}){if(this.type=Z,Z)this.#$=!0;if(this.#Y=J,this.#J=this.#Y?this.#Y.#J:this,this.#K=this.#J===this?$:this.#J.#K,this.#Q=this.#J===this?[]:this.#J.#Q,Z==="!"&&!this.#J.#H)this.#Q.push(this);this.#B=this.#Y?this.#Y.#X.length:0}get hasMagic(){if(this.#$!==void 0)return this.#$;for(let Z of this.#X){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#$=!0}return this.#$}toString(){if(this.#W!==void 0)return this.#W;if(!this.type)return this.#W=this.#X.map((Z)=>String(Z)).join("");else return this.#W=this.type+"("+this.#X.map((Z)=>String(Z)).join("|")+")"}#L(){if(this!==this.#J)throw Error("should only call on root");if(this.#H)return this;this.toString(),this.#H=!0;let Z;while(Z=this.#Q.pop()){if(Z.type!=="!")continue;let J=Z,$=J.#Y;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.#Y}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof w4&&J.#Y===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.#J||this.#J.#H&&this.#Y?.type==="!"))Z.push({});return Z}isStart(){if(this.#J===this)return!0;if(!this.#Y?.isStart())return!1;if(this.#B===0)return!0;let Z=this.#Y;for(let J=0;J<this.#B;J++){let $=Z.#X[J];if(!($ instanceof w4&&$.type==="!"))return!1}return!0}isEnd(){if(this.#J===this)return!0;if(this.#Y?.type==="!")return!0;if(!this.#Y?.isEnd())return!1;if(!this.type)return this.#Y?.isEnd();let Z=this.#Y?this.#Y.#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 w4(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&&Wi(U)&&Z.charAt(F)==="("){J.push(B),B="";let L=new w4(U,J);F=w4.#D(Z,L,F,X),J.push(L);continue}B+=U}return J.push(B),F}let z=$+1,G=new w4(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(Wi(F)&&Z.charAt(z)==="("){G.push(V),V="";let B=new w4(F,G);G.push(B),z=w4.#D(Z,B,z,X);continue}if(F==="|"){G.push(V),V="",H.push(G),G=new w4(null,J);continue}if(F===")"){if(V===""&&J.#X.length===0)J.#Z=!0;return G.push(V),V="",J.push(...H,G),z}V+=F}return J.type=null,J.#$=void 0,J.#X=[Z.substring($-1)],z}static fromGlob(Z,J={}){let $=new w4(null,void 0,J);return w4.#D(Z,$,0,J),$}toMMPattern(){if(this!==this.#J)return this.#J.toMMPattern();let Z=this.toString(),[J,$,X,Y]=this.toRegExpSource();if(!(X||this.#$||this.#K.nocase&&!this.#K.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return $;let W=(this.#K.nocase?"i":"")+(Y?"u":"");return Object.assign(new RegExp(`^${J}$`,W),{_src:J,_glob:Z})}get options(){return this.#K}toRegExpSource(Z){let J=Z??!!this.#K.dot;if(this.#J===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"?w4.#V(F,this.#$,K):F.toRegExpSource(Z);return this.#$=this.#$||L,this.#G=this.#G||O,B}).join(""),G="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&wh0.has(this.#X[0]))){let B=_h0,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?Oh0:L?mz:""}}}let H="";if(this.isEnd()&&this.#J.#H&&this.#Y?.type==="!")H="(?:$|\\/)";return[G+z+H,P7(z),this.#$=!!this.#$,this.#G]}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.#$=void 0,[K,P7(this.toString()),!1,!1]}let Q=!$||Z||J||!mz?"":this.#F(!0);if(Q===Y)Q="";if(Q)Y=`(?:${Y})(?:${Q})*?`;let W="";if(this.type==="!"&&this.#Z)W=(this.isStart()&&!J?mz:"")+zi;else{let K=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?mz:"")+Ki+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;W=X+Y+K}return[W,P7(Y),this.#$=!!this.#$,this.#G]}#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.#G=this.#G||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+=(jh0.has(K)?"\\":"")+K;continue}if(K==="\\"){if(W===Z.length-1)Y+="\\\\";else X=!0;continue}if(K==="["){let[z,G,H,V]=Qi(Z,W);if(H){Y+=z,Q=Q||G,W+=H-1,J=J||V;continue}}if(K==="*"){if($&&Z==="*")Y+=zi;else Y+=Ki;J=!0;continue}if(K==="?"){Y+=JD,J=!0;continue}Y+=Mh0(K)}return[Y,P7(Z),!!J,Q]}}var $D=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var j4=(Z,J,$={})=>{if(P3(J),!$.nocomment&&J.charAt(0)==="#")return!1;return new S3(J,$).match(Z)},Ah0=/^\*+([^+@!?\*\[\(]*)$/,Th0=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),Nh0=(Z)=>(J)=>J.endsWith(Z),Rh0=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},qh0=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},Ch0=/^\*+\.\*+$/,Eh0=(Z)=>!Z.startsWith(".")&&Z.includes("."),Ph0=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),Ih0=/^\.\*+$/,Sh0=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),yh0=/^\*+$/,kh0=(Z)=>Z.length!==0&&!Z.startsWith("."),xh0=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",vh0=/^\?+([^+@!?\*\[\(]*)?$/,hh0=([Z,J=""])=>{let $=Fi([Z]);if(!J)return $;return J=J.toLowerCase(),(X)=>$(X)&&X.toLowerCase().endsWith(J)},fh0=([Z,J=""])=>{let $=Bi([Z]);if(!J)return $;return J=J.toLowerCase(),(X)=>$(X)&&X.toLowerCase().endsWith(J)},bh0=([Z,J=""])=>{let $=Bi([Z]);return!J?$:(X)=>$(X)&&X.endsWith(J)},gh0=([Z,J=""])=>{let $=Fi([Z]);return!J?$:(X)=>$(X)&&X.endsWith(J)},Fi=([Z])=>{let J=Z.length;return($)=>$.length===J&&!$.startsWith(".")},Bi=([Z])=>{let J=Z.length;return($)=>$.length===J&&$!=="."&&$!==".."},Ui=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Gi={win32:{sep:"\\"},posix:{sep:"/"}},mh0=Ui==="win32"?Gi.win32.sep:Gi.posix.sep;j4.sep=mh0;var e6=Symbol("globstar **");j4.GLOBSTAR=e6;var uh0="[^/]",dh0=uh0+"*?",ch0="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",lh0="(?:(?!(?:\\/|^)\\.).)*?",ph0=(Z,J={})=>($)=>j4($,Z,J);j4.filter=ph0;var t6=(Z,J={})=>Object.assign({},Z,J),ih0=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return j4;let J=j4;return Object.assign((X,Y,Q={})=>J(X,Y,t6(Z,Q)),{Minimatch:class extends J.Minimatch{constructor(Y,Q={}){super(Y,t6(Z,Q))}static defaults(Y){return J.defaults(t6(Z,Y)).Minimatch}},AST:class extends J.AST{constructor(Y,Q,W={}){super(Y,Q,t6(Z,W))}static fromGlob(Y,Q={}){return J.AST.fromGlob(Y,t6(Z,Q))}},unescape:(X,Y={})=>J.unescape(X,t6(Z,Y)),escape:(X,Y={})=>J.escape(X,t6(Z,Y)),filter:(X,Y={})=>J.filter(X,t6(Z,Y)),defaults:(X)=>J.defaults(t6(Z,X)),makeRe:(X,Y={})=>J.makeRe(X,t6(Z,Y)),braceExpand:(X,Y={})=>J.braceExpand(X,t6(Z,Y)),match:(X,Y,Q={})=>J.match(X,Y,t6(Z,Q)),sep:J.sep,GLOBSTAR:e6})};j4.defaults=ih0;var Li=(Z,J={})=>{if(P3(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return Vi.default(Z)};j4.braceExpand=Li;var nh0=(Z,J={})=>new S3(Z,J).makeRe();j4.makeRe=nh0;var ah0=(Z,J,$={})=>{let X=new S3(J,$);if(Z=Z.filter((Y)=>X.match(Y)),X.options.nonull&&!Z.length)Z.push(J);return Z};j4.match=ah0;var Hi=/[?*]|[+@!]\(.*?\)|\[|\]/,oh0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class S3{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(P3(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||Ui,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]==="?"||!Hi.test(Y[2]))&&!Hi.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,j=_?3:O?0:void 0;if(typeof w==="number"&&typeof j==="number"){let[T,N]=[Z[w],J[j]];if(T.toLowerCase()===N.toLowerCase()){if(J[j]=T,j>w)J=J.slice(j);else if(w>j)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===e6){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(`
52
52
  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(`
53
- >>> 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 Li(this.pattern,this.options)}parse(Z){P3(Z);let J=this.options;if(Z==="**")return e6;if(Z==="")return"";let $,X=null;if($=Z.match(yh0))X=J.dot?xh0:kh0;else if($=Z.match(Ah0))X=(J.nocase?J.dot?qh0:Rh0:J.dot?Nh0:Th0)($[1]);else if($=Z.match(vh0))X=(J.nocase?J.dot?fh0:hh0:J.dot?bh0:gh0)($);else if($=Z.match(Ch0))X=J.dot?Ph0:Eh0;else if($=Z.match(Ih0))X=Sh0;let Y=w4.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?dh0:J.dot?ch0:lh0,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"?oh0(G):G===e6?e6:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==e6||F===e6)return;if(F===void 0)if(V!==void 0&&V!==e6)z[H+1]="(?:\\/|"+$+"\\/)?"+V;else z[H]=$;else if(V===void 0)z[H-1]=F+"(?:\\/|"+$+")?";else if(V!==e6)z[H-1]=F+"(?:\\/|\\/"+$+"\\/)"+V,z[H+1]=e6}),z.filter((G)=>G!==e6).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 j4.defaults(Z).Minimatch}}j4.AST=w4;j4.Minimatch=S3;j4.escape=$D;j4.unescape=P7;var Oi="@fastify/otel",sh0="0.8.0",th0=">=4.0.0 <6",_i=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],H1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},I7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},G9="anonymous",p4=Symbol("fastify otel instance"),S7=Symbol("fastify otel request spans"),y3=Symbol("fastify otel request context"),wi=Symbol("fastify otel addhook original"),ji=Symbol("fastify otel setnotfound original"),uz=Symbol("fastify otel ignore path");class XD extends Mi.InstrumentationBase{constructor(Z){super(Oi,sh0,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[uz]=null,this._logger=d1.diag.createComponentLogger({namespace:Oi}),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 $=j4;this[uz]=(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)},Di.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)Di.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:th0,name:"@fastify/otel"},J;function J($,X,Y){$.decorate(p4,Z),$.decorate(wi,$.addHook),$.decorate(ji,$.setNotFoundHandler),$.decorateRequest("opentelemetry",function(){let V=this[y3];return{span:this[S7],tracer:Z.tracer,context:V,inject:(B,U)=>{return d1.propagation.inject(V,B,U)},extract:(B,U)=>{return d1.propagation.extract(V,B,U)}}}),$.decorateRequest(S7,null),$.decorateRequest(y3,null),$.addHook("onRoute",function(H){if(Z[uz]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of _i)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[H1.FASTIFY_TYPE]:I7.ROUTE,[o1.ATTR_HTTP_ROUTE]:H.url,[H1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:G9});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[H1.FASTIFY_TYPE]:I7.ROUTE,[o1.ATTR_HTTP_ROUTE]:H.url,[H1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:G9}));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,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - route-handler`,[H1.FASTIFY_TYPE]:I7.HANDLER,[o1.ATTR_HTTP_ROUTE]:H.url,[H1.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:G9})}),$.addHook("onRequest",function(H,V,F){if(this[p4].isEnabled()===!1)return F();else if(this[p4][uz]?.({url:H.url,method:H.method})===!0)return this[p4]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=d1.context.active();if(d1.trace.getSpan(B)==null)B=d1.propagation.extract(B,H.headers);let U=dz.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===dz.RPCType.HTTP)U.route=H.routeOptions.url;let L=this[p4].tracer.startSpan("request",{attributes:{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.ROOT]:"@fastify/otel",[o1.ATTR_HTTP_ROUTE]:H.url,[o1.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[y3]=d1.trace.setSpan(B,L),H[S7]=L,d1.context.with(H[y3],()=>{F()})}),$.addHook("onResponse",function(H,V,F){let B=H[S7];if(B!=null)B.setStatus({code:d1.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[o1.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[S7]=null,F()}),$.addHook=K,$.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[S7];if(U!=null){if(V.statusCode<500)U.setStatus({code:d1.SpanStatusCode.OK,message:"OK"});U.setAttributes({[o1.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[S7]=null,B(null,F)}function W(H,V,F,B){let U=H[S7];if(U!=null)U.setStatus({code:d1.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[wi];if(_i.includes(H))return F.call(this,H,G(V,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - ${H}`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:G9}));else return F.call(this,H,V)}function z(H,V){let F=this[ji];if(typeof H==="function")V=G(H,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:G9}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:G9});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:G9});V=G(V,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:G9}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[p4],[L]=B;if(U.isEnabled()===!1)return H.call(this,...B);let O=L[y3]??d1.context.active(),_=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??G9}`,{attributes:V},O);return d1.context.with(d1.trace.setSpan(O,_),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((j)=>{return _.end(),j},(j)=>{return _.setStatus({code:d1.SpanStatusCode.ERROR,message:j.message}),_.recordException(j),_.end(),Promise.reject(j)});return _.end(),w}catch(w){throw _.setStatus({code:d1.SpanStatusCode.ERROR,message:w.message}),_.recordException(w),_.end(),w}},this)}}}}}var d8=v(m(),1),lz=v(_1(),1),ZJ=v(U0(),1),qi=v(e0(),1);var H9;(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})(H9||(H9={}));var k3;(function(Z){Z.MIDDLEWARE="middleware";let $="request_handler";Z.REQUEST_HANDLER=$})(k3||(k3={}));var x3;(function(Z){Z.MIDDLEWARE="middleware";let $="request handler";Z.REQUEST_HANDLER=$})(x3||(x3={}));var Ti=v(m(),1);var v3=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function YD(Z,J,$,X={}){let Y=J.startSpan($,{attributes:X}),Q=Z[v3]||[];return Q.push(Y),Object.defineProperty(Z,v3,{enumerable:!1,configurable:!0,value:Q}),Y}function cz(Z,J){let $=Z[v3]||[];if(!$.length)return;$.forEach((X)=>{if(J)X.setStatus({code:Ti.SpanStatusCode.ERROR,message:J.message}),X.recordException(J);X.end()}),delete Z[v3]}function Ni(Z,J,$){let X,Y=void 0;try{if(Y=Z(),Ai(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){X=Q}finally{if(!Ai(Y)){if(J(X,Y),X)throw X}return Y}}function Ai(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var eh0="0.1.0",Zf0="@sentry/instrumentation-fastify-v3",Ri="anonymous",Jf0=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class QD extends ZJ.InstrumentationBase{constructor(Z={}){super(Zf0,eh0,Z)}init(){return[new ZJ.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=lz.getRPCMetadata(d8.context.active()),K=Q.routeOptions?Q.routeOptions.url:$.routerPath;if(K&&W?.type===lz.RPCType.HTTP)W.route=K;let z=$.method||"GET";x0().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||Ri,K=`${x3.MIDDLEWARE} - ${W}`,z=Q[1],G=YD(z,Y.tracer,K,{[H9.FASTIFY_TYPE]:k3.MIDDLEWARE,[H9.PLUGIN_NAME]:Z,[H9.HOOK_NAME]:J}),H=X&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){cz(z),H.apply(this,V)};return d8.context.with(d8.trace.setSpan(d8.context.active(),G),()=>{return Ni(()=>{return $.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:d8.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!X)cz(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(!Jf0.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()),$f0(),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 ZJ.safeExecuteInTheMiddle(()=>{return $.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;cz(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=`${x3.REQUEST_HANDLER} - ${K||this.pluginName||Ri}`,G={[H9.PLUGIN_NAME]:this.pluginName,[H9.FASTIFY_TYPE]:k3.REQUEST_HANDLER,[qi.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:$.routerPath};if(K)G[H9.FASTIFY_NAME]=K;let H=YD(X,Z.tracer,z,G);Ci(H);let{requestHook:V}=Z.getConfig();if(V)ZJ.safeExecuteInTheMiddle(()=>V(H,{request:$}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return d8.context.with(d8.trace.setSpan(d8.context.active(),H),()=>{Y()})}}}function $f0(){let Z=p();if(Z)Z.on("spanStart",(J)=>{Ci(J)})}function Ci(Z){let J=$0(Z).data,$=J["fastify.type"];if(J[V0]||!$)return;Z.setAttributes({[Q0]:"auto.http.otel.fastify",[V0]:`${$}.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 pz="Fastify",Pi=s(`${pz}.v3`,()=>new QD);function Xf0(){let Z=p();if(!Z)return;else return Z.getIntegrationByName(pz)}function Ei(Z,J,$,X){let Y=Xf0()?.getShouldHandleError()||yi;if(X==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&X==="onError-hook"){k1&&A.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,$))L0(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var Ii=s(`${pz}.v5`,()=>{let Z=new XD,J=Z.plugin();return WD.subscribe("fastify.initialization",($)=>{let X=$.fastify;X?.register(J).after((Y)=>{if(Y)k1&&A.error("Failed to setup Fastify instrumentation",Y);else if(Qf0(),X)Wf0(X)})}),WD.subscribe("tracing:fastify.request.handler:error",($)=>{let{error:X,request:Y,reply:Q}=$;Ei.call(Ei,X,Y,Q,"diagnostics-channel")}),Z}),Yf0=({shouldHandleError:Z})=>{let J;return{name:pz,setupOnce(){J=Z||yi,Pi(),Ii()},getShouldHandleError(){return J},setShouldHandleError($){J=$}}},Si=k((Z={})=>Yf0(Z));function yi(Z,J,$){let X=$.statusCode;return X>=500||X<=299}function ki(Z){let J=$0(Z),$=J.description,X=J.data,Y=X["fastify.type"],Q=Y==="hook",W=Y===$?.startsWith("handler -"),K=$==="request"||Y==="request-handler";if(X[V0]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[Q0]:"auto.http.otel.fastify",[V0]:`${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 Qf0(){let Z=p();if(Z)Z.on("spanStart",(J)=>{ki(J)})}function Wf0(Z){Z.addHook("onRequest",async(J,$)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)ki(Q)}let X=J.routeOptions?.url,Y=J.method||"GET";x0().setTransactionName(`${Y} ${X}`)})}var Dn=v(m(),1),On=v(Ln(),1);var _n="Graphql",wn=s(_n,On.GraphQLInstrumentation,(Z)=>{let J=Mn(Z);return{...J,responseHook($,X){if(Z1($,"auto.graphql.otel.graphql"),X.errors?.length&&!$0($).status)$.setStatus({code:Dn.SpanStatusCode.ERROR});let Q=$0($).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=S1($),H=$0(z).data[b$]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute(b$,H);else if(typeof H==="string")z.setAttribute(b$,[H,V]);else z.setAttribute(b$,V);if(!$0(z).data["original-description"])z.setAttribute("original-description",$0(z).description);z.updateName(`${$0(z).data["original-description"]} (${hf0(H)})`)}}}}),vf0=(Z={})=>{return{name:_n,setupOnce(){wn(Mn(Z))}}},jn=k(vf0);function Mn(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function hf0(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 ln=v(cn(),1);var pn="Kafka",nn=s(pn,()=>new ln.KafkaJsInstrumentation({consumerHook(Z){Z1(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){Z1(Z,"auto.kafkajs.otel.producer")}})),$b0=()=>{return{name:pn,setupOnce(){nn()}}},an=k($b0);var Wa=v(Qa(),1);var Ka="LruMemoizer",za=s(Ka,()=>new Wa.LruMemoizerInstrumentation),Wb0=()=>{return{name:Ka,setupOnce(){za()}}},Ga=k(Wb0);var qa=v(Ra(),1);var Ca="Mongo",Ea=s(Ca,()=>new qa.MongoDBInstrumentation({dbStatementSerializer:Ab0,responseHook(Z){Z1(Z,"auto.db.otel.mongo")}}));function Ab0(Z){let J=wD(Z);return JSON.stringify(J)}function wD(Z){if(Array.isArray(Z))return Z.map((J)=>wD(J));if(Tb0(Z)){let J={};return Object.entries(Z).map(([$,X])=>[$,wD(X)]).reduce(($,X)=>{if(Rb0(X))$[X[0]]=X[1];return $},J)}return"?"}function Tb0(Z){return typeof Z==="object"&&Z!==null&&!Nb0(Z)}function Nb0(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function Rb0(Z){return Array.isArray(Z)}var qb0=()=>{return{name:Ca,setupOnce(){Ea()}}},Pa=k(qb0);var oa=v(aa(),1);var ra="Mongoose",sa=s(ra,()=>new oa.MongooseInstrumentation({responseHook(Z){Z1(Z,"auto.db.otel.mongoose")}})),nb0=()=>{return{name:ra,setupOnce(){sa()}}},ta=k(nb0);var Lo=v(Uo(),1);var Do="Mysql",Oo=s(Do,()=>new Lo.MySQLInstrumentation({})),_g0=()=>{return{name:Do,setupOnce(){Oo()}}},_o=k(_g0);var fo=v(ho(),1);var bo="Mysql2",go=s(bo,()=>new fo.MySQL2Instrumentation({responseHook(Z){Z1(Z,"auto.db.otel.mysql2")}})),ig0=()=>{return{name:bo,setupOnce(){go()}}},mo=k(ig0);var mr=v(Wr(),1),ur=v(vr(),1);var Em0=["get","set","setex"],uD=["get","mget"],Pm0=["set","setex"];function p3(Z,J){return Z.includes(J.toLowerCase())}function dD(Z){if(p3(uD,Z))return"cache.get";else if(p3(Pm0,Z))return"cache.put";else return}function Im0(Z,J){return J.some(($)=>Z.startsWith($))}function fr(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 hr(Y.map((Q)=>$(Q)));else return["<unknown>"]},X=J[0];if(p3(Em0,Z)&&X!=null)return $(X);return hr(J.map((Y)=>$(Y)))}catch{return}}function br(Z,J,$){if(!dD(Z))return!1;for(let X of J)if(Im0(X,$))return!0;return!1}function gr(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 hr(Z){let J=[],$=(X)=>{X.forEach((Y)=>{if(Array.isArray(Y))$(Y);else J.push(Y)})};return $(Z),J}var WG="Redis",i3={},dr=(Z,J,$,X)=>{Z.setAttribute(Q0,"auto.db.otel.redis");let Y=fr(J,$),Q=dD(J);if(!Y||!Q||!i3.cachePrefixes||!br(J,Y,i3.cachePrefixes))return;let W=$0(Z).data["net.peer.name"],K=$0(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=gr(X);if(z)Z.setAttribute(yU,z);if(p3(uD,J)&&z!==void 0)Z.setAttribute(IU,z>0);Z.setAttributes({[V0]:Q,[SU]:Y});let G=Y.join(", ");Z.updateName(i3.maxCacheKeyLength?J7(G,i3.maxCacheKeyLength):G)},Sm0=s(`${WG}.IORedis`,()=>{return new mr.IORedisInstrumentation({responseHook:dr})}),ym0=s(`${WG}.Redis`,()=>{return new ur.RedisInstrumentation({responseHook:dr})}),cr=Object.assign(()=>{Sm0(),ym0()},{id:WG}),km0=(Z={})=>{return{name:WG,setupOnce(){i3=Z,cr()}}},lr=k(km0);var js=v(ws(),1);var Ms="Postgres",As=s(Ms,()=>new js.PgInstrumentation({requireParentSpan:!0,requestHook(Z){Z1(Z,"auto.db.otel.postgres")}})),Ru0=()=>{return{name:Ms,setupOnce(){As()}}},Ts=k(Ru0);var QX=v(m(),1),U9=v(U0(),1),c1=v(e0(),1);var BG="PostgresJs",Ns=[">=3.0.0 <4"],qu0=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,FG=Symbol("sentryPostgresConnectionContext"),oD=Symbol.for("sentry.instrumented.postgresjs"),Rs=Symbol.for("sentry.query.from.instrumented.sql"),qs=s(BG,(Z)=>new Cs({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class Cs extends U9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",y0,Z)}init(){let Z=new U9.InstrumentationNodeModuleDefinition("postgres",Ns,(J)=>{try{return this._patchPostgres(J)}catch($){return k1&&A.error("Failed to patch postgres module:",$),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new U9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,Ns,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",$=J?Z:Z.default;if(typeof $!=="function")return k1&&A.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 k1&&A.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 X3(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=$[FG];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(c1.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(c1.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(c1.ATTR_SERVER_PORT,$)}}_setOperationName(Z,J,$){if($){Z.setAttribute(c1.ATTR_DB_OPERATION_NAME,$);return}let X=J?.match(qu0);if(X?.[1])Z.setAttribute(c1.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[FG]=W}_instrumentSqlInstance(Z,J){if(Z[oD])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[FG]=J;else this._attachConnectionContext(Z,X);return Z[oD]=!0,X[oD]=!0,X}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Rs]=!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 O4({name:K||"postgresjs.query",op:"db"},(z)=>{Z1(z,"auto.db.postgresjs"),z.setAttributes({[c1.ATTR_DB_SYSTEM_NAME]:"postgres",[c1.ATTR_DB_QUERY_TEXT]:K});let G=J?J[FG]:void 0;X._setConnectionAttributes(z,G);let H=X.getConfig(),{requestHook:V}=H;if(V)U9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),k1&&A.error(`Error in requestHook for ${BG} 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){k1&&A.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:C0,message:L?.[0]?.message||"unknown_error"}),z.setAttribute(c1.ATTR_DB_RESPONSE_STATUS_CODE,L?.[0]?.code||"unknown"),z.setAttribute(c1.ATTR_ERROR_TYPE,L?.[0]?.name||"unknown"),X._setOperationName(z,K),z.end()}catch(O){k1&&A.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:C0,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return QX.trace.getSpan(QX.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[Rs])return $.apply(this,X);if(!J._shouldCreateSpans())return $.apply(this,X);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return O4({name:Q||"postgresjs.query",op:"db"},(W)=>{Z1(W,"auto.db.postgresjs"),W.setAttributes({[c1.ATTR_DB_SYSTEM_NAME]:"postgres",[c1.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)U9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),k1&&A.error(`Error in requestHook for ${BG} 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){k1&&A.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:C0,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(c1.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(c1.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){k1&&A.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:C0,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 Cu0=(Z)=>{return{name:BG,setupOnce(){qs(Z)}}},Es=k(Cu0);var Q8=v(m(),1);var Ss=v(m(),1),UG=v(U0(),1),h7=v(m(),1);var Eu0=process.env.PRISMA_SHOW_ALL_TRACES==="true",Pu0="00-10-10-00";function Iu0(Z){switch(Z){case"client":return h7.SpanKind.CLIENT;case"internal":default:return h7.SpanKind.INTERNAL}}var Su0=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=h7.trace.getSpanContext(Z??h7.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return Pu0}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),$=new Map,X=Z.filter((Y)=>Y.parentId===null);for(let Y of X)ys(J,Y,Z,$,this.ignoreSpanTypes)}getActiveContext(){return h7.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!Eu0)return J();let $=this.tracerProvider.getTracer("prisma"),X=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(ks(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=$.startSpan(Y,Z,X);return Ps(Q,J(Q,X))}return $.startActiveSpan(Y,Z,(Q)=>Ps(Q,J(Q,X)))}};function ys(Z,J,$,X,Y){if(ks(J.name,Y))return;let Q={attributes:J.attributes,kind:Iu0(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)ys(Z,z,$,X,Y);W.end(J.endTime)})}function Ps(Z,J){if(yu0(J))return J.then(($)=>{return Z.end(),$},($)=>{throw Z.end(),$});return Z.end(),J}function yu0(Z){return Z!=null&&typeof Z.then==="function"}function ks(Z,J){return J.some(($)=>typeof $==="string"?$===Z:$.test(Z))}var xs={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},sD=xs.version,ku0=sD.split(".")[0],Is="PRISMA_INSTRUMENTATION",rD=`V${ku0}_PRISMA_INSTRUMENTATION`,xu0=xs.name,vu0="@prisma/client",vs=class extends UG.InstrumentationBase{tracerProvider;constructor(Z={}){super(xu0,sD,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new UG.InstrumentationNodeModuleDefinition(vu0,[sD])]}enable(){let Z=this._config,J={helper:new Su0({tracerProvider:this.tracerProvider??Ss.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[Is]=J,global[rD]=J}disable(){delete global[Is],delete global[rD]}isEnabled(){return Boolean(global[rD])}};var hs="Prisma";function hu0(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function fs(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class bs extends vs{constructor(){super()}enable(){super.enable();let Z=fs();if(hu0(Z))Z.createEngineSpan=(J)=>{let $=Q8.trace.getTracer("prismaV5Compatibility"),X=$._idGenerator;if(!X){m1(()=>{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=fu0(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:Q8.TraceFlags.SAMPLED}}}),H=Q8.trace.setSpanContext(Q8.context.active(),{traceId:z,spanId:W,traceFlags:Q8.TraceFlags.SAMPLED});Q8.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 fu0(Z){switch(Z){case"client":return Q8.SpanKind.CLIENT;case"internal":default:return Q8.SpanKind.INTERNAL}}var bu0=s(hs,(Z)=>{return new bs}),gs=k((Z)=>{return{name:hs,setupOnce(){bu0()},setup(J){if(!fs())return;J.on("spanStart",($)=>{let X=$0($);if(X.description?.startsWith("prisma:"))$.setAttribute(Q0,"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 Kt=v(Wt(),1);var zt="Hapi",Gt=s(zt,()=>new Kt.HapiInstrumentation),zd0=()=>{return{name:zt,setupOnce(){Gt()}}},Ht=k(zd0);var OG=v(e0(),1);var b7={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},s3={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var XJ=v(m(),1),DG=v(U0(),1);var Gd0="@sentry/instrumentation-hono",Hd0="0.0.1";class $O extends DG.InstrumentationBase{constructor(Z={}){super(Gd0,Hd0,Z)}init(){return[new DG.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 XJ.context.with(XJ.trace.setSpan(XJ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[$,X]);if(u4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[b7.HONO_TYPE]:z,[b7.HONO_NAME]:z===s3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[b7.HONO_TYPE]:K,[b7.HONO_NAME]:K===s3.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(u4(X))X.then(()=>J(),(Y)=>$(Y));else J();return X}catch(X){throw $(X),X}}_determineHandlerType(Z){return Z===void 0?s3.MIDDLEWARE:s3.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:XJ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var Vt="Hono";function Vd0(Z){let J=$0(Z).data,$=J[b7.HONO_TYPE];if(J[V0]||!$)return;Z.setAttributes({[Q0]:"auto.http.otel.hono",[V0]:`${$}.hono`});let X=J[b7.HONO_NAME];if(typeof X==="string")Z.updateName(X);if(x0()===A6()){k1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[OG.ATTR_HTTP_ROUTE],Q=J[OG.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")x0().setTransactionName(`${Q} ${Y}`)}var Ft=s(Vt,()=>new $O({responseHook:(Z)=>{Vd0(Z)}})),Fd0=()=>{return{name:Vt,setupOnce(){Ft()}}},Bt=k(Fd0);var ht=v(vt(),1),ft=v(e0(),1);var bt="Koa",gt=s(bt,ht.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,$){Z1(J,"auto.http.otel.koa");let X=$0(J).data,Y=X["koa.type"];if(Y)J.setAttribute(V0,`${Y}.koa`);let Q=X["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(x0()===A6()){k1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=X[ft.ATTR_HTTP_ROUTE],K=$.context?.request?.method?.toUpperCase()||"GET";if(W)x0().setTransactionName(`${K} ${W}`)}}}),Nd0=(Z={})=>{return{name:bt,setupOnce(){gt(Z)}}},mt=k(Nd0);var Ke=v(We(),1);var ze="Connect",Ge=s(ze,()=>new Ke.ConnectInstrumentation),bd0=()=>{return{name:ze,setupOnce(){Ge()}}},He=k(bd0);var Ee=v(Ce(),1);var ed0=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),Pe="Tedious",Ie=s(Pe,()=>new Ee.TediousInstrumentation({})),Zc0=()=>{let Z;return{name:Pe,setupOnce(){let J=Ie();Z=A3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let{description:X,data:Y}=$0($);if(!X||Y["db.system"]!=="mssql")return;let Q=X.split(" ")[0]||"";if(ed0.has(Q))$.setAttribute(Q0,"auto.db.otel.tedious")}))}}},Se=k(Zc0);var ue=v(me(),1);var de="GenericPool",ce=s(de,()=>new ue.GenericPoolInstrumentation({})),Yc0=()=>{let Z;return{name:de,setupOnce(){let J=ce();Z=A3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let Y=$0($).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")$.setAttribute(Q0,"auto.db.otel.generic_pool")}))}}},le=k(Yc0);var U00=v(B00(),1);var L00="Amqplib",bc0={consumeEndHook:(Z)=>{Z1(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{Z1(Z,"auto.amqplib.otel.publisher")}},D00=s(L00,()=>new U00.AmqplibInstrumentation(bc0)),gc0=()=>{return{name:L00,setupOnce(){D00()}}},O00=k(gc0);var $Q="VercelAI";var qG=v(U0(),1);var mc0=[">=3.0.0 <7"],_00=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function uc0(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 dc0(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(uc0($)){let X=RL($.toolCallId);if(X){let Y=X.spanContext();W6((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"),L0($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),qL($.toolCallId)}else W6((Y)=>{Y.setTag("vercel.ai.tool.name",$.toolName),Y.setTag("vercel.ai.tool.callId",$.toolCallId),Y.setLevel("error"),L0($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function cc0(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 XQ extends qG.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",y0,Z);XQ.prototype.__init.call(this),XQ.prototype.__init2.call(this)}init(){return new qG.InstrumentationNodeModuleDefinition("ai",mc0,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($Q),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=cc0(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},T6(()=>Reflect.apply(X,Y,Q),(U)=>{if(U&&typeof U==="object")p1(U,"_sentry_active_span",z5())},()=>{},(U)=>{dc0(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let $ of _00)Z[$]=J(Z[$]);return Z}else{let $=_00.reduce((X,Y)=>{return X[Y]=J(Z[Y]),X},{});return{...Z,...$}}}}var w00=s($Q,()=>new XQ({}));function lc0(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var pc0=(Z={})=>{let J;return{name:$Q,options:Z,setupOnce(){J=w00()},afterAllSetup($){if(Z.force??lc0($))aK($);else J?.callWhenPatched(()=>aK($))}}},j00=k(pc0);var CG=v(U0(),1);var ic0=[">=4.0.0 <7"];class MO extends CG.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",y0,Z)}init(){return new CG.InstrumentationNodeModuleDefinition("openai",ic0,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(uZ(A7))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 sK(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 M00=s(A7,(Z)=>new MO(Z)),nc0=(Z={})=>{return{name:A7,setupOnce(){M00(Z)}}},A00=k(nc0);var EG=v(U0(),1);var ac0=[">=0.19.2 <1.0.0"];class AO extends EG.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",y0,Z)}init(){return new EG.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",ac0,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,$=this.getConfig(),X=function(...Y){if(uZ(T7))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 PL(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 T00=s(T7,(Z)=>new AO(Z)),oc0=(Z={})=>{return{name:T7,options:Z,setupOnce(){T00(Z)}}},N00=k(oc0);var HX=v(U0(),1);var R00=[">=0.10.0 <2"];class TO extends HX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",y0,Z)}init(){return new HX.InstrumentationNodeModuleDefinition("@google/genai",R00,(J)=>this._patch(J),(J)=>J,[new HX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",R00,(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(uZ(N7))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 kL(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 X3(Z,"GoogleGenAI",X),Z}}var q00=s(N7,(Z)=>new TO(Z)),rc0=(Z={})=>{return{name:N7,setupOnce(){q00(Z)}}},C00=k(rc0);var u7=v(U0(),1);var PG=[">=0.1.0 <2.0.0"];function sc0(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 tc0(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=sc0(z,J);return K.callbacks=G,Reflect.apply(X,Y,Q)}})}class NO extends u7.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",y0,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 u7.InstrumentationNodeModuleDefinition($,PG,this._patch.bind(this),(X)=>X,[new u7.InstrumentationNodeModuleFile(`${$}/dist/index.cjs`,PG,this._patch.bind(this),(X)=>X)]));return Z.push(new u7.InstrumentationNodeModuleDefinition("langchain",PG,this._patch.bind(this),($)=>$,[new u7.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",PG,this._patch.bind(this),($)=>$)])),Z}_patch(Z){QL([A7,T7,N7]);let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X?.recordInputs??$,Q=X?.recordOutputs??$,W=eK({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]=tc0(z,J)}}}var E00=s(tK,(Z)=>new NO(Z)),ec0=(Z={})=>{return{name:tK,setupOnce(){E00(Z)}}},P00=k(ec0);var VX=v(U0(),1);var I00=[">=0.0.0 <2.0.0"];class RO extends VX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",y0,Z)}init(){return new VX.InstrumentationNodeModuleDefinition("@langchain/langgraph",I00,this._patch.bind(this),(J)=>J,[new VX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",I00,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=hL(K.prototype.compile,W)}return Z}}var S00=s(Zz,(Z)=>new RO(Z)),Zl0=(Z={})=>{return{name:Zz,setupOnce(){S00(Z)}}},y00=k(Zl0);var m00=v(U0(),1);var D9=v(m(),1),O9=v(U0(),1),W8=v(e0(),1);import*as x00 from"net";function v00(Z,J,$,X,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{O9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;D9.diag.error(V?.message)},!0)};let z=new O9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>k00(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 O9.InstrumentationNodeModuleFile(H,J,(V)=>k00(V,$,X,Z,W),(V)=>h00(V,X)));return z}function k00(Z,J,$,X,Y){return h00(Z,$),J(Z,"addDoc",Jl0(X,Y)),J(Z,"getDocs",Xl0(X,Y)),J(Z,"setDoc",Yl0(X,Y)),J(Z,"deleteDoc",$l0(X,Y)),Z}function h00(Z,J){for(let $ of["addDoc","getDocs","setDoc","deleteDoc"])if(O9.isWrapped(Z[$]))J(Z,$);return Z}function Jl0(Z,J){return function(X){return function(Y,Q){let W=SG(Z,"addDoc",Y);return J(W),IG(W,()=>{return X(Y,Q)})}}}function $l0(Z,J){return function(X){return function(Y){let Q=SG(Z,"deleteDoc",Y.parent||Y);return J(Q),IG(Q,()=>{return X(Y)})}}}function Xl0(Z,J){return function(X){return function(Y){let Q=SG(Z,"getDocs",Y);return J(Q),IG(Q,()=>{return X(Y)})}}}function Yl0(Z,J){return function(X){return function(Y,Q,W){let K=SG(Z,"setDoc",Y.parent||Y);return J(K),IG(K,()=>{return typeof W<"u"?X(Y,Q,W):X(Y,Q)})}}}function IG(Z,J){return D9.context.with(D9.trace.setSpan(D9.context.active(),Z),()=>{return O9.safeExecuteInTheMiddle(()=>{return J()},($)=>{if($)Z.recordException($);Z.end()},!0)})}function SG(Z,J,$){let X=Z.startSpan(`${J} ${$.path}`,{kind:D9.SpanKind.CLIENT});return Wl0(X,$),X.setAttribute(W8.ATTR_DB_OPERATION_NAME,J),X}function Ql0(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(x00.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 Wl0(Z,J){let $=J.firestore.app,X=$.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[W8.ATTR_DB_COLLECTION_NAME]:J.path,[W8.ATTR_DB_NAMESPACE]:$.name,[W8.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}=Ql0(Q);if(K)W[W8.ATTR_SERVER_ADDRESS]=K;if(z)W[W8.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var w5=v(m(),1),_9=v(U0(),1);function f00(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)=>{_9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;w5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{_9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;w5.diag.error(B?.message)},!0)};let H=new _9.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 _9.InstrumentationNodeModuleFile(F,J,(U)=>Kl0(U,$,X,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>b00(U,X)))}),H}function a4(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:w5.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),w5.context.with(w5.trace.setSpan(w5.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 Kl0(Z,J,$,X,Y,Q){switch(b00(Z,$),Q){case"function":J(Z,"onRequest",a4(X,Y,"http.request")),J(Z,"onCall",a4(X,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",a4(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",a4(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",a4(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",a4(X,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",a4(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",a4(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",a4(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",a4(X,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",a4(X,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",a4(X,Y,"storage.object.finalized")),J(Z,"onObjectArchived",a4(X,Y,"storage.object.archived")),J(Z,"onObjectDeleted",a4(X,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",a4(X,Y,"storage.object.metadataUpdated"));break}return Z}function b00(Z,J){let $=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let X of $)if(_9.isWrapped(Z[X]))J(Z,X);return Z}var g00={},zl0=[">=3.0.0 <5"],Gl0=[">=6.0.0 <7"];class qO extends m00.InstrumentationBase{constructor(Z=g00){super("@sentry/instrumentation-firebase",y0,Z)}setConfig(Z={}){super.setConfig({...g00,...Z})}init(){let Z=[];return Z.push(v00(this.tracer,zl0,this._wrap,this._unwrap,this.getConfig())),Z.push(f00(this.tracer,Gl0,this._wrap,this._unwrap,this.getConfig())),Z}}var u00="Firebase",Hl0={firestoreSpanCreationHook:(Z)=>{Z1(Z,"auto.firebase.otel.firestore"),Z.setAttribute(V0,"db.query")},functions:{requestHook:(Z)=>{Z1(Z,"auto.firebase.otel.functions"),Z.setAttribute(V0,"http.request")},errorHook:async(Z,J)=>{if(J)L0(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await yK(2000)}}},d00=s(u00,()=>new qO(Hl0)),Vl0=()=>{return{name:u00,setupOnce(){d00()}}},c00=k(Vl0);function YQ(){return[lp(),Si(),jn(),Bt(),Pa(),ta(),_o(),mo(),lr(),Ts(),gs(),Ht(),mt(),He(),Se(),le(),an(),O00(),Ga(),P00(),y00(),j00(),A00(),N00(),C00(),Es(),c00()]}var FX=v(m(),1);var BX=v(e0(),1);var CO=1e6;function l00(Z,J={}){if(Z.getOptions().debug)x2();let[$,X]=Fl0(Z,J);Z.traceProvider=$,Z.asyncLocalStorageLookup=X}function Fl0(Z,J={}){let $=new Mz({sampler:new w2(Z),resource:z3().merge(Lz({[BX.ATTR_SERVICE_NAME]:"node",[BX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[BX.ATTR_SERVICE_VERSION]:y0})),forceFlushTimeoutMillis:500,spanProcessors:[new _2({timeout:Bl0(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});FX.trace.setGlobalTracerProvider($),FX.propagation.setGlobalPropagator(new O2);let X=new Ez;return FX.context.setGlobalContextManager(X),[$,X.getAsyncLocalStorageLookup()]}function Bl0(Z){if(Z==null)return;if(Z>CO)return k1&&A.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${CO}`),CO;else if(Z<=0||Number.isNaN(Z)){k1&&A.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function p00(){return kz().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(N3(),q3())}function i00(Z){return[...p00(),...A1(Z)?YQ():[]]}function EO(Z={}){return Ul0(Z,i00)}function Ul0(Z={},J){$9(Z,"node");let $=l2({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if($&&!Z.skipOpenTelemetrySetup)l00($,{spanProcessors:Z.openTelemetrySpanProcessors}),xz();return $}import*as s00 from"os";var Ll0="BunServer",Dl0=()=>{return{name:Ll0,setupOnce(){Ol0()}}},o00=k(Dl0),n00=!1;function Ol0(){if(n00)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,$){a00($[0]);let X=Z.apply(J,$),Y=X.reload.bind(X);return X.reload=(Q)=>{return a00(Q),Y(Q)},X}}),n00=!0}function a00(Z){_l0(Z),wl0(Z)}function _l0(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,$,X){return PO(J,$,X)}})}function wl0(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 PO(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 PO(Q,W,K,J)}})})})}function PO(Z,J,$,X){return IZ((Y)=>{let Q=$[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,$);let K=pY(Q.url),z=jl0(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[M1]="route",z["url.template"]=X,G=X}if(X?.endsWith("/*"))z[M1]="route",z["url.template"]=X,G=X;return Object.assign(z,O$(Q.headers.toJSON(),p()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),PK({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>q6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,$);if(V?.status)BK(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw L0(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function jl0(Z,J){let $={[Q0]:"auto.http.bun.serve",[kU]:J.method||"GET",[M1]:"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(!KL(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 r00(Z){function J($){let X={body:$.body,method:"POST",headers:Z.headers};try{return H7(()=>{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 mZ(Z,J)}function t00(Z){return[w$(),_$(),j$(),M$(),A$(),N3(),q3(),i$(),n$(),l$(),c$(),p$(),o00(),...A1(Z)?YQ():[]]}function IO(Z={}){$9(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||s00.hostname()};if(J.transport=J.transport||r00,J.defaultIntegrations===void 0)J.defaultIntegrations=t00(J);return EO(J)}IO({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as e00}from"fs";import{join as Z10}from"path";function A4(){return"3.1.0-beta.6"}function SO(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 w9(Z){let J=SO(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function QQ(Z,J){try{let $=SO(Z),X=SO(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 Al0}from"util";var Tl0={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 J10(){let Z=Al0({options:Tl0,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${A4()}`),process.exit(0);if(Z.values.help)Nl0(),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 Nl0(){console.log(`
53
+ >>> 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 Li(this.pattern,this.options)}parse(Z){P3(Z);let J=this.options;if(Z==="**")return e6;if(Z==="")return"";let $,X=null;if($=Z.match(yh0))X=J.dot?xh0:kh0;else if($=Z.match(Ah0))X=(J.nocase?J.dot?qh0:Rh0:J.dot?Nh0:Th0)($[1]);else if($=Z.match(vh0))X=(J.nocase?J.dot?fh0:hh0:J.dot?bh0:gh0)($);else if($=Z.match(Ch0))X=J.dot?Ph0:Eh0;else if($=Z.match(Ih0))X=Sh0;let Y=w4.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?dh0:J.dot?ch0:lh0,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"?oh0(G):G===e6?e6:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==e6||F===e6)return;if(F===void 0)if(V!==void 0&&V!==e6)z[H+1]="(?:\\/|"+$+"\\/)?"+V;else z[H]=$;else if(V===void 0)z[H-1]=F+"(?:\\/|"+$+")?";else if(V!==e6)z[H-1]=F+"(?:\\/|\\/"+$+"\\/)"+V,z[H+1]=e6}),z.filter((G)=>G!==e6).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 j4.defaults(Z).Minimatch}}j4.AST=w4;j4.Minimatch=S3;j4.escape=$D;j4.unescape=P7;var Oi="@fastify/otel",sh0="0.8.0",th0=">=4.0.0 <6",_i=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],H1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},I7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},G9="anonymous",p4=Symbol("fastify otel instance"),S7=Symbol("fastify otel request spans"),y3=Symbol("fastify otel request context"),wi=Symbol("fastify otel addhook original"),ji=Symbol("fastify otel setnotfound original"),uz=Symbol("fastify otel ignore path");class XD extends Mi.InstrumentationBase{constructor(Z){super(Oi,sh0,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[uz]=null,this._logger=d1.diag.createComponentLogger({namespace:Oi}),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 $=j4;this[uz]=(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)},Di.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)Di.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:th0,name:"@fastify/otel"},J;function J($,X,Y){$.decorate(p4,Z),$.decorate(wi,$.addHook),$.decorate(ji,$.setNotFoundHandler),$.decorateRequest("opentelemetry",function(){let V=this[y3];return{span:this[S7],tracer:Z.tracer,context:V,inject:(B,U)=>{return d1.propagation.inject(V,B,U)},extract:(B,U)=>{return d1.propagation.extract(V,B,U)}}}),$.decorateRequest(S7,null),$.decorateRequest(y3,null),$.addHook("onRoute",function(H){if(Z[uz]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of _i)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[H1.FASTIFY_TYPE]:I7.ROUTE,[o1.ATTR_HTTP_ROUTE]:H.url,[H1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:G9});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[H1.FASTIFY_TYPE]:I7.ROUTE,[o1.ATTR_HTTP_ROUTE]:H.url,[H1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:G9}));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,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - route-handler`,[H1.FASTIFY_TYPE]:I7.HANDLER,[o1.ATTR_HTTP_ROUTE]:H.url,[H1.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:G9})}),$.addHook("onRequest",function(H,V,F){if(this[p4].isEnabled()===!1)return F();else if(this[p4][uz]?.({url:H.url,method:H.method})===!0)return this[p4]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=d1.context.active();if(d1.trace.getSpan(B)==null)B=d1.propagation.extract(B,H.headers);let U=dz.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===dz.RPCType.HTTP)U.route=H.routeOptions.url;let L=this[p4].tracer.startSpan("request",{attributes:{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.ROOT]:"@fastify/otel",[o1.ATTR_HTTP_ROUTE]:H.url,[o1.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[y3]=d1.trace.setSpan(B,L),H[S7]=L,d1.context.with(H[y3],()=>{F()})}),$.addHook("onResponse",function(H,V,F){let B=H[S7];if(B!=null)B.setStatus({code:d1.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[o1.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[S7]=null,F()}),$.addHook=K,$.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[S7];if(U!=null){if(V.statusCode<500)U.setStatus({code:d1.SpanStatusCode.OK,message:"OK"});U.setAttributes({[o1.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[S7]=null,B(null,F)}function W(H,V,F,B){let U=H[S7];if(U!=null)U.setStatus({code:d1.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[wi];if(_i.includes(H))return F.call(this,H,G(V,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - ${H}`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:G9}));else return F.call(this,H,V)}function z(H,V){let F=this[ji];if(typeof H==="function")V=G(H,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:G9}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:G9});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:G9});V=G(V,{[o1.ATTR_SERVICE_NAME]:$[p4].servername,[H1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[H1.FASTIFY_TYPE]:I7.INSTANCE,[H1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:G9}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[p4],[L]=B;if(U.isEnabled()===!1)return H.call(this,...B);let O=L[y3]??d1.context.active(),_=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??G9}`,{attributes:V},O);return d1.context.with(d1.trace.setSpan(O,_),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((j)=>{return _.end(),j},(j)=>{return _.setStatus({code:d1.SpanStatusCode.ERROR,message:j.message}),_.recordException(j),_.end(),Promise.reject(j)});return _.end(),w}catch(w){throw _.setStatus({code:d1.SpanStatusCode.ERROR,message:w.message}),_.recordException(w),_.end(),w}},this)}}}}}var d8=v(m(),1),lz=v(_1(),1),ZJ=v(U0(),1),qi=v(e0(),1);var H9;(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})(H9||(H9={}));var k3;(function(Z){Z.MIDDLEWARE="middleware";let $="request_handler";Z.REQUEST_HANDLER=$})(k3||(k3={}));var x3;(function(Z){Z.MIDDLEWARE="middleware";let $="request handler";Z.REQUEST_HANDLER=$})(x3||(x3={}));var Ti=v(m(),1);var v3=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function YD(Z,J,$,X={}){let Y=J.startSpan($,{attributes:X}),Q=Z[v3]||[];return Q.push(Y),Object.defineProperty(Z,v3,{enumerable:!1,configurable:!0,value:Q}),Y}function cz(Z,J){let $=Z[v3]||[];if(!$.length)return;$.forEach((X)=>{if(J)X.setStatus({code:Ti.SpanStatusCode.ERROR,message:J.message}),X.recordException(J);X.end()}),delete Z[v3]}function Ni(Z,J,$){let X,Y=void 0;try{if(Y=Z(),Ai(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){X=Q}finally{if(!Ai(Y)){if(J(X,Y),X)throw X}return Y}}function Ai(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var eh0="0.1.0",Zf0="@sentry/instrumentation-fastify-v3",Ri="anonymous",Jf0=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class QD extends ZJ.InstrumentationBase{constructor(Z={}){super(Zf0,eh0,Z)}init(){return[new ZJ.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=lz.getRPCMetadata(d8.context.active()),K=Q.routeOptions?Q.routeOptions.url:$.routerPath;if(K&&W?.type===lz.RPCType.HTTP)W.route=K;let z=$.method||"GET";x0().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||Ri,K=`${x3.MIDDLEWARE} - ${W}`,z=Q[1],G=YD(z,Y.tracer,K,{[H9.FASTIFY_TYPE]:k3.MIDDLEWARE,[H9.PLUGIN_NAME]:Z,[H9.HOOK_NAME]:J}),H=X&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){cz(z),H.apply(this,V)};return d8.context.with(d8.trace.setSpan(d8.context.active(),G),()=>{return Ni(()=>{return $.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:d8.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!X)cz(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(!Jf0.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()),$f0(),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 ZJ.safeExecuteInTheMiddle(()=>{return $.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;cz(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=`${x3.REQUEST_HANDLER} - ${K||this.pluginName||Ri}`,G={[H9.PLUGIN_NAME]:this.pluginName,[H9.FASTIFY_TYPE]:k3.REQUEST_HANDLER,[qi.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:$.routerPath};if(K)G[H9.FASTIFY_NAME]=K;let H=YD(X,Z.tracer,z,G);Ci(H);let{requestHook:V}=Z.getConfig();if(V)ZJ.safeExecuteInTheMiddle(()=>V(H,{request:$}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return d8.context.with(d8.trace.setSpan(d8.context.active(),H),()=>{Y()})}}}function $f0(){let Z=p();if(Z)Z.on("spanStart",(J)=>{Ci(J)})}function Ci(Z){let J=$0(Z).data,$=J["fastify.type"];if(J[V0]||!$)return;Z.setAttributes({[Q0]:"auto.http.otel.fastify",[V0]:`${$}.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 pz="Fastify",Pi=s(`${pz}.v3`,()=>new QD);function Xf0(){let Z=p();if(!Z)return;else return Z.getIntegrationByName(pz)}function Ei(Z,J,$,X){let Y=Xf0()?.getShouldHandleError()||yi;if(X==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&X==="onError-hook"){k1&&A.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,$))L0(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var Ii=s(`${pz}.v5`,()=>{let Z=new XD,J=Z.plugin();return WD.subscribe("fastify.initialization",($)=>{let X=$.fastify;X?.register(J).after((Y)=>{if(Y)k1&&A.error("Failed to setup Fastify instrumentation",Y);else if(Qf0(),X)Wf0(X)})}),WD.subscribe("tracing:fastify.request.handler:error",($)=>{let{error:X,request:Y,reply:Q}=$;Ei.call(Ei,X,Y,Q,"diagnostics-channel")}),Z}),Yf0=({shouldHandleError:Z})=>{let J;return{name:pz,setupOnce(){J=Z||yi,Pi(),Ii()},getShouldHandleError(){return J},setShouldHandleError($){J=$}}},Si=k((Z={})=>Yf0(Z));function yi(Z,J,$){let X=$.statusCode;return X>=500||X<=299}function ki(Z){let J=$0(Z),$=J.description,X=J.data,Y=X["fastify.type"],Q=Y==="hook",W=Y===$?.startsWith("handler -"),K=$==="request"||Y==="request-handler";if(X[V0]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[Q0]:"auto.http.otel.fastify",[V0]:`${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 Qf0(){let Z=p();if(Z)Z.on("spanStart",(J)=>{ki(J)})}function Wf0(Z){Z.addHook("onRequest",async(J,$)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)ki(Q)}let X=J.routeOptions?.url,Y=J.method||"GET";x0().setTransactionName(`${Y} ${X}`)})}var Dn=v(m(),1),On=v(Ln(),1);var _n="Graphql",wn=s(_n,On.GraphQLInstrumentation,(Z)=>{let J=Mn(Z);return{...J,responseHook($,X){if(Z1($,"auto.graphql.otel.graphql"),X.errors?.length&&!$0($).status)$.setStatus({code:Dn.SpanStatusCode.ERROR});let Q=$0($).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=S1($),H=$0(z).data[b$]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute(b$,H);else if(typeof H==="string")z.setAttribute(b$,[H,V]);else z.setAttribute(b$,V);if(!$0(z).data["original-description"])z.setAttribute("original-description",$0(z).description);z.updateName(`${$0(z).data["original-description"]} (${hf0(H)})`)}}}}),vf0=(Z={})=>{return{name:_n,setupOnce(){wn(Mn(Z))}}},jn=k(vf0);function Mn(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function hf0(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 ln=v(cn(),1);var pn="Kafka",nn=s(pn,()=>new ln.KafkaJsInstrumentation({consumerHook(Z){Z1(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){Z1(Z,"auto.kafkajs.otel.producer")}})),$b0=()=>{return{name:pn,setupOnce(){nn()}}},an=k($b0);var Wa=v(Qa(),1);var Ka="LruMemoizer",za=s(Ka,()=>new Wa.LruMemoizerInstrumentation),Wb0=()=>{return{name:Ka,setupOnce(){za()}}},Ga=k(Wb0);var qa=v(Ra(),1);var Ca="Mongo",Ea=s(Ca,()=>new qa.MongoDBInstrumentation({dbStatementSerializer:Ab0,responseHook(Z){Z1(Z,"auto.db.otel.mongo")}}));function Ab0(Z){let J=wD(Z);return JSON.stringify(J)}function wD(Z){if(Array.isArray(Z))return Z.map((J)=>wD(J));if(Tb0(Z)){let J={};return Object.entries(Z).map(([$,X])=>[$,wD(X)]).reduce(($,X)=>{if(Rb0(X))$[X[0]]=X[1];return $},J)}return"?"}function Tb0(Z){return typeof Z==="object"&&Z!==null&&!Nb0(Z)}function Nb0(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function Rb0(Z){return Array.isArray(Z)}var qb0=()=>{return{name:Ca,setupOnce(){Ea()}}},Pa=k(qb0);var oa=v(aa(),1);var ra="Mongoose",sa=s(ra,()=>new oa.MongooseInstrumentation({responseHook(Z){Z1(Z,"auto.db.otel.mongoose")}})),nb0=()=>{return{name:ra,setupOnce(){sa()}}},ta=k(nb0);var Lo=v(Uo(),1);var Do="Mysql",Oo=s(Do,()=>new Lo.MySQLInstrumentation({})),_g0=()=>{return{name:Do,setupOnce(){Oo()}}},_o=k(_g0);var fo=v(ho(),1);var bo="Mysql2",go=s(bo,()=>new fo.MySQL2Instrumentation({responseHook(Z){Z1(Z,"auto.db.otel.mysql2")}})),ig0=()=>{return{name:bo,setupOnce(){go()}}},mo=k(ig0);var mr=v(Wr(),1),ur=v(vr(),1);var Em0=["get","set","setex"],uD=["get","mget"],Pm0=["set","setex"];function p3(Z,J){return Z.includes(J.toLowerCase())}function dD(Z){if(p3(uD,Z))return"cache.get";else if(p3(Pm0,Z))return"cache.put";else return}function Im0(Z,J){return J.some(($)=>Z.startsWith($))}function fr(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 hr(Y.map((Q)=>$(Q)));else return["<unknown>"]},X=J[0];if(p3(Em0,Z)&&X!=null)return $(X);return hr(J.map((Y)=>$(Y)))}catch{return}}function br(Z,J,$){if(!dD(Z))return!1;for(let X of J)if(Im0(X,$))return!0;return!1}function gr(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 hr(Z){let J=[],$=(X)=>{X.forEach((Y)=>{if(Array.isArray(Y))$(Y);else J.push(Y)})};return $(Z),J}var WG="Redis",i3={},dr=(Z,J,$,X)=>{Z.setAttribute(Q0,"auto.db.otel.redis");let Y=fr(J,$),Q=dD(J);if(!Y||!Q||!i3.cachePrefixes||!br(J,Y,i3.cachePrefixes))return;let W=$0(Z).data["net.peer.name"],K=$0(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=gr(X);if(z)Z.setAttribute(yU,z);if(p3(uD,J)&&z!==void 0)Z.setAttribute(IU,z>0);Z.setAttributes({[V0]:Q,[SU]:Y});let G=Y.join(", ");Z.updateName(i3.maxCacheKeyLength?J7(G,i3.maxCacheKeyLength):G)},Sm0=s(`${WG}.IORedis`,()=>{return new mr.IORedisInstrumentation({responseHook:dr})}),ym0=s(`${WG}.Redis`,()=>{return new ur.RedisInstrumentation({responseHook:dr})}),cr=Object.assign(()=>{Sm0(),ym0()},{id:WG}),km0=(Z={})=>{return{name:WG,setupOnce(){i3=Z,cr()}}},lr=k(km0);var js=v(ws(),1);var Ms="Postgres",As=s(Ms,()=>new js.PgInstrumentation({requireParentSpan:!0,requestHook(Z){Z1(Z,"auto.db.otel.postgres")}})),Ru0=()=>{return{name:Ms,setupOnce(){As()}}},Ts=k(Ru0);var QX=v(m(),1),U9=v(U0(),1),c1=v(e0(),1);var BG="PostgresJs",Ns=[">=3.0.0 <4"],qu0=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,FG=Symbol("sentryPostgresConnectionContext"),oD=Symbol.for("sentry.instrumented.postgresjs"),Rs=Symbol.for("sentry.query.from.instrumented.sql"),qs=s(BG,(Z)=>new Cs({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class Cs extends U9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",y0,Z)}init(){let Z=new U9.InstrumentationNodeModuleDefinition("postgres",Ns,(J)=>{try{return this._patchPostgres(J)}catch($){return k1&&A.error("Failed to patch postgres module:",$),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new U9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,Ns,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",$=J?Z:Z.default;if(typeof $!=="function")return k1&&A.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 k1&&A.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 X3(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=$[FG];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(c1.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(c1.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(c1.ATTR_SERVER_PORT,$)}}_setOperationName(Z,J,$){if($){Z.setAttribute(c1.ATTR_DB_OPERATION_NAME,$);return}let X=J?.match(qu0);if(X?.[1])Z.setAttribute(c1.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[FG]=W}_instrumentSqlInstance(Z,J){if(Z[oD])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[FG]=J;else this._attachConnectionContext(Z,X);return Z[oD]=!0,X[oD]=!0,X}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Rs]=!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 O4({name:K||"postgresjs.query",op:"db"},(z)=>{Z1(z,"auto.db.postgresjs"),z.setAttributes({[c1.ATTR_DB_SYSTEM_NAME]:"postgres",[c1.ATTR_DB_QUERY_TEXT]:K});let G=J?J[FG]:void 0;X._setConnectionAttributes(z,G);let H=X.getConfig(),{requestHook:V}=H;if(V)U9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),k1&&A.error(`Error in requestHook for ${BG} 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){k1&&A.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:C0,message:L?.[0]?.message||"unknown_error"}),z.setAttribute(c1.ATTR_DB_RESPONSE_STATUS_CODE,L?.[0]?.code||"unknown"),z.setAttribute(c1.ATTR_ERROR_TYPE,L?.[0]?.name||"unknown"),X._setOperationName(z,K),z.end()}catch(O){k1&&A.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:C0,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return QX.trace.getSpan(QX.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[Rs])return $.apply(this,X);if(!J._shouldCreateSpans())return $.apply(this,X);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return O4({name:Q||"postgresjs.query",op:"db"},(W)=>{Z1(W,"auto.db.postgresjs"),W.setAttributes({[c1.ATTR_DB_SYSTEM_NAME]:"postgres",[c1.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)U9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),k1&&A.error(`Error in requestHook for ${BG} 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){k1&&A.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:C0,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(c1.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(c1.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){k1&&A.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:C0,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 Cu0=(Z)=>{return{name:BG,setupOnce(){qs(Z)}}},Es=k(Cu0);var Q8=v(m(),1);var Ss=v(m(),1),UG=v(U0(),1),h7=v(m(),1);var Eu0=process.env.PRISMA_SHOW_ALL_TRACES==="true",Pu0="00-10-10-00";function Iu0(Z){switch(Z){case"client":return h7.SpanKind.CLIENT;case"internal":default:return h7.SpanKind.INTERNAL}}var Su0=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=h7.trace.getSpanContext(Z??h7.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return Pu0}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),$=new Map,X=Z.filter((Y)=>Y.parentId===null);for(let Y of X)ys(J,Y,Z,$,this.ignoreSpanTypes)}getActiveContext(){return h7.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!Eu0)return J();let $=this.tracerProvider.getTracer("prisma"),X=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(ks(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=$.startSpan(Y,Z,X);return Ps(Q,J(Q,X))}return $.startActiveSpan(Y,Z,(Q)=>Ps(Q,J(Q,X)))}};function ys(Z,J,$,X,Y){if(ks(J.name,Y))return;let Q={attributes:J.attributes,kind:Iu0(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)ys(Z,z,$,X,Y);W.end(J.endTime)})}function Ps(Z,J){if(yu0(J))return J.then(($)=>{return Z.end(),$},($)=>{throw Z.end(),$});return Z.end(),J}function yu0(Z){return Z!=null&&typeof Z.then==="function"}function ks(Z,J){return J.some(($)=>typeof $==="string"?$===Z:$.test(Z))}var xs={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},sD=xs.version,ku0=sD.split(".")[0],Is="PRISMA_INSTRUMENTATION",rD=`V${ku0}_PRISMA_INSTRUMENTATION`,xu0=xs.name,vu0="@prisma/client",vs=class extends UG.InstrumentationBase{tracerProvider;constructor(Z={}){super(xu0,sD,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new UG.InstrumentationNodeModuleDefinition(vu0,[sD])]}enable(){let Z=this._config,J={helper:new Su0({tracerProvider:this.tracerProvider??Ss.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[Is]=J,global[rD]=J}disable(){delete global[Is],delete global[rD]}isEnabled(){return Boolean(global[rD])}};var hs="Prisma";function hu0(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function fs(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class bs extends vs{constructor(){super()}enable(){super.enable();let Z=fs();if(hu0(Z))Z.createEngineSpan=(J)=>{let $=Q8.trace.getTracer("prismaV5Compatibility"),X=$._idGenerator;if(!X){m1(()=>{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=fu0(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:Q8.TraceFlags.SAMPLED}}}),H=Q8.trace.setSpanContext(Q8.context.active(),{traceId:z,spanId:W,traceFlags:Q8.TraceFlags.SAMPLED});Q8.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 fu0(Z){switch(Z){case"client":return Q8.SpanKind.CLIENT;case"internal":default:return Q8.SpanKind.INTERNAL}}var bu0=s(hs,(Z)=>{return new bs}),gs=k((Z)=>{return{name:hs,setupOnce(){bu0()},setup(J){if(!fs())return;J.on("spanStart",($)=>{let X=$0($);if(X.description?.startsWith("prisma:"))$.setAttribute(Q0,"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 Kt=v(Wt(),1);var zt="Hapi",Gt=s(zt,()=>new Kt.HapiInstrumentation),zd0=()=>{return{name:zt,setupOnce(){Gt()}}},Ht=k(zd0);var OG=v(e0(),1);var b7={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},s3={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var XJ=v(m(),1),DG=v(U0(),1);var Gd0="@sentry/instrumentation-hono",Hd0="0.0.1";class $O extends DG.InstrumentationBase{constructor(Z={}){super(Gd0,Hd0,Z)}init(){return[new DG.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 XJ.context.with(XJ.trace.setSpan(XJ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[$,X]);if(u4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[b7.HONO_TYPE]:z,[b7.HONO_NAME]:z===s3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[b7.HONO_TYPE]:K,[b7.HONO_NAME]:K===s3.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(u4(X))X.then(()=>J(),(Y)=>$(Y));else J();return X}catch(X){throw $(X),X}}_determineHandlerType(Z){return Z===void 0?s3.MIDDLEWARE:s3.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:XJ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var Vt="Hono";function Vd0(Z){let J=$0(Z).data,$=J[b7.HONO_TYPE];if(J[V0]||!$)return;Z.setAttributes({[Q0]:"auto.http.otel.hono",[V0]:`${$}.hono`});let X=J[b7.HONO_NAME];if(typeof X==="string")Z.updateName(X);if(x0()===A6()){k1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[OG.ATTR_HTTP_ROUTE],Q=J[OG.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")x0().setTransactionName(`${Q} ${Y}`)}var Ft=s(Vt,()=>new $O({responseHook:(Z)=>{Vd0(Z)}})),Fd0=()=>{return{name:Vt,setupOnce(){Ft()}}},Bt=k(Fd0);var ht=v(vt(),1),ft=v(e0(),1);var bt="Koa",gt=s(bt,ht.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,$){Z1(J,"auto.http.otel.koa");let X=$0(J).data,Y=X["koa.type"];if(Y)J.setAttribute(V0,`${Y}.koa`);let Q=X["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(x0()===A6()){k1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=X[ft.ATTR_HTTP_ROUTE],K=$.context?.request?.method?.toUpperCase()||"GET";if(W)x0().setTransactionName(`${K} ${W}`)}}}),Nd0=(Z={})=>{return{name:bt,setupOnce(){gt(Z)}}},mt=k(Nd0);var Ke=v(We(),1);var ze="Connect",Ge=s(ze,()=>new Ke.ConnectInstrumentation),bd0=()=>{return{name:ze,setupOnce(){Ge()}}},He=k(bd0);var Ee=v(Ce(),1);var ed0=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),Pe="Tedious",Ie=s(Pe,()=>new Ee.TediousInstrumentation({})),Zc0=()=>{let Z;return{name:Pe,setupOnce(){let J=Ie();Z=A3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let{description:X,data:Y}=$0($);if(!X||Y["db.system"]!=="mssql")return;let Q=X.split(" ")[0]||"";if(ed0.has(Q))$.setAttribute(Q0,"auto.db.otel.tedious")}))}}},Se=k(Zc0);var ue=v(me(),1);var de="GenericPool",ce=s(de,()=>new ue.GenericPoolInstrumentation({})),Yc0=()=>{let Z;return{name:de,setupOnce(){let J=ce();Z=A3(J)},setup(J){Z?.(()=>J.on("spanStart",($)=>{let Y=$0($).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")$.setAttribute(Q0,"auto.db.otel.generic_pool")}))}}},le=k(Yc0);var U00=v(B00(),1);var L00="Amqplib",bc0={consumeEndHook:(Z)=>{Z1(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{Z1(Z,"auto.amqplib.otel.publisher")}},D00=s(L00,()=>new U00.AmqplibInstrumentation(bc0)),gc0=()=>{return{name:L00,setupOnce(){D00()}}},O00=k(gc0);var $Q="VercelAI";var qG=v(U0(),1);var mc0=[">=3.0.0 <7"],_00=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function uc0(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 dc0(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(uc0($)){let X=RL($.toolCallId);if(X){let Y=X.spanContext();W6((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"),L0($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),qL($.toolCallId)}else W6((Y)=>{Y.setTag("vercel.ai.tool.name",$.toolName),Y.setTag("vercel.ai.tool.callId",$.toolCallId),Y.setLevel("error"),L0($.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function cc0(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 XQ extends qG.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",y0,Z);XQ.prototype.__init.call(this),XQ.prototype.__init2.call(this)}init(){return new qG.InstrumentationNodeModuleDefinition("ai",mc0,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($Q),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=cc0(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},T6(()=>Reflect.apply(X,Y,Q),(U)=>{if(U&&typeof U==="object")p1(U,"_sentry_active_span",z5())},()=>{},(U)=>{dc0(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let $ of _00)Z[$]=J(Z[$]);return Z}else{let $=_00.reduce((X,Y)=>{return X[Y]=J(Z[Y]),X},{});return{...Z,...$}}}}var w00=s($Q,()=>new XQ({}));function lc0(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var pc0=(Z={})=>{let J;return{name:$Q,options:Z,setupOnce(){J=w00()},afterAllSetup($){if(Z.force??lc0($))aK($);else J?.callWhenPatched(()=>aK($))}}},j00=k(pc0);var CG=v(U0(),1);var ic0=[">=4.0.0 <7"];class MO extends CG.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",y0,Z)}init(){return new CG.InstrumentationNodeModuleDefinition("openai",ic0,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(uZ(A7))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 sK(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 M00=s(A7,(Z)=>new MO(Z)),nc0=(Z={})=>{return{name:A7,setupOnce(){M00(Z)}}},A00=k(nc0);var EG=v(U0(),1);var ac0=[">=0.19.2 <1.0.0"];class AO extends EG.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",y0,Z)}init(){return new EG.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",ac0,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,$=this.getConfig(),X=function(...Y){if(uZ(T7))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 PL(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 T00=s(T7,(Z)=>new AO(Z)),oc0=(Z={})=>{return{name:T7,options:Z,setupOnce(){T00(Z)}}},N00=k(oc0);var HX=v(U0(),1);var R00=[">=0.10.0 <2"];class TO extends HX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",y0,Z)}init(){return new HX.InstrumentationNodeModuleDefinition("@google/genai",R00,(J)=>this._patch(J),(J)=>J,[new HX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",R00,(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(uZ(N7))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 kL(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 X3(Z,"GoogleGenAI",X),Z}}var q00=s(N7,(Z)=>new TO(Z)),rc0=(Z={})=>{return{name:N7,setupOnce(){q00(Z)}}},C00=k(rc0);var u7=v(U0(),1);var PG=[">=0.1.0 <2.0.0"];function sc0(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 tc0(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=sc0(z,J);return K.callbacks=G,Reflect.apply(X,Y,Q)}})}class NO extends u7.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",y0,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 u7.InstrumentationNodeModuleDefinition($,PG,this._patch.bind(this),(X)=>X,[new u7.InstrumentationNodeModuleFile(`${$}/dist/index.cjs`,PG,this._patch.bind(this),(X)=>X)]));return Z.push(new u7.InstrumentationNodeModuleDefinition("langchain",PG,this._patch.bind(this),($)=>$,[new u7.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",PG,this._patch.bind(this),($)=>$)])),Z}_patch(Z){QL([A7,T7,N7]);let J=p(),$=Boolean(J?.getOptions().sendDefaultPii),X=this.getConfig(),Y=X?.recordInputs??$,Q=X?.recordOutputs??$,W=eK({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]=tc0(z,J)}}}var E00=s(tK,(Z)=>new NO(Z)),ec0=(Z={})=>{return{name:tK,setupOnce(){E00(Z)}}},P00=k(ec0);var VX=v(U0(),1);var I00=[">=0.0.0 <2.0.0"];class RO extends VX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",y0,Z)}init(){return new VX.InstrumentationNodeModuleDefinition("@langchain/langgraph",I00,this._patch.bind(this),(J)=>J,[new VX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",I00,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=hL(K.prototype.compile,W)}return Z}}var S00=s(Zz,(Z)=>new RO(Z)),Zl0=(Z={})=>{return{name:Zz,setupOnce(){S00(Z)}}},y00=k(Zl0);var m00=v(U0(),1);var D9=v(m(),1),O9=v(U0(),1),W8=v(e0(),1);import*as x00 from"net";function v00(Z,J,$,X,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{O9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;D9.diag.error(V?.message)},!0)};let z=new O9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>k00(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 O9.InstrumentationNodeModuleFile(H,J,(V)=>k00(V,$,X,Z,W),(V)=>h00(V,X)));return z}function k00(Z,J,$,X,Y){return h00(Z,$),J(Z,"addDoc",Jl0(X,Y)),J(Z,"getDocs",Xl0(X,Y)),J(Z,"setDoc",Yl0(X,Y)),J(Z,"deleteDoc",$l0(X,Y)),Z}function h00(Z,J){for(let $ of["addDoc","getDocs","setDoc","deleteDoc"])if(O9.isWrapped(Z[$]))J(Z,$);return Z}function Jl0(Z,J){return function(X){return function(Y,Q){let W=SG(Z,"addDoc",Y);return J(W),IG(W,()=>{return X(Y,Q)})}}}function $l0(Z,J){return function(X){return function(Y){let Q=SG(Z,"deleteDoc",Y.parent||Y);return J(Q),IG(Q,()=>{return X(Y)})}}}function Xl0(Z,J){return function(X){return function(Y){let Q=SG(Z,"getDocs",Y);return J(Q),IG(Q,()=>{return X(Y)})}}}function Yl0(Z,J){return function(X){return function(Y,Q,W){let K=SG(Z,"setDoc",Y.parent||Y);return J(K),IG(K,()=>{return typeof W<"u"?X(Y,Q,W):X(Y,Q)})}}}function IG(Z,J){return D9.context.with(D9.trace.setSpan(D9.context.active(),Z),()=>{return O9.safeExecuteInTheMiddle(()=>{return J()},($)=>{if($)Z.recordException($);Z.end()},!0)})}function SG(Z,J,$){let X=Z.startSpan(`${J} ${$.path}`,{kind:D9.SpanKind.CLIENT});return Wl0(X,$),X.setAttribute(W8.ATTR_DB_OPERATION_NAME,J),X}function Ql0(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(x00.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 Wl0(Z,J){let $=J.firestore.app,X=$.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[W8.ATTR_DB_COLLECTION_NAME]:J.path,[W8.ATTR_DB_NAMESPACE]:$.name,[W8.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}=Ql0(Q);if(K)W[W8.ATTR_SERVER_ADDRESS]=K;if(z)W[W8.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var w5=v(m(),1),_9=v(U0(),1);function f00(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)=>{_9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;w5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{_9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;w5.diag.error(B?.message)},!0)};let H=new _9.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 _9.InstrumentationNodeModuleFile(F,J,(U)=>Kl0(U,$,X,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>b00(U,X)))}),H}function a4(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:w5.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),w5.context.with(w5.trace.setSpan(w5.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 Kl0(Z,J,$,X,Y,Q){switch(b00(Z,$),Q){case"function":J(Z,"onRequest",a4(X,Y,"http.request")),J(Z,"onCall",a4(X,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",a4(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",a4(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",a4(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",a4(X,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",a4(X,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",a4(X,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",a4(X,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",a4(X,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",a4(X,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",a4(X,Y,"storage.object.finalized")),J(Z,"onObjectArchived",a4(X,Y,"storage.object.archived")),J(Z,"onObjectDeleted",a4(X,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",a4(X,Y,"storage.object.metadataUpdated"));break}return Z}function b00(Z,J){let $=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let X of $)if(_9.isWrapped(Z[X]))J(Z,X);return Z}var g00={},zl0=[">=3.0.0 <5"],Gl0=[">=6.0.0 <7"];class qO extends m00.InstrumentationBase{constructor(Z=g00){super("@sentry/instrumentation-firebase",y0,Z)}setConfig(Z={}){super.setConfig({...g00,...Z})}init(){let Z=[];return Z.push(v00(this.tracer,zl0,this._wrap,this._unwrap,this.getConfig())),Z.push(f00(this.tracer,Gl0,this._wrap,this._unwrap,this.getConfig())),Z}}var u00="Firebase",Hl0={firestoreSpanCreationHook:(Z)=>{Z1(Z,"auto.firebase.otel.firestore"),Z.setAttribute(V0,"db.query")},functions:{requestHook:(Z)=>{Z1(Z,"auto.firebase.otel.functions"),Z.setAttribute(V0,"http.request")},errorHook:async(Z,J)=>{if(J)L0(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await yK(2000)}}},d00=s(u00,()=>new qO(Hl0)),Vl0=()=>{return{name:u00,setupOnce(){d00()}}},c00=k(Vl0);function YQ(){return[lp(),Si(),jn(),Bt(),Pa(),ta(),_o(),mo(),lr(),Ts(),gs(),Ht(),mt(),He(),Se(),le(),an(),O00(),Ga(),P00(),y00(),j00(),A00(),N00(),C00(),Es(),c00()]}var FX=v(m(),1);var BX=v(e0(),1);var CO=1e6;function l00(Z,J={}){if(Z.getOptions().debug)x2();let[$,X]=Fl0(Z,J);Z.traceProvider=$,Z.asyncLocalStorageLookup=X}function Fl0(Z,J={}){let $=new Mz({sampler:new w2(Z),resource:z3().merge(Lz({[BX.ATTR_SERVICE_NAME]:"node",[BX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[BX.ATTR_SERVICE_VERSION]:y0})),forceFlushTimeoutMillis:500,spanProcessors:[new _2({timeout:Bl0(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});FX.trace.setGlobalTracerProvider($),FX.propagation.setGlobalPropagator(new O2);let X=new Ez;return FX.context.setGlobalContextManager(X),[$,X.getAsyncLocalStorageLookup()]}function Bl0(Z){if(Z==null)return;if(Z>CO)return k1&&A.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${CO}`),CO;else if(Z<=0||Number.isNaN(Z)){k1&&A.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function p00(){return kz().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(N3(),q3())}function i00(Z){return[...p00(),...A1(Z)?YQ():[]]}function EO(Z={}){return Ul0(Z,i00)}function Ul0(Z={},J){$9(Z,"node");let $=l2({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if($&&!Z.skipOpenTelemetrySetup)l00($,{spanProcessors:Z.openTelemetrySpanProcessors}),xz();return $}import*as s00 from"os";var Ll0="BunServer",Dl0=()=>{return{name:Ll0,setupOnce(){Ol0()}}},o00=k(Dl0),n00=!1;function Ol0(){if(n00)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,$){a00($[0]);let X=Z.apply(J,$),Y=X.reload.bind(X);return X.reload=(Q)=>{return a00(Q),Y(Q)},X}}),n00=!0}function a00(Z){_l0(Z),wl0(Z)}function _l0(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,$,X){return PO(J,$,X)}})}function wl0(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 PO(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 PO(Q,W,K,J)}})})})}function PO(Z,J,$,X){return IZ((Y)=>{let Q=$[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,$);let K=pY(Q.url),z=jl0(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[M1]="route",z["url.template"]=X,G=X}if(X?.endsWith("/*"))z[M1]="route",z["url.template"]=X,G=X;return Object.assign(z,O$(Q.headers.toJSON(),p()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),PK({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>q6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,$);if(V?.status)BK(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw L0(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function jl0(Z,J){let $={[Q0]:"auto.http.bun.serve",[kU]:J.method||"GET",[M1]:"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(!KL(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 r00(Z){function J($){let X={body:$.body,method:"POST",headers:Z.headers};try{return H7(()=>{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 mZ(Z,J)}function t00(Z){return[w$(),_$(),j$(),M$(),A$(),N3(),q3(),i$(),n$(),l$(),c$(),p$(),o00(),...A1(Z)?YQ():[]]}function IO(Z={}){$9(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||s00.hostname()};if(J.transport=J.transport||r00,J.defaultIntegrations===void 0)J.defaultIntegrations=t00(J);return EO(J)}IO({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as e00}from"fs";import{join as Z10}from"path";function A4(){return"3.1.0-beta.7"}function SO(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 w9(Z){let J=SO(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function QQ(Z,J){try{let $=SO(Z),X=SO(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 Al0}from"util";var Tl0={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 J10(){let Z=Al0({options:Tl0,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${A4()}`),process.exit(0);if(Z.values.help)Nl0(),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 Nl0(){console.log(`
54
54
  Backend v2 - Clean modular architecture
55
55
 
56
56
  Usage:
@@ -2387,7 +2387,7 @@ ${z}`,H=Y.permissionMode||"acceptEdits";b.debug("[ClaudeAgent] Clear context req
2387
2387
  `);for(let H of G)if(H.startsWith("opencode server listening")){let V=H.match(/on\s+(https?:\/\/[^\s]+)/);if(!V)throw Error(`Failed to parse server url from output: ${H}`);clearTimeout(W),Y(V[1]);return}}),$.stderr?.on("data",(z)=>{K+=z.toString()}),$.on("exit",(z)=>{clearTimeout(W);let G=`Server exited with code ${z}`;if(K.trim())G+=`
2388
2388
  Server output: ${K}`;Q(Error(G))}),$.on("error",(z)=>{clearTimeout(W),Q(z)}),Z.signal)Z.signal.addEventListener("abort",()=>{clearTimeout(W),Q(Error("Aborted"))})}),close(){$.kill()}}}async function oW0(Z){let J=await aW0({...Z});return{client:fV({baseUrl:J.url}),server:J}}function rW0(Z){switch(Z){case"bypassPermissions":return[{permission:"*",pattern:"*",action:"allow"}];case"acceptEdits":return[{permission:"*",pattern:"*",action:"allow"},{permission:"bash",pattern:"*",action:"ask"}];case"plan":return[{permission:"*",pattern:"*",action:"ask"}];case"default":default:return[{permission:"*",pattern:"*",action:"ask"}]}}function NW(Z){let J=Z.indexOf("/");if(J>0)return{providerID:Z.substring(0,J),modelID:Z.substring(J+1)};return{providerID:"anthropic",modelID:Z}}var f0=y(),sW0={SYSTEM_PROMPT:3000,TOOLS_TOTAL:12000,AUTOCOMPACT_BUFFER:40000,CONTEXT_LIMIT_STANDARD:200000};class BM{sessions=new Map;tempSessions=new Map;userMessageIds=new Set;modelContextLimits=new Map;modelContextLimitsFetched=!1;server=null;serverInitPromise=null;config;callbacks;constructor(Z,J={}){this.config=Z,this.callbacks=J}async startServer(){if(this.server)return;if(this.serverInitPromise){await this.serverInitPromise;return}this.serverInitPromise=(async()=>{let $=[4097,4096,4098,4099,4100];for(let Y of $)try{let Q=`http://127.0.0.1:${Y}`;if((await fetch(`${Q}/health`,{signal:AbortSignal.timeout(1000)})).ok){f0.info(`[OpenCodeProcessManager] Reusing existing server at ${Q}`);let K=fV({baseUrl:Q}),z={url:Q,client:K,close:()=>{},directoryPath:process.cwd(),port:Y,sessionCount:0,createdAt:new Date,lastActivity:new Date};return this.startEventListener(z),this.server=z,await this.fetchModelContextLimits().catch(()=>{}),z}}catch{}f0.info("[OpenCodeProcessManager] Starting new server on port 4097"),await kQ(4097);let X=3;for(let Y=1;Y<=X;Y++)try{let{client:Q,server:W}=await oW0({hostname:"127.0.0.1",port:4097,timeout:30000}),K={url:W.url,client:Q,close:W.close,directoryPath:process.cwd(),port:4097,sessionCount:0,createdAt:new Date,lastActivity:new Date};return this.startEventListener(K),this.server=K,f0.info(`[OpenCodeProcessManager] Server started at ${W.url}`),await this.fetchModelContextLimits().catch(()=>{}),K}catch(Q){if(Q instanceof Error&&Q.message.includes("Failed to start server on port")&&Y<X){f0.warn(`[OpenCodeProcessManager] Spawn attempt ${Y}/${X} failed (port busy), retrying...`),await kQ(4097),await new Promise((K)=>setTimeout(K,Y*2000));continue}throw f0.error("[OpenCodeProcessManager] Failed to start server:",{port:4097,error:Q instanceof Error?Q.message:"Unknown error"}),this.serverInitPromise=null,Q}throw Error("Failed to start OpenCode server after all attempts")})(),await this.serverInitPromise,this.serverInitPromise=null}getClient(){return this.server?.client??null}async ensureServer(){if(this.server){if(!this.server.eventAbortController||this.server.eventAbortController.signal.aborted)f0.warn("[OpenCodeProcessManager] SSE event listener dead, reconnecting..."),this.startEventListener(this.server);return this.server}return await this.startServer(),this.server}async startEventListener(Z){let J=new AbortController;Z.eventAbortController=J,(async()=>{try{f0.info(`[OpenCodeProcessManager] Starting SSE event listener for ${Z.url} (global)`);let $=await Z.client.global.event();if(!$.stream){f0.error("[OpenCodeProcessManager] No SSE stream returned from server");return}f0.info("[OpenCodeProcessManager] SSE stream connected, listening for events");for await(let X of $.stream){if(J.signal.aborted)break;try{let Y=X?.payload||X;this.handleSSEEvent(Y,Z)}catch(Y){f0.error("[OpenCodeProcessManager] Error handling SSE event:",{type:X?.type||X?.payload?.type,error:Y instanceof Error?Y.message:"Unknown error"})}}if(f0.warn(`[OpenCodeProcessManager] SSE event loop exited (aborted=${J.signal.aborted})`),!J.signal.aborted)J.abort()}catch($){if(!J.signal.aborted)J.abort();f0.error("[OpenCodeProcessManager] SSE stream error:",{url:Z.url,error:$ instanceof Error?$.message:"Unknown error"})}})()}handleSSEEvent(Z,J){switch(Z.type){case"message.part.updated":this.handlePartUpdated(Z.properties.part,J);break;case"message.part.delta":break;case"message.updated":this.handleMessageUpdated(Z.properties.info,J);break;case"session.updated":this.handleSessionUpdated(Z.properties.info,J);break;case"session.created":this.handleSessionCreated(Z.properties.info,J);break;case"session.status":{let{sessionID:$,status:X}=Z.properties,Y=this.sessions.get($);if(!Y)break;if(X.type==="busy"){if(Y.status!=="processing")Y.status="processing",this.callbacks.onProcessingStarted?.(Y)}else if(X.type==="idle"){if(Y.status==="processing")Y.status="idle",this.callbacks.onProcessingComplete?.(Y)}break}case"session.idle":{let $=this.sessions.get(Z.properties.sessionID);if($&&$.status==="processing")$.status="idle",$.lastActivity=new Date,this.callbacks.onProcessingComplete?.($);this.userMessageIds.clear();break}case"session.error":{let $=Z.properties.sessionID;if(!$)break;let X=this.sessions.get($);if(!X)break;let Y=Z.properties.error,Q=Y?`${Y.name}: ${Y.data?.message||"Unknown error"}`:"Unknown session error";this.handleSessionError(X,Q);break}case"permission.asked":this.handlePermissionAsked(Z.properties,J);break;case"question.asked":this.handleQuestionAsked(Z.properties,J);break;default:break}}handlePartUpdated(Z,J){let $=this.sessions.get(Z.sessionID);if(!$||$.stopped)return;if(this.userMessageIds.has(Z.messageID))return;$.lastActivity=new Date;let X=this.translatePartToClaudeMessage(Z);if(X)this.callbacks.onAssistantMessage?.($,X)}handlePartDelta(Z,J){let $=this.sessions.get(Z.sessionID);if(!$||$.stopped)return;if(Z.field==="text"){let X={type:"assistant",message:{content:[{type:"text",text:Z.delta}]},_opencode_delta:!0,_opencode_partId:Z.partID,_opencode_messageId:Z.messageID};this.callbacks.onAssistantMessage?.($,X)}}translatePartToClaudeMessage(Z){switch(Z.type){case"text":{let J=Z;if(J.synthetic||J.ignored)return null;return{type:"assistant",content:J.text,message:{content:[{type:"text",text:J.text}]}}}case"tool":{let J=Z,$=J.state;if($.status==="pending"||$.status==="running")return{type:"assistant",message:{content:[{type:"tool_use",id:J.callID,name:J.tool,input:$.input,...$.status==="running"&&{_title:$.title}}]}};else if($.status==="completed")return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:J.callID,content:$.output,is_error:!1}]}};else if($.status==="error")return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:J.callID,content:$.error,is_error:!0}]}};return null}case"reasoning":return{type:"assistant",message:{content:[{type:"thinking",thinking:Z.text}]}};case"step-finish":{let J=Z,$=this.sessions.get(Z.sessionID);if($){let X=this.getModelContextLimit($.providerModel?.modelID),Y=this.calculateContextBreakdown(J.tokens,X);$.contextUsage=Y,this.callbacks.onContextUpdate?.($,Y)}return null}default:return null}}handleMessageUpdated(Z,J){if(Z.role==="user"&&Z.id){this.userMessageIds.add(Z.id);return}if(Z.role!=="assistant")return;let $=this.sessions.get(Z.sessionID);if(!$||$.stopped)return;if($.lastActivity=new Date,$.messageCount++,Z.tokens){let X=this.getModelContextLimit(Z.modelID),Y=this.calculateContextBreakdown(Z.tokens,X);$.contextUsage=Y,this.callbacks.onContextUpdate?.($,Y)}}handleSessionCreated(Z,J){for(let[$,X]of this.tempSessions)if(!X.sessionId){X.sessionId=Z.id,X.status="idle",X.title=Z.title,this.tempSessions.delete($),this.sessions.set(Z.id,X),this.callbacks.onSessionInitialized?.(X,Z);break}}handleSessionUpdated(Z,J){let $=this.sessions.get(Z.id);if(!$)return;if(Z.title&&Z.title!==$.title)$.title=Z.title,this.callbacks.onTitleGenerated?.($,Z.title)}handlePermissionAsked(Z,J){let $=this.sessions.get(Z.sessionID);if(!$||$.stopped)return;$.status="waiting_permission",f0.info("[OpenCodeProcessManager] Permission asked:",{id:Z.id,permission:Z.permission,metadata:JSON.stringify(Z.metadata),patterns:Z.patterns});let X={};if(Z.metadata)if(typeof Z.metadata==="string")try{X=JSON.parse(Z.metadata)}catch{}else X={...Z.metadata};let Y={...X};if(Z.patterns?.length>0){let W=Z.patterns[0];switch(Z.permission){case"bash":case"execute_command":if(!Y.command)Y.command=W;break;case"grep":case"glob":if(!Y.pattern)Y.pattern=W;break;case"webfetch":if(!Y.url)Y.url=W;break;case"websearch":if(!Y.query)Y.query=W;break;case"task":if(!Y.description)Y.description=W;break;default:if(!Y.filepath&&!Y.file_path)Y.filepath=W;break}}if(!Y.filepath&&!Y.file_path&&Z.patterns?.length>0)Y.filepath=Z.patterns[0];let Q={type:"control_request",request_id:Z.id,action:Z.permission,params:Y,timestamp:Date.now(),_opencode_patterns:Z.patterns,_opencode_always:Z.always,_opencode_tool:Z.tool};this.callbacks.onPermissionRequest?.($,Q)}handleQuestionAsked(Z,J){let $=this.sessions.get(Z.sessionID);if(!$||$.stopped)return;$.status="waiting_permission";let X={type:"control_request",request_id:Z.id,action:"AskUserQuestion",params:{questions:Z.questions.map((Y)=>({question:Y.question,header:Y.header,options:Y.options.map((Q)=>({label:Q.label,description:Q.description})),multiSelect:Y.multiple||!1}))},timestamp:Date.now(),_opencode_question:!0};this.callbacks.onPermissionRequest?.($,X)}async fetchModelContextLimits(){if(this.modelContextLimitsFetched)return;try{let{providers:Z}=await this.getProviders();for(let J of Z)if(J.models)for(let[$,X]of Object.entries(J.models)){let Y=X;if(Y?.limit?.context)this.modelContextLimits.set($,Y.limit.context)}this.modelContextLimitsFetched=!0,f0.debug(`[OpenCodeProcessManager] Cached context limits for ${this.modelContextLimits.size} models`)}catch(Z){f0.warn("[OpenCodeProcessManager] Failed to fetch model context limits:",Z)}}getModelContextLimit(Z){if(!this.modelContextLimitsFetched)this.fetchModelContextLimits().catch(()=>{});if(Z&&this.modelContextLimits.has(Z))return this.modelContextLimits.get(Z);return sW0.CONTEXT_LIMIT_STANDARD}calculateContextBreakdown(Z,J){let $=Z.input||0,X=Z.output||0,Y=Z.reasoning||0,Q=Z.cache?.read||0,W=Z.cache?.write||0,K=$+Q+W,z=J||sW0.CONTEXT_LIMIT_STANDARD;return{total:K,inputTokens:$,outputTokens:X,cacheCreation:W,cacheRead:Q,reasoningTokens:Y,systemPrompt:0,tools:0,mcpServers:0,messages:K,autocompactBuffer:0,contextLimit:z,remaining:Math.max(0,z-K),percentage:Math.round(K/z*100),lastUpdated:Date.now()}}async spawnSession(Z,J,$,X,Y,Q,W,K,z,G,H){if(f0.debug(`[OpenCodeProcessManager] Spawning session for project ${$} in ${X}`),this.sessions.size+this.tempSessions.size>=this.config.maxConcurrentSessions)throw Error("Maximum concurrent sessions reached");let V=await this.ensureServer(),F=Q?rW0(Q):void 0,B;try{let L=await V.client.session.create({directory:X,permission:F});if(L.error)throw Error(`Session creation failed: ${JSON.stringify(L.error)}`);if(B=L.data,!B?.id)throw f0.error("[OpenCodeProcessManager] Unexpected session.create() response:",{keys:Object.keys(L||{}),type:typeof L,hasData:!!L?.data,dataKeys:Object.keys(L?.data||{})}),Error("Session creation returned no ID")}catch(L){throw f0.error("[OpenCodeProcessManager] Failed to create session:",{error:L instanceof Error?L.message:"Unknown error"}),L}let U={tempId:Z,sessionId:B.id,userId:J,projectId:$,directoryPath:H?H.originalPath:X,status:"idle",permissionMode:Q||"default",model:W,agent:K,variant:G,createdAt:new Date,lastActivity:new Date,messageCount:0,title:B.title,...H&&{worktreePath:H.worktreePath,worktreeBranch:H.branch}};if(W)U.providerModel=NW(W);if(this.sessions.set(B.id,U),V.sessionCount++,this.callbacks.onSessionInitialized?.(U,B),Y&&Y.trim())this.sendPrompt(U,Y,z).catch((L)=>{f0.error("[OpenCodeProcessManager] Failed to send initial message:",{sessionId:U.sessionId,error:L instanceof Error?L.message:"Unknown error"})});return U}async resumeSession(Z,J,$,X,Y,Q,W,K){f0.info(`[OpenCodeProcessManager] Resuming session ${Z} for project ${$}`);let z=await this.ensureServer(),G;try{G=(await this.listSessions(X)).find((F)=>F.id===Z)}catch(V){f0.warn(`[OpenCodeProcessManager] Failed to verify session ${Z} in SDK:`,V)}if(!G)throw Error(`Session ${Z} not found in OpenCode SDK`);let H={tempId:Z,sessionId:Z,userId:J,projectId:$,directoryPath:X,status:"idle",permissionMode:Y||"default",model:Q,agent:W,variant:K,createdAt:new Date,lastActivity:new Date,messageCount:0,title:G.title};if(Q)H.providerModel=NW(Q);return this.sessions.set(Z,H),z.sessionCount++,this.callbacks.onSessionInitialized?.(H,G),H}async sendPrompt(Z,J,$){if(!Z.sessionId)throw Error("Session not initialized");let X=this.server;if(!X)throw Error("No OpenCode server running");let Y=[];if(J&&J.trim())Y.push({type:"text",text:J});if($?.length){for(let Q of $)if(Q.type==="image"&&Q.mimeType?.startsWith("image/")){let W=Q.mimeType.split("/")[1]||"png",K=gJ.join(bV.homedir(),".ccc","tmp","attachments",Z.sessionId);m9.mkdirSync(K,{recursive:!0});let z=gJ.join(K,`${tW0.randomUUID()}.${W}`);m9.writeFileSync(z,Buffer.from(Q.data,"base64")),Y.push({type:"file",mime:Q.mimeType,url:`file://${z}`,filename:`image.${W}`})}}if(Z.status!=="processing")Z.status="processing",this.callbacks.onProcessingStarted?.(Z);if(Z.lastActivity=new Date,Z.messageCount++,!Z.firstUserMessage&&J.trim())Z.firstUserMessage=J.trim();try{await X.client.session.promptAsync({sessionID:Z.sessionId,directory:Z.worktreePath||Z.directoryPath,parts:Y,model:Z.providerModel,agent:Z.agent,variant:Z.variant})}catch(Q){f0.error("[OpenCodeProcessManager] Failed to send prompt:",{sessionId:Z.sessionId,error:Q instanceof Error?Q.message:"Unknown error"}),this.handleSessionError(Z,Q instanceof Error?Q.message:"Failed to send message")}}async sendPermissionResponse(Z,J){let $=this.server;if(!$)throw f0.warn("[OpenCodeProcessManager] No server for permission response"),Error("No OpenCode server available");let X=this.sessions.get(Z),Y=X?.directoryPath;if(!X)f0.info(`[OpenCodeProcessManager] Session ${Z} not in memory, sending permission reply directly via SDK`);try{let Q;if(J._opencode_question&&J.behavior==="allow"&&J.updatedInput?.answers){let W=Object.values(J.updatedInput.answers).map((K)=>[String(K)]);Q=await $.client.question.reply({requestID:J.request_id,...Y&&{directory:Y},answers:W})}else if(J._opencode_question&&J.behavior==="deny")Q=await $.client.question.reject({requestID:J.request_id,...Y&&{directory:Y}});else{let W=J.behavior==="allow"?J.alwaysAllow?"always":"once":"reject";Q=await $.client.permission.reply({requestID:J.request_id,...Y&&{directory:Y},reply:W,message:J.message})}if(f0.info("[OpenCodeProcessManager] Permission reply SDK result:",{requestId:J.request_id,data:Q?.data,error:Q?.error,response:Q?.response?.status}),Q?.error)throw Error(`SDK error: ${JSON.stringify(Q.error)}`);if(X)X.status="idle",X.lastActivity=new Date}catch(Q){throw f0.error("[OpenCodeProcessManager] Failed to send permission response:",{sessionId:Z,requestId:J.request_id,error:Q instanceof Error?Q.message:"Unknown error"}),Q}}handleSessionError(Z,J){Z.status="error",this.callbacks.onSessionError?.(Z,J)}async stopSession(Z){let J=this.sessions.get(Z)||this.tempSessions.get(Z);if(!J){f0.warn(`[OpenCodeProcessManager] Session not found: ${Z}`);return}if(J.stopped=!0,J.status="stopped",J.sessionId){if(this.server){try{await this.server.client.session.abort({sessionID:J.sessionId,directory:J.directoryPath})}catch($){f0.debug("[OpenCodeProcessManager] Error aborting session (may already be idle):",{sessionId:J.sessionId,error:$ instanceof Error?$.message:"Unknown error"})}if(this.server.sessionCount>0)this.server.sessionCount--}}if(J.sessionId){let $=gJ.join(bV.homedir(),".ccc","tmp","attachments",J.sessionId);if(m9.existsSync($))m9.rmSync($,{recursive:!0})}if(J.sessionId)this.sessions.delete(J.sessionId);this.tempSessions.delete(J.tempId),this.callbacks.onSessionStopped?.(J,"user_stopped")}async stopAllSessions(){for(let[Z]of this.sessions)await this.stopSession(Z).catch(()=>{});for(let[Z]of this.tempSessions)await this.stopSession(Z).catch(()=>{})}async stopAll(){if(await this.stopAllSessions(),this.server){let Z=this.server.port;try{this.server.eventAbortController?.abort(),await Promise.race([this.server.client.instance.dispose(),new Promise((J,$)=>setTimeout(()=>$(Error("dispose timeout")),5000))]).catch(()=>{}),this.server.close()}catch{}this.server=null,this.serverInitPromise=null,await kQ(Z),f0.info(`[OpenCodeProcessManager] Server stopped, port ${Z} freed`)}}async restartServer(){if(f0.info("[OpenCodeProcessManager] Restarting server for config reload..."),this.server){let Z=this.server.port;try{this.server.eventAbortController?.abort(),await Promise.race([this.server.client.instance.dispose(),new Promise((J,$)=>setTimeout(()=>$(Error("dispose timeout")),5000))]).catch(()=>{}),this.server.close()}catch{}this.server=null,this.serverInitPromise=null,await kQ(Z)}await this.startServer(),f0.info("[OpenCodeProcessManager] Server restarted successfully")}getSession(Z){return this.sessions.get(Z)||this.tempSessions.get(Z)}getAllSessions(){return[...this.sessions.values(),...this.tempSessions.values()]}getSessionCount(){return this.sessions.size+this.tempSessions.size}getServerCount(){return this.server?1:0}getServer(){return this.server}async getProviders(){let Z=await this.ensureServer(),[J,$]=await Promise.all([Z.client.provider.list(),Z.client.global.config.get()]),X=J.data||J,Y=$.data||$,Q={},W=Y?.provider||{};for(let[K,z]of Object.entries(W)){let G=z?.blacklist;if(Array.isArray(G)&&G.length>0)Q[K]=G}return{providers:X.all||[],connected:X.connected||[],defaults:X.default||{},blacklists:Q}}async getAnyServer(){return this.ensureServer()}async listSessions(Z){let J=await this.ensureServer();try{let $=await J.client.session.list({directory:Z}),X=$.data||$;return Array.isArray(X)?X:[]}catch($){return f0.error("[OpenCodeProcessManager] Failed to list sessions:",{directory:Z,error:$ instanceof Error?$.message:"Unknown error"}),[]}}findOpenCodeDbPath(Z){let J=[];if(Z)J.push(gJ.join(Z,".opencode","opencode.db"));let $=bV.homedir();J.push(gJ.join($,".local","share","opencode","opencode.db"));let X=process.env.LOCALAPPDATA;if(X)J.push(gJ.join(X,"opencode","opencode.db"));for(let Y of J)if(m9.existsSync(Y))return Y;return null}getSessionMessageCounts(Z){let J=new Map,$=this.findOpenCodeDbPath(Z);if(!$)return f0.debug("[OpenCodeProcessManager] No OpenCode SQLite database found"),J;try{let X=new n$1($,{readonly:!0});try{let Y=X.query("SELECT session_id, COUNT(*) as cnt FROM message GROUP BY session_id").all();for(let Q of Y)J.set(Q.session_id,Q.cnt)}finally{X.close()}}catch(X){f0.warn("[OpenCodeProcessManager] Failed to query OpenCode SQLite db:",{dbPath:$,error:X instanceof Error?X.message:"Unknown error"})}return J}async getSessionMessages(Z,J){let $=await this.ensureServer(),X;try{X=(await this.listSessions(J)).find((V)=>V.id===Z)?.title}catch{}let Y=await $.client.session.messages({sessionID:Z,directory:J}),Q=Y.data||Y;if(!Array.isArray(Q))return{messages:[],title:X};let W=[],K=null;for(let G of Q){let H=G.info,V=G.parts||[],F=H.role,B=H.id,U=H.time.created>1000000000000?H.time.created:H.time.created*1000,L=new Date(U).toISOString();if(F==="user"){let _=V.filter((w)=>w.type==="text").map((w)=>w.text||"").join(`
2389
2389
  `);W.push({uuid:B,parentUuid:K,timestamp:L,type:"user",role:"user",content:_||"[user message]"}),K=B}else if(F==="assistant")for(let O of V){let _=O.id||`${B}-${V.indexOf(O)}`;if(O.type==="text"){if(O.synthetic||O.ignored)continue;W.push({uuid:_,parentUuid:K,timestamp:L,type:"assistant",role:"assistant",content:[{type:"text",text:O.text||""}]}),K=_}else if(O.type==="tool"){let w=O.state||{},j=w.input||{},T;try{T=typeof j==="string"?JSON.parse(j):j}catch{T=j}let N={...T,...w.metadata||{}};if(W.push({uuid:_,parentUuid:K,timestamp:L,type:"assistant",role:"assistant",content:[{type:"tool_use",id:O.callID||_,name:O.tool||"unknown",input:N}]}),K=_,w.status==="completed"||w.status==="error"){let R=`${_}-result`;W.push({uuid:R,parentUuid:K,timestamp:L,type:"tool",content:w.output||w.error||"",toolName:O.tool||"unknown",toolUseId:O.callID||_,isError:w.status==="error"}),K=R}}else if(O.type==="reasoning"){let w=O.text||"";if(w)W.push({uuid:_,parentUuid:K,timestamp:L,type:"assistant",role:"assistant",content:[{type:"thinking",thinking:w}]}),K=_}}}let z;for(let G=Q.length-1;G>=0;G--){let H=Q[G];if(H&&H.info?.role==="assistant"){if(H.info.tokens)z=this.calculateContextBreakdown(H.info.tokens);break}}return{messages:W,title:X,context:z}}cleanupInactiveSessions(){let Z=Date.now(),J=this.config.sessionTimeoutMs;for(let $ of this.getAllSessions())if(Z-$.lastActivity.getTime()>J)this.stopSession($.sessionId||$.tempId).catch(()=>{})}async getCheckpoints(Z,J,$=5){let Y=await(await this.ensureServer()).client.session.messages({sessionID:Z,directory:J}),Q=Y.data||Y;if(!Array.isArray(Q))return{checkpoints:[],hasAnyFileChanges:!1};let K=Q.filter((V)=>V.info.role==="user").slice(-$-1).reverse(),z=[],G=!1;if(K.length>0)z.push({uuid:"current",preview:"(current)",timestamp:new Date().toISOString(),hasFileChanges:!1,fileCount:0});let H=new Map;for(let V=0;V<Q.length;V++)if(Q[V].info?.id)H.set(Q[V].info.id,V);for(let V of K.slice(0,$)){let F=V.info.id,U=(V.parts||[]).filter((g)=>g.type==="text").map((g)=>g.text||"").join(`
2390
- `).trim(),L=U.length>100?U.substring(0,100)+"...":U,O=V.info.time?.created||0,_=O>1000000000000?O:O*1000,w=new Date(_).toISOString(),j=!1,T=0,N=0,R=0,P=V.info.summary?.diffs||[],c=H.get(F);if(P.length>0){j=!0,G=!0,T=P.length;for(let g of P){if(g.additions!==void 0)N+=g.additions;if(g.deletions!==void 0)R+=g.deletions}}else if(c!==void 0){let g=new Set;for(let H0=c+1;H0<Q.length;H0++){let S0=Q[H0];if(S0.info.role==="user")break;if(!S0.parts)continue;for(let Y0 of S0.parts){if(Y0.type==="patch"&&Array.isArray(Y0.files))for(let X0 of Y0.files)g.add(X0);if(Y0.type==="tool"&&Y0.state?.status==="completed"){let X0=(Y0.tool||"").toLowerCase();if(X0==="apply_patch"){let j0=Y0.state.metadata?.files||[];for(let B0 of j0)if(B0.filePath||B0.relativePath){if(g.add(B0.filePath||B0.relativePath),B0.additions!==void 0)N+=B0.additions;if(B0.deletions!==void 0)R+=B0.deletions}}else if(["write","edit","multi_edit","patch"].includes(X0)){let j0=Y0.state.metadata?.filepath||Y0.state.input?.filePath||Y0.state.input?.file_path||"";if(j0)g.add(j0);if(Y0.state.metadata?.filediff){if(Y0.state.metadata.filediff.additions!==void 0)N+=Y0.state.metadata.filediff.additions;if(Y0.state.metadata.filediff.deletions!==void 0)R+=Y0.state.metadata.filediff.deletions}}}}}if(g.size>0)j=!0,G=!0,T=g.size}z.push({uuid:F,preview:L||"[user message]",fullMessage:U||void 0,timestamp:w,hasFileChanges:j,fileCount:T,linesAdded:j?N:void 0,linesRemoved:j?R:void 0})}return{checkpoints:z,hasAnyFileChanges:G}}async revertToMessage(Z,J,$){let Y=await(await this.ensureServer()).client.session.revert({sessionID:Z,messageID:J,directory:$});return Y.data||Y}async unrevert(Z,J){let X=await(await this.ensureServer()).client.session.unrevert({sessionID:Z,directory:J});return X.data||X}async getCommandsAndAgents(Z){let J=await this.ensureServer(),$={slashCommands:[],agents:[],skills:[]};try{let X=await J.client.command.list({directory:Z}),Y=X.data||X||[];if(Array.isArray(Y))$.slashCommands=Y.map((Q)=>Q.name||Q).filter(Boolean)}catch(X){f0.debug("[OpenCodeProcessManager] Failed to list commands:",{error:X.message})}try{let X=await J.client.app.agents({directory:Z}),Y=X.data||X||[];if(Array.isArray(Y))$.agents=Y.map((Q)=>Q.name||Q.id||Q).filter(Boolean)}catch(X){f0.debug("[OpenCodeProcessManager] Failed to list agents:",{error:X.message})}try{let X=await J.client.app.skills({directory:Z}),Y=X.data||X||[];if(Array.isArray(Y))$.skills=Y.map((Q)=>Q.name||Q.id||Q).filter(Boolean)}catch(X){f0.debug("[OpenCodeProcessManager] Failed to list skills:",{error:X.message})}return $}async forkAtMessage(Z,J,$){let Y=await(await this.ensureServer()).client.session.fork({sessionID:Z,messageID:J,directory:$});return Y.data||Y}}import*as DM from"path";import*as eW0 from"os";import*as u9 from"fs";var ZK0=y(),UM=DM.join(eW0.homedir(),".ccc"),LM=DM.join(UM,"settings.json");function a$1(){if(!u9.existsSync(UM))u9.mkdirSync(UM,{recursive:!0})}function JK0(){try{if(!u9.existsSync(LM))return{};let Z=u9.readFileSync(LM,"utf-8");return JSON.parse(Z)}catch(Z){return ZK0.warn("[BackendSettings] Failed to read settings:",Z),{}}}function o$1(Z){try{a$1(),u9.writeFileSync(LM,JSON.stringify(Z,null,2),"utf-8")}catch(J){ZK0.error("[BackendSettings] Failed to write settings:",J)}}function OM(Z,J){let $=JK0();$[Z]=J,o$1($)}function _M(Z){return JK0()[Z]}var N0=y();class RW{name="OpenCode Agent Service";running=!1;startedAt;mqttClient=null;sessionsService=null;processManager;worktreeManager;config;totalSessionsCreated=0;totalMessagesProcessed=0;pendingPermissions=new Map;static PENDING_PERMISSION_TTL_MS=3600000;cleanupInterval;getProcessManager(){return this.processManager}constructor(Z){this.config=Z,this.worktreeManager=new KZ,this.processManager=new BM(Z,{onSessionInitialized:this.handleSessionInitialized.bind(this),onTitleGenerated:this.handleTitleGenerated.bind(this),onAssistantMessage:this.handleAssistantMessage.bind(this),onPermissionRequest:this.handlePermissionRequest.bind(this),onQuestionRequest:this.handlePermissionRequest.bind(this),onSessionError:this.handleSessionError.bind(this),onSessionStopped:this.handleSessionStopped.bind(this),onProcessingStarted:this.handleProcessingStarted.bind(this),onProcessingComplete:this.handleProcessingComplete.bind(this),onContextUpdate:this.handleContextUpdate.bind(this)})}async determineWorkingDirectory(Z,J,$,X=!1){try{if(!X)return{path:J,isWorktree:!1};if(!await WZ(J))return{path:J,isWorktree:!1};let Q=await M8(J);if(!Q)return{path:J,isWorktree:!1};let{worktree:W,isNew:K}=await this.worktreeManager.getOrCreateForSession($,Q);return{path:W.path,isWorktree:!0,branch:W.branch}}catch(Y){return N0.error("[OpenCodeAgent] Worktree creation failed, falling back to project path",{error:Y instanceof Error?Y.message:"Unknown error"}),{path:J,isWorktree:!1}}}setMQTTClient(Z){this.mqttClient=Z}setSessionsService(Z){this.sessionsService=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,N0.info("[OpenCodeAgent] Service starting..."),this.mqttClient)this.registerMQTTHandlers();else N0.warn("[OpenCodeAgent] MQTT client not set - handlers will not be registered");if(_M("opencode_enabled"))N0.info("[OpenCodeAgent] OpenCode is enabled, starting server..."),await this.processManager.startServer();else N0.info("[OpenCodeAgent] OpenCode is disabled, server will not start until enabled");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions(),this.cleanupStalePendingPermissions()},300000),N0.info("[OpenCodeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions})}catch(Z){if(N0.error("[OpenCodeAgent] Failed to start",Z),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=void 0;throw this.running=!1,Z}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=void 0;this.pendingPermissions.clear(),await this.processManager.stopAll(),N0.info("[OpenCodeAgent] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("opencode/+/session/start",(Z,J)=>{this.handleSessionStart(J)}),this.mqttClient.subscribe("opencode/+/input/+",(Z,J)=>{let $=Z.split("/")[3]||"";this.handleUserInput($,J)}),this.mqttClient.subscribe("opencode/+/permission/response/+",(Z,J)=>{let $=Z.split("/")[4]||"";this.handlePermissionResponseFromMobile($,J)}),this.mqttClient.subscribe("opencode/+/session/stop/+",(Z,J)=>{let $=Z.split("/")[4]||"";this.handleSessionStop($,J)}),this.mqttClient.subscribe("opencode/+/providers/list",(Z,J)=>{this.handleProvidersList(J)}),this.mqttClient.subscribe("opencode/+/providers/toggle-model",(Z,J)=>{this.handleToggleModel(J)}),this.mqttClient.subscribe("opencode/+/toggle",(Z,J)=>{this.handleToggleOpenCode(J)}),this.mqttClient.subscribe("opencode/+/enabled",(Z,J)=>{this.handleGetEnabled(J)}),this.mqttClient.subscribe("opencode/+/checkpoints/list/+",(Z,J)=>{let $=Z.split("/")[4]||"";this.handleCheckpointList($,J)}),this.mqttClient.subscribe("opencode/+/session/rewind/+",(Z,J)=>{let $=Z.split("/")[4]||"";this.handleRewind($,J)}),N0.info("[OpenCodeAgent] MQTT handlers registered")}async handleSessionStart(Z){let J="",$="";try{let X=await this.parseMessage(Z);if(!X)return;let{data:Y,profileId:Q}=X;J=Q,$=Y.tempId||"",N0.info("[OpenCodeAgent] Session start request:",{profileId:J,tempId:Y.tempId,projectId:Y.projectId,directoryPath:Y.directoryPath,permissionMode:Y.permissionMode,selectedModel:Y.selectedModel});let{path:W,isWorktree:K,branch:z}=await this.determineWorkingDirectory(Y.projectId,Y.directoryPath,Y.tempId,Y.gitWorktreesEnabled??!1),G=await this.processManager.spawnSession(Y.tempId,J,Y.projectId,W,Y.initialMessage||"",Y.permissionMode,Y.selectedModel,Y.agent,Y.attachments,Y.variant,K?{originalPath:Y.directoryPath,worktreePath:W,branch:z}:void 0);this.totalSessionsCreated++}catch(X){if(N0.error("[OpenCodeAgent] Error starting session:",{profileId:J,error:X instanceof Error?X.message:"Unknown error"}),J)this.publishStatus(J,$||"temp_error",{type:"error",error:X instanceof Error?X.message:"Failed to start session",tempId:$,timestamp:Date.now()})}}async handleUserInput(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;let{data:Y,profileId:Q}=X;if($=Q,!Y.message&&(!Y.attachments||Y.attachments.length===0))return;let W=this.processManager.getSession(Y.sessionId);if(!W)try{W=await this.processManager.resumeSession(Y.sessionId,$,Y.projectId,Y.directoryPath,Y.permissionMode,Y.selectedModel,Y.agent,Y.variant),N0.info(`[OpenCodeAgent] Resumed existing session ${Y.sessionId}`)}catch{N0.info(`[OpenCodeAgent] Session ${Y.sessionId} not found in SDK, creating new session`);let{path:K,isWorktree:z,branch:G}=await this.determineWorkingDirectory(Y.projectId,Y.directoryPath,Y.sessionId,Y.gitWorktreesEnabled??!1);W=await this.processManager.spawnSession(Y.sessionId,$,Y.projectId,K,Y.message||"",Y.permissionMode,Y.selectedModel,Y.agent,Y.attachments,Y.variant,z?{originalPath:Y.directoryPath,worktreePath:K,branch:G}:void 0),this.totalSessionsCreated++,this.totalMessagesProcessed++;return}if(Y.selectedModel&&Y.selectedModel!==W.model)W.model=Y.selectedModel,W.providerModel=NW(Y.selectedModel),N0.info("[OpenCodeAgent] Model changed mid-session:",{sessionId:Z,newModel:Y.selectedModel});if(Y.agent&&Y.agent!==W.agent)W.agent=Y.agent;if(Y.variant!==void 0)W.variant=Y.variant||void 0;await this.processManager.sendPrompt(W,Y.message||"",Y.attachments),this.totalMessagesProcessed++}catch(X){N0.error("[OpenCodeAgent] 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;$=Q.data,X=$.requestId,Y=Q.profileId;let W=this.pendingPermissions.get(X),K=W?._opencode_question,z=this.processManager.getSession(Z);if(!z){N0.info(`[OpenCodeAgent] Session ${Z} not in memory, attempting resume for permission response`);let G=await b4.getPermission(X);N0.info("[OpenCodeAgent] Stored permission lookup:",{requestId:X,found:!!G,projectPath:G?.projectPath});let H=G?.projectPath;if(H)try{await this.processManager.resumeSession(Z,Y,"",H),N0.info(`[OpenCodeAgent] Resumed session ${Z} for permission response`)}catch(V){N0.warn(`[OpenCodeAgent] Could not resume session ${Z}:`,{error:V instanceof Error?V.message:"Unknown error"})}else N0.warn(`[OpenCodeAgent] No directoryPath available to resume session ${Z}`)}else N0.info(`[OpenCodeAgent] Session ${Z} already in memory, status: ${z.status}`);if($.approved&&$.answers&&Object.keys($.answers).length>0)await this.processManager.sendPermissionResponse(Z,{request_id:X,behavior:"allow",updatedInput:{answers:$.answers},_opencode_question:K});else if($.approved)await this.processManager.sendPermissionResponse(Z,{request_id:X,behavior:"allow",updatedInput:W?.params,_opencode_question:K,alwaysAllow:!!$.addToAllowedTools});else{let G=$.denyMessage||"Permission denied by user",H=$.hardDeny!==!1;if(await this.processManager.sendPermissionResponse(Z,{request_id:X,behavior:"deny",message:G,_opencode_question:K}),H){let V=Y;setTimeout(()=>{this.processManager.stopSession(Z),this.publishStatus(V,Z,{type:"session_stopped",reason:"permission_denied",message:G,timestamp:Date.now()})},100)}}if(W)this.pendingPermissions.delete(X);b4.removePermission(X).catch(()=>{})}catch(Q){if(N0.error("[OpenCodeAgent] 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),b4.removePermission(X).catch(()=>{})}}async handleSessionStop(Z,J){let X=(await this.parseMessage(J))?.profileId||"";N0.info("[OpenCodeAgent] Session stop request:",{profileId:X,sessionId:Z});try{await this.processManager.stopSession(Z)}catch(Y){N0.error("[OpenCodeAgent] Failed to stop session",{sessionId:Z,error:Y})}}async handleProvidersList(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=await this.processManager.getProviders();this.publishProviderResponse(J,{providers:X.providers,connected:X.connected,defaults:X.defaults,blacklists:X.blacklists})}catch($){if(N0.error("[OpenCodeAgent] Error listing providers:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishProviderResponse(J,{error:$ instanceof Error?$.message:"Failed to list providers"})}}async handleToggleModel(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;let{data:X,profileId:Y}=$;J=Y;let{providerId:Q,modelId:W,enabled:K}=X;if(!Q||!W){this.publishProviderResponse(J,{error:"providerId and modelId are required"});return}let z=await this.processManager.getAnyServer(),G=await z.client.global.config.get(),F=((G.data||G)?.provider?.[Q]||{}).blacklist||[],B;if(K)B=F.filter((U)=>U!==W);else B=F.includes(W)?F:[...F,W];await z.client.global.config.update({config:{provider:{[Q]:{blacklist:B}}}}),this.publishProviderResponse(J,{success:!0,providerId:Q,modelId:W,enabled:K})}catch($){if(N0.error("[OpenCodeAgent] Error toggling model:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishProviderResponse(J,{error:$ instanceof Error?$.message:"Failed to toggle model"})}}async handleToggleOpenCode(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let{enabled:X}=$.data;if(X)N0.info("[OpenCodeAgent] Enabling OpenCode, starting server..."),await this.processManager.startServer(),OM("opencode_enabled",!0);else N0.info("[OpenCodeAgent] Disabling OpenCode, stopping server..."),OM("opencode_enabled",!1),await this.processManager.stopAll();this.publishToggleResponse(J,{enabled:!!X})}catch($){if(N0.error("[OpenCodeAgent] Error toggling OpenCode:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishToggleResponse(J,{enabled:!1,error:$ instanceof Error?$.message:"Failed to toggle OpenCode"})}}async handleGetEnabled(Z){let J=await this.parseMessage(Z);if(!J)return;let $=J.profileId,X=_M("opencode_enabled")||!1;this.publishToggleResponse($,{enabled:X})}publishToggleResponse(Z,J){if(!this.mqttClient)return;let $=`opencode/${Z}/toggle/response`;this.publishEncrypted($,J,Z).catch((X)=>{N0.error("[OpenCodeAgent] Failed to publish toggle response",{error:X instanceof Error?X.message:"Unknown error"})})}publishProviderResponse(Z,J){if(!this.mqttClient)return;let $=`opencode/${Z}/providers/response`;this.publishEncrypted($,J,Z).catch((X)=>{N0.error("[OpenCodeAgent] Failed to publish provider response",{error:X instanceof Error?X.message:"Unknown error"})})}handleSessionInitialized(Z,J){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,worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch,slashCommands:[],agents:[],skills:[],timestamp:Date.now()}),this.processManager.getCommandsAndAgents(Z.directoryPath).then(({slashCommands:$,agents:X,skills:Y})=>{if($.length||X.length||Y.length)this.publishStatus(Z.userId,Z.sessionId,{type:"commands_updated",sessionId:Z.sessionId,slashCommands:$,agents:X,skills:Y,timestamp:Date.now()})}).catch(($)=>{N0.debug("[OpenCodeAgent] Failed to fetch commands/agents/skills:",{error:$.message})}),this.sessionsService){let $=Z.worktreePath||Z.directoryPath;this.sessionsService.notifySessionCreated(Z.directoryPath,$).catch(()=>{}),this.sessionsService.notifyOpenCodeSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"OpenCode Session",status:Z.status}).catch(()=>{})}}handleTitleGenerated(Z,J){if(this.publishStatus(Z.userId,Z.sessionId,{type:"title_generated",title:J,timestamp:Date.now()}),this.sessionsService&&Z.sessionId)this.sessionsService.notifyOpenCodeSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:J,status:Z.status}).catch(()=>{})}handleAssistantMessage(Z,J){if(this.totalMessagesProcessed++,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(),...J._opencode_question&&{_opencode_question:!0}}),b4.addPermission({requestId:J.request_id,sessionId:Z.sessionId,projectPath:Z.directoryPath,action:J.action,params:J.params,createdAt:new Date().toISOString()}).catch(()=>{});let $=`opencode/${Z.userId}/permission/request/${Z.sessionId}`,X={request_id:J.request_id,action:J.action,params:J.params};N0.info("[OpenCodeAgent] Publishing permission request:",{topic:$,action:J.action,params:JSON.stringify(J.params)}),this.publishEncrypted($,X,Z.userId).catch((Y)=>{N0.error("[OpenCodeAgent] Failed to publish permission request",{error:Y instanceof Error?Y.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.notifyOpenCodeSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"OpenCode Session",status:"stopped"}).catch(()=>{})}}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){if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifyOpenCodeSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"OpenCode Session",status:"idle"}).catch(()=>{})}}handleContextUpdate(Z,J){if(Z.sessionId)this.publishContextUpdate(Z.userId,Z.sessionId,J)}publishStatus(Z,J,$){if(!this.mqttClient)return;let X=`opencode/${Z}/status/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{N0.error("[OpenCodeAgent] Failed to publish status",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishOutput(Z,J,$){if(!this.mqttClient)return;let X=`opencode/${Z}/output/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{N0.error("[OpenCodeAgent] Failed to publish output",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishContextUpdate(Z,J,$){if(!this.mqttClient)return;let X=`opencode/${Z}/context/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{N0.error("[OpenCodeAgent] Failed to publish context",{error:Y instanceof Error?Y.message:"Unknown error"})})}async handleCheckpointList(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{limit:Y,directoryPath:Q}=X.data,W=await this.processManager.getCheckpoints(Z,Q||"",Y||5),K=`opencode/${$}/checkpoints/response/${Z}`;await this.publishEncrypted(K,{sessionId:Z,checkpoints:W.checkpoints,hasAnyFileChanges:W.hasAnyFileChanges},$)}catch(X){if(N0.error("[OpenCodeAgent] Error handling checkpoint list:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`opencode/${$}/checkpoints/response/${Z}`;await this.publishEncrypted(Y,{sessionId:Z,checkpoints:[],hasAnyFileChanges:!1,error:X instanceof Error?X.message:"Failed to get checkpoints"},$)}}}async handleRewind(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{checkpointUuid:Y,mode:Q,directoryPath:W}=X.data,K=W||"",z;if(Q==="conversation_only")z=(await this.processManager.forkAtMessage(Z,Y,K))?.id;else if(Q==="both")await this.processManager.revertToMessage(Z,Y,K),z=(await this.processManager.forkAtMessage(Z,Y,K))?.id;let G=`opencode/${$}/rewind/response/${Z}`;await this.publishEncrypted(G,{type:"rewind_complete",sessionId:Z,checkpointUuid:Y,mode:Q,newSessionId:z},$)}catch(X){if(N0.error("[OpenCodeAgent] Error handling rewind:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`opencode/${$}/rewind/response/${Z}`;await this.publishEncrypted(Y,{type:"rewind_failed",sessionId:Z,error:X instanceof Error?X.message:"Rewind failed"},$)}}}async parseMessage(Z){try{let J=JSON.parse(Z.toString());if(h0.isEncryptedEnvelope(J)){let $=J.c;if(!$)return null;let X=h0.getClientKey($);if(!X)return null;let Y=await h0.decrypt(X,J);return{data:JSON.parse(Y),profileId:$}}return N0.warn("[OpenCodeAgent] Received unencrypted message \u2014 dropping"),null}catch(J){return N0.warn("[OpenCodeAgent] Failed to parse message",{error:J}),null}}async publishEncrypted(Z,J,$){if(!this.mqttClient)return;if(!$||!h0.hasKey($)){N0.warn(`[OpenCodeAgent] No encryption key for profile ${$} \u2014 dropping message on ${Z}`);return}let X=h0.getClientKey($),Y=await h0.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>RW.PENDING_PERMISSION_TTL_MS)this.pendingPermissions.delete(J),b4.removePermission(J).catch(()=>{})}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.processManager.getSessionCount(),activeServers:this.processManager.getServerCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}async listSessions(Z){let J=await this.processManager.listSessions(Z),$=this.processManager.getSessionMessageCounts(Z),X=[];for(let Y of J){let Q,W;try{let K=await this.worktreeManager.getWorktreeForSession(Y.id,Z);if(K)Q=K.path,W=K.branch}catch{}X.push({sessionId:Y.id,title:Y.title||"OpenCode Session",lastActivity:new Date(Y.time?.updated||Y.time?.created||0).toISOString(),messageCount:$.get(Y.id)||0,worktreePath:Q,worktreeBranch:W})}return X}async getSessionMessages(Z,J){return this.processManager.getSessionMessages(Z,J)}getActiveSessions(){return this.processManager.getAllSessions().filter((Z)=>Z.sessionId).map((Z)=>({sessionId:Z.sessionId,projectPath:Z.directoryPath,status:Z.status,title:Z.title,messageCount:Z.messageCount,lastActivity:Z.lastActivity.toISOString(),worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch}))}}import*as L1 from"fs/promises";import*as wM from"fs";import*as r1 from"path";import*as zZ from"fs/promises";var rX=y(),$K0=10485760;async function U1(Z,J={}){let{maxSize:$=$K0,encoding:X="utf-8",logWarnings:Y=!0}=J;try{let Q=await zZ.stat(Z);if(!Q.isFile()){if(Y)rX.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Q.size>$){if(Y)rX.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Q.size,maxSize:$});return null}return await zZ.readFile(Z,X)}catch(Q){if(Q.code!=="ENOENT"&&Y)rX.debug("[SafeFS] Error reading file",{filePath:Z,error:Q});return null}}async function XK0(Z,J={}){let{maxSize:$=$K0,logWarnings:X=!0}=J;try{let Y=await zZ.stat(Z);if(!Y.isFile()){if(X)rX.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Y.size>$){if(X)rX.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Y.size,maxSize:$});return null}return await zZ.readFile(Z)}catch(Y){if(Y.code!=="ENOENT"&&X)rX.debug("[SafeFS] Error reading file",{filePath:Z,error:Y});return null}}async function Z6(Z){try{return(await zZ.stat(Z)).isDirectory()}catch{return!1}}async function d9(Z){try{return await zZ.stat(Z)}catch{return null}}var c9=y();class gV{validatePath(Z,J){try{let $=r1.resolve(Z),X=r1.resolve($,J);if(!(X===$||X.startsWith($+r1.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};try{let Q=wM.realpathSync(X),W=wM.realpathSync($);if(!(Q===W||Q.startsWith(W+r1.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 L1.stat($.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let Y=await L1.readdir($.fullPath,{withFileTypes:!0}),Q=await Promise.all(Y.map(async(W)=>{let K=r1.join($.fullPath,W.name);try{let z=await L1.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 c9.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 d9($.fullPath);if(!X||!X.isFile())return{content:"",size:0,error:"Path is not a file"};let Y=await U1($.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 c9.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=r1.dirname(X.fullPath);return await L1.mkdir(Y,{recursive:!0}),await L1.writeFile(X.fullPath,$,"utf-8"),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return c9.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 L1.access($.fullPath),{success:!1,error:"File already exists"}}catch{}let X=r1.basename(J);if(!this.isValidFilename(X))return{success:!1,error:"Invalid filename"};let Y=r1.dirname($.fullPath);return await L1.mkdir(Y,{recursive:!0}),await L1.writeFile($.fullPath,"","utf-8"),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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=r1.basename(J);if(!this.isValidFilename(X))return{success:!1,error:"Invalid directory name"};try{if((await L1.stat($.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await L1.mkdir($.fullPath,{recursive:!0}),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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 L1.stat($.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await L1.unlink($.fullPath),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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===r1.resolve(Z))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await L1.stat($.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await L1.rm($.fullPath,{recursive:!0,force:!0}),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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 L1.access($.fullPath),!0}catch{return!1}}async getStats(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return null;try{let X=await L1.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 d9($.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 XK0($.fullPath,{maxSize:Y});if(Q===null)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Failed to read file"};let W=this.getMimeType(r1.basename(J));return{content:Q,size:Number(X.size),mimeType:W}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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=r1.basename(J);if(!this.isValidFilename(Y))return{success:!1,error:"Invalid filename"};let Q=r1.dirname(X.fullPath);return await L1.mkdir(Q,{recursive:!0}),await L1.writeFile(X.fullPath,$),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return c9.error("[FileManager] writeFileBinary error",{error:Q,path:X.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}getMimeType(Z){let J=r1.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 jM from"path";var J6=y(),sX=51200,YK0=50,r$1=60000,QK0=300000;class mV extends J1{name="File Browser Service";get logPrefix(){return"[FileBrowser]"}fileManager;fileSaveOperations=new Map;binaryUploadOperations=new Map;staleOpCleanupInterval=null;constructor(){super();this.fileManager=new gV}async onStart(){this.staleOpCleanupInterval=setInterval(()=>{this.cleanupStaleOperations()},r$1)}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)}),J6.info("[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){J6.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/sX));for(let K=0;K<W;K++){let z=K*sX,G=Math.min(z+sX,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(YK0)}this.requestsHandled++}catch(J){J6.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){J6.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){J6.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){J6.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){J6.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){J6.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)J6.error("[FileBrowser] Binary upload write failed",{error:G.error});else this.requestsHandled++,J6.info("[FileBrowser] Binary upload completed",{path:$.relativePath,size:z.length})}}catch(J){J6.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:jM.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/sX)),z=jM.basename($.relativePath);for(let G=0;G<K;G++){let H=G*sX,V=Math.min(H+sX,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(YK0)}this.requestsHandled++,J6.info("[FileBrowser] Binary download completed",{path:$.relativePath,size:Q.size,chunks:K})}catch(J){J6.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>QK0)J6.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>QK0)J6.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 Z0=y();class uV extends J1{name="Git Service";get logPrefix(){return"[GitService]"}worktreeManager;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){super();this.worktreeManager=new KZ}async onStart(){if(this.ghAuthResult=await CQ0(),!this.ghAuthResult.authenticated)Z0.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else{Z0.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username,gitProtocol:this.ghAuthResult.gitProtocol});let Z=await PQ0();if(!Z.success)Z0.warn("[GitService] Could not sync gh config git_protocol",{error:Z.error});let J=await IQ0();if(!J.success)Z0.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)}),Z0.info("[GitService] MQTT handlers registered")}async handleOrgsRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z0.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 XM(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z0.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(Z0.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 CV($.org,$.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${Y}/response`,W,X),this.requestsHandled++}catch(J){Z0.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(Z0.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 SQ0($.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),Z0.debug("[GitService] Sent search results",{source:W,count:Q.length,isComplete:K})},$.limit||50),this.requestsHandled++}catch(J){Z0.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(Z0.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 yQ0($.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){Z0.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(Z0.info("[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 kQ0($.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){Z0.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{Z0.debug("[GitService] Is-repo request",{clientId:$.clientId,path:$.path});let Y=await WZ($.path),Q;if(Y){let[W,K,z]=await Promise.all([M8($.path),fJ($.path),lQ0($.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){Z0.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{Z0.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){Z0.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;Z0.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){Z0.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;Z0.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){Z0.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{Z0.debug("[GitService] Status request",{clientId:$.clientId,path:$.path});let Q={success:!0,status:await YM($.path),timestamp:Date.now()};await this.publishResponse(`git/status/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z0.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{Z0.debug("[GitService] Diff request",{clientId:$.clientId,path:$.path,file:$.file,staged:$.staged});let Y=await vQ0($.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){Z0.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{Z0.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 YM(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){Z0.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){Z0.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{Z0.debug("[GitService] Stage request",{clientId:$.clientId,path:$.path,files:$.files}),await hQ0($.path,$.files);let Y={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${$.clientId}/response`,Y,X),this.requestsHandled++}catch(Y){Z0.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{Z0.debug("[GitService] Unstage request",{clientId:$.clientId,path:$.path,files:$.files}),await fQ0($.path,$.files);let Y={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${$.clientId}/response`,Y,X),this.requestsHandled++}catch(Y){Z0.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{Z0.info("[GitService] Commit request",{clientId:$.clientId,path:$.path,signoff:$.signoff});let Q={success:!0,commit:await bQ0($.path,$.message,$.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z0.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{Z0.debug("[GitService] Unpushed commits request",{clientId:$.clientId,path:$.path});let Y=await pX($.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){Z0.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{Z0.info("[GitService] Push request",{clientId:$.clientId,path:$.path,force:$.force});let Y=await pQ0($.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){Z0.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{Z0.info("[GitService] History request",{clientId:$.clientId,path:$.path,limit:$.limit});let Y=await iQ0($.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){Z0.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{Z0.debug("[GitService] Commit details request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash});let Q={success:!0,commit:await nQ0($.path,$.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z0.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{Z0.debug("[GitService] Commit file diff request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash,filePath:$.filePath});let Y=await oQ0($.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){Z0.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{Z0.info("[GitService] Sync request",{clientId:$.clientId,path:$.path});let Y=await aQ0($.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){Z0.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{Z0.info("[GitService] Create PR request",{clientId:$.clientId,path:$.path,title:$.title,baseBranch:$.baseBranch,draft:$.draft});let Y=await rQ0($.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){Z0.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{Z0.debug("[GitService] Default branch request",{clientId:$.clientId,path:$.path});let Y=await QM($.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){Z0.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{Z0.debug("[GitService] Existing PR request",{clientId:$.clientId,path:$.path});let Y=await sQ0($.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){Z0.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{Z0.debug("[GitService] Remote branches request",{clientId:$.clientId,path:$.path});let Y=await tQ0($.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){Z0.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{Z0.info("[GitService] Create branch request",{clientId:$.clientId,path:$.path,branchName:$.branchName,checkout:$.checkout});let Y=await gQ0($.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){Z0.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{Z0.debug("[GitService] Local branches request",{clientId:$.clientId,path:$.path});let Y=await uQ0($.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){Z0.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{Z0.info("[GitService] Checkout branch request",{clientId:$.clientId,path:$.path,branchName:$.branchName});let Y=await mQ0($.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){Z0.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 HK0 from"path";import*as dV from"path";import*as WK0 from"os";import*as cV from"fs";var D1=y(),EW=dV.join(WK0.homedir(),".ccc"),qW=dV.join(EW,"device-tokens.json"),CW=dV.join(EW,"notification-preferences.json");class KK0{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if(!cV.existsSync(EW))cV.mkdirSync(EW,{recursive:!0}),D1.debug("[NotificationStorage] Created .ccc directory:",EW)}catch(Z){throw D1.error("[NotificationStorage] Error ensuring directory:",Z),Z}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let Z=Bun.file(qW);if(await Z.exists()){let J=await Z.text(),$=JSON.parse(J);if($&&typeof $==="object"&&Array.isArray($.tokens)){let X=$;return this.tokensCache=X,D1.debug("[NotificationStorage] Loaded tokens:",{count:X.tokens.length}),X}else if($&&typeof $==="object")return D1.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{D1.error("[NotificationStorage] Completely invalid tokens file format, creating backup");let X=`${qW}.backup.${Date.now()}`;await Bun.write(X,J),D1.error("[NotificationStorage] Backup saved to:",X)}}}catch(Z){D1.error("[NotificationStorage] Error loading tokens:",Z);try{let J=Bun.file(qW);if(await J.exists()){let $=await J.text(),X=`${qW}.backup.${Date.now()}`;await Bun.write(X,$),D1.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(qW,JSON.stringify(Z,null,2)),this.tokensCache=Z,D1.debug("[NotificationStorage] Saved tokens:",{count:Z.tokens.length})}catch(J){throw D1.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,D1.info("[NotificationStorage] Updated device token:",{deviceId:Z,platform:X,hasExpoPushToken:!!$});else Q.tokens.push(G),D1.info("[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),D1.info("[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),D1.info("[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(CW);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,D1.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys(X.preferences).length}),X}else if($&&typeof $==="object")return D1.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{D1.error("[NotificationStorage] Completely invalid preferences file format, creating backup");let X=`${CW}.backup.${Date.now()}`;await Bun.write(X,J),D1.error("[NotificationStorage] Backup saved to:",X)}}}catch(Z){D1.error("[NotificationStorage] Error loading preferences:",Z);try{let J=Bun.file(CW);if(await J.exists()){let $=await J.text(),X=`${CW}.backup.${Date.now()}`;await Bun.write(X,$),D1.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(CW,JSON.stringify(Z,null,2)),this.preferencesCache=Z,D1.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(Z.preferences).length})}catch(J){throw D1.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),D1.info("[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($),D1.info("[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,D1.debug("[NotificationStorage] Cleared cache")}}var T8=new KK0;import{Expo as s$1}from"expo-server-sdk";function t$1(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 j6=y();class zK0{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;getExpo(){if(!this.expo)this.expo=new s$1;return this.expo}isValidToken(Z){return t$1(Z)}async sendNotification(Z,J){if(!this.isValidToken(Z))return j6.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 j6.debug("[ExpoPushClient] Sent notification:",{token:Z.substring(0,20)+"...",status:Q?.status}),Q??null}catch(X){return j6.error("[ExpoPushClient] Error sending notification:",X),null}}async sendBatchNotifications(Z,J){let $=[];for(let K of Z)if(!this.isValidToken(K))j6.warn("[ExpoPushClient] Skipping invalid token:",{token:K.substring(0,20)+"..."});else $.push(K);if($.length===0)return j6.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){j6.error("[ExpoPushClient] Error sending batch chunk:",z)}return j6.info("[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(j6.warn("[ExpoPushClient] Ticket error:",{message:Z.message,details:Z.details}),Z.details?.error==="DeviceNotRegistered"){j6.info("[ExpoPushClient] Removing invalid token:",{token:J.substring(0,20)+"..."});let X=(await T8.getAllTokens()).find((Y)=>Y.expoPushToken===J);if(X)await T8.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;j6.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")j6.debug("[ExpoPushClient] Receipt OK:",{ticketId:K});else if(H.status==="error"){let V=z;if(j6.warn("[ExpoPushClient] Receipt error:",{ticketId:K,message:V.message,details:V.details}),V.details?.error==="DeviceNotRegistered"&&G){let B=(await T8.getAllTokens()).find((U)=>U.expoPushToken===G.token);if(B)j6.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:B.deviceId}),await T8.unregisterToken(B.deviceId)}}this.pendingTickets.delete(K)}}catch(W){j6.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 PW=new zK0;var h1=y(),GK0=200,e$1=900000;class lV extends J1{name="Notification Service";get logPrefix(){return"[Notification]"}claudeAgentService=null;openCodeAgentService=null;receiptCheckInterval;setClaudeAgentService(Z){this.claudeAgentService=Z}setOpenCodeAgentService(Z){this.openCodeAgentService=Z}async onStart(){this.receiptCheckInterval=setInterval(()=>{PW.checkReceipts().catch((Z)=>{h1.error("[Notification] Error checking receipts:",Z)})},e$1),h1.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)),h1.info("[Notification] MQTT handlers registered")}async handleRegisterToken(Z,J){try{let $=await this.parseMessage(J);if(!$)return;let{data:X,profileId:Y}=$;h1.info("[Notification] Register token request:",{deviceId:X.deviceId,platform:X.platform,hasExpoPushToken:!!X.expoPushToken,hasFcmToken:!!X.fcmToken}),await T8.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),h1.info("[Notification] Token registered successfully:",{deviceId:X.deviceId})}catch($){h1.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}=$;h1.debug("[Notification] Get preferences request:",{deviceId:X.deviceId});let Q=await T8.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),h1.debug("[Notification] Sent preferences:",{deviceId:X.deviceId})}catch($){h1.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}=$;h1.info("[Notification] Update preferences request:",{deviceId:X.deviceId,preferences:X.preferences});let Q=await T8.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),h1.info("[Notification] Preferences updated:",{deviceId:X.deviceId})}catch($){h1.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){h1.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"}),h1.debug("[Notification] Sent message notification:",{sessionId:$,title:W})}catch($){h1.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){h1.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"}),h1.info("[Notification] Sent permission notification:",{sessionId:$,action:Y.action})}catch($){h1.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}}return null}buildNotificationTitle(Z){let J=HK0.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(`
2390
+ `).trim(),L=U.length>100?U.substring(0,100)+"...":U,O=V.info.time?.created||0,_=O>1000000000000?O:O*1000,w=new Date(_).toISOString(),j=!1,T=0,N=0,R=0,P=V.info.summary?.diffs||[],c=H.get(F);if(P.length>0){j=!0,G=!0,T=P.length;for(let g of P){if(g.additions!==void 0)N+=g.additions;if(g.deletions!==void 0)R+=g.deletions}}else if(c!==void 0){let g=new Set;for(let H0=c+1;H0<Q.length;H0++){let S0=Q[H0];if(S0.info.role==="user")break;if(!S0.parts)continue;for(let Y0 of S0.parts){if(Y0.type==="patch"&&Array.isArray(Y0.files))for(let X0 of Y0.files)g.add(X0);if(Y0.type==="tool"&&Y0.state?.status==="completed"){let X0=(Y0.tool||"").toLowerCase();if(X0==="apply_patch"){let j0=Y0.state.metadata?.files||[];for(let B0 of j0)if(B0.filePath||B0.relativePath){if(g.add(B0.filePath||B0.relativePath),B0.additions!==void 0)N+=B0.additions;if(B0.deletions!==void 0)R+=B0.deletions}}else if(["write","edit","multi_edit","patch"].includes(X0)){let j0=Y0.state.metadata?.filepath||Y0.state.input?.filePath||Y0.state.input?.file_path||"";if(j0)g.add(j0);if(Y0.state.metadata?.filediff){if(Y0.state.metadata.filediff.additions!==void 0)N+=Y0.state.metadata.filediff.additions;if(Y0.state.metadata.filediff.deletions!==void 0)R+=Y0.state.metadata.filediff.deletions}}}}}if(g.size>0)j=!0,G=!0,T=g.size}z.push({uuid:F,preview:L||"[user message]",fullMessage:U||void 0,timestamp:w,hasFileChanges:j,fileCount:T,linesAdded:j?N:void 0,linesRemoved:j?R:void 0})}return{checkpoints:z,hasAnyFileChanges:G}}async revertToMessage(Z,J,$){let Y=await(await this.ensureServer()).client.session.revert({sessionID:Z,messageID:J,directory:$});return Y.data||Y}async unrevert(Z,J){let X=await(await this.ensureServer()).client.session.unrevert({sessionID:Z,directory:J});return X.data||X}async getCommandsAndAgents(Z){let J=await this.ensureServer(),$={slashCommands:[],agents:[],skills:[]};try{let X=await J.client.command.list({directory:Z}),Y=X.data||X||[];if(Array.isArray(Y))$.slashCommands=Y.filter((Q)=>Q.name).map((Q)=>({name:Q.name,description:Q.description||void 0,source:Q.source||void 0}))}catch(X){f0.debug("[OpenCodeProcessManager] Failed to list commands:",{error:X.message})}try{let X=await J.client.app.agents({directory:Z}),Y=X.data||X||[];if(Array.isArray(Y))$.agents=Y.map((Q)=>Q.name||Q.id||Q).filter(Boolean)}catch(X){f0.debug("[OpenCodeProcessManager] Failed to list agents:",{error:X.message})}try{let X=await J.client.app.skills({directory:Z}),Y=X.data||X||[];if(Array.isArray(Y))$.skills=Y.map((Q)=>Q.name||Q.id||Q).filter(Boolean)}catch(X){f0.debug("[OpenCodeProcessManager] Failed to list skills:",{error:X.message})}return $}async forkAtMessage(Z,J,$){let Y=await(await this.ensureServer()).client.session.fork({sessionID:Z,messageID:J,directory:$});return Y.data||Y}}import*as DM from"path";import*as eW0 from"os";import*as u9 from"fs";var ZK0=y(),UM=DM.join(eW0.homedir(),".ccc"),LM=DM.join(UM,"settings.json");function a$1(){if(!u9.existsSync(UM))u9.mkdirSync(UM,{recursive:!0})}function JK0(){try{if(!u9.existsSync(LM))return{};let Z=u9.readFileSync(LM,"utf-8");return JSON.parse(Z)}catch(Z){return ZK0.warn("[BackendSettings] Failed to read settings:",Z),{}}}function o$1(Z){try{a$1(),u9.writeFileSync(LM,JSON.stringify(Z,null,2),"utf-8")}catch(J){ZK0.error("[BackendSettings] Failed to write settings:",J)}}function OM(Z,J){let $=JK0();$[Z]=J,o$1($)}function _M(Z){return JK0()[Z]}var N0=y();class RW{name="OpenCode Agent Service";running=!1;startedAt;mqttClient=null;sessionsService=null;processManager;worktreeManager;config;totalSessionsCreated=0;totalMessagesProcessed=0;pendingPermissions=new Map;static PENDING_PERMISSION_TTL_MS=3600000;cleanupInterval;getProcessManager(){return this.processManager}constructor(Z){this.config=Z,this.worktreeManager=new KZ,this.processManager=new BM(Z,{onSessionInitialized:this.handleSessionInitialized.bind(this),onTitleGenerated:this.handleTitleGenerated.bind(this),onAssistantMessage:this.handleAssistantMessage.bind(this),onPermissionRequest:this.handlePermissionRequest.bind(this),onQuestionRequest:this.handlePermissionRequest.bind(this),onSessionError:this.handleSessionError.bind(this),onSessionStopped:this.handleSessionStopped.bind(this),onProcessingStarted:this.handleProcessingStarted.bind(this),onProcessingComplete:this.handleProcessingComplete.bind(this),onContextUpdate:this.handleContextUpdate.bind(this)})}async determineWorkingDirectory(Z,J,$,X=!1){try{if(!X)return{path:J,isWorktree:!1};if(!await WZ(J))return{path:J,isWorktree:!1};let Q=await M8(J);if(!Q)return{path:J,isWorktree:!1};let{worktree:W,isNew:K}=await this.worktreeManager.getOrCreateForSession($,Q);return{path:W.path,isWorktree:!0,branch:W.branch}}catch(Y){return N0.error("[OpenCodeAgent] Worktree creation failed, falling back to project path",{error:Y instanceof Error?Y.message:"Unknown error"}),{path:J,isWorktree:!1}}}setMQTTClient(Z){this.mqttClient=Z}setSessionsService(Z){this.sessionsService=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,N0.info("[OpenCodeAgent] Service starting..."),this.mqttClient)this.registerMQTTHandlers();else N0.warn("[OpenCodeAgent] MQTT client not set - handlers will not be registered");if(_M("opencode_enabled"))N0.info("[OpenCodeAgent] OpenCode is enabled, starting server..."),await this.processManager.startServer();else N0.info("[OpenCodeAgent] OpenCode is disabled, server will not start until enabled");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions(),this.cleanupStalePendingPermissions()},300000),N0.info("[OpenCodeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions})}catch(Z){if(N0.error("[OpenCodeAgent] Failed to start",Z),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=void 0;throw this.running=!1,Z}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=void 0;this.pendingPermissions.clear(),await this.processManager.stopAll(),N0.info("[OpenCodeAgent] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("opencode/+/session/start",(Z,J)=>{this.handleSessionStart(J)}),this.mqttClient.subscribe("opencode/+/input/+",(Z,J)=>{let $=Z.split("/")[3]||"";this.handleUserInput($,J)}),this.mqttClient.subscribe("opencode/+/permission/response/+",(Z,J)=>{let $=Z.split("/")[4]||"";this.handlePermissionResponseFromMobile($,J)}),this.mqttClient.subscribe("opencode/+/session/stop/+",(Z,J)=>{let $=Z.split("/")[4]||"";this.handleSessionStop($,J)}),this.mqttClient.subscribe("opencode/+/providers/list",(Z,J)=>{this.handleProvidersList(J)}),this.mqttClient.subscribe("opencode/+/providers/toggle-model",(Z,J)=>{this.handleToggleModel(J)}),this.mqttClient.subscribe("opencode/+/toggle",(Z,J)=>{this.handleToggleOpenCode(J)}),this.mqttClient.subscribe("opencode/+/enabled",(Z,J)=>{this.handleGetEnabled(J)}),this.mqttClient.subscribe("opencode/+/checkpoints/list/+",(Z,J)=>{let $=Z.split("/")[4]||"";this.handleCheckpointList($,J)}),this.mqttClient.subscribe("opencode/+/session/rewind/+",(Z,J)=>{let $=Z.split("/")[4]||"";this.handleRewind($,J)}),N0.info("[OpenCodeAgent] MQTT handlers registered")}async handleSessionStart(Z){let J="",$="";try{let X=await this.parseMessage(Z);if(!X)return;let{data:Y,profileId:Q}=X;J=Q,$=Y.tempId||"",N0.info("[OpenCodeAgent] Session start request:",{profileId:J,tempId:Y.tempId,projectId:Y.projectId,directoryPath:Y.directoryPath,permissionMode:Y.permissionMode,selectedModel:Y.selectedModel});let{path:W,isWorktree:K,branch:z}=await this.determineWorkingDirectory(Y.projectId,Y.directoryPath,Y.tempId,Y.gitWorktreesEnabled??!1),G=await this.processManager.spawnSession(Y.tempId,J,Y.projectId,W,Y.initialMessage||"",Y.permissionMode,Y.selectedModel,Y.agent,Y.attachments,Y.variant,K?{originalPath:Y.directoryPath,worktreePath:W,branch:z}:void 0);this.totalSessionsCreated++}catch(X){if(N0.error("[OpenCodeAgent] Error starting session:",{profileId:J,error:X instanceof Error?X.message:"Unknown error"}),J)this.publishStatus(J,$||"temp_error",{type:"error",error:X instanceof Error?X.message:"Failed to start session",tempId:$,timestamp:Date.now()})}}async handleUserInput(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;let{data:Y,profileId:Q}=X;if($=Q,!Y.message&&(!Y.attachments||Y.attachments.length===0))return;let W=this.processManager.getSession(Y.sessionId);if(!W)try{W=await this.processManager.resumeSession(Y.sessionId,$,Y.projectId,Y.directoryPath,Y.permissionMode,Y.selectedModel,Y.agent,Y.variant),N0.info(`[OpenCodeAgent] Resumed existing session ${Y.sessionId}`)}catch{N0.info(`[OpenCodeAgent] Session ${Y.sessionId} not found in SDK, creating new session`);let{path:K,isWorktree:z,branch:G}=await this.determineWorkingDirectory(Y.projectId,Y.directoryPath,Y.sessionId,Y.gitWorktreesEnabled??!1);W=await this.processManager.spawnSession(Y.sessionId,$,Y.projectId,K,Y.message||"",Y.permissionMode,Y.selectedModel,Y.agent,Y.attachments,Y.variant,z?{originalPath:Y.directoryPath,worktreePath:K,branch:G}:void 0),this.totalSessionsCreated++,this.totalMessagesProcessed++;return}if(Y.selectedModel&&Y.selectedModel!==W.model)W.model=Y.selectedModel,W.providerModel=NW(Y.selectedModel),N0.info("[OpenCodeAgent] Model changed mid-session:",{sessionId:Z,newModel:Y.selectedModel});if(Y.agent&&Y.agent!==W.agent)W.agent=Y.agent;if(Y.variant!==void 0)W.variant=Y.variant||void 0;await this.processManager.sendPrompt(W,Y.message||"",Y.attachments),this.totalMessagesProcessed++}catch(X){N0.error("[OpenCodeAgent] 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;$=Q.data,X=$.requestId,Y=Q.profileId;let W=this.pendingPermissions.get(X),K=W?._opencode_question,z=this.processManager.getSession(Z);if(!z){N0.info(`[OpenCodeAgent] Session ${Z} not in memory, attempting resume for permission response`);let G=await b4.getPermission(X);N0.info("[OpenCodeAgent] Stored permission lookup:",{requestId:X,found:!!G,projectPath:G?.projectPath});let H=G?.projectPath;if(H)try{await this.processManager.resumeSession(Z,Y,"",H),N0.info(`[OpenCodeAgent] Resumed session ${Z} for permission response`)}catch(V){N0.warn(`[OpenCodeAgent] Could not resume session ${Z}:`,{error:V instanceof Error?V.message:"Unknown error"})}else N0.warn(`[OpenCodeAgent] No directoryPath available to resume session ${Z}`)}else N0.info(`[OpenCodeAgent] Session ${Z} already in memory, status: ${z.status}`);if($.approved&&$.answers&&Object.keys($.answers).length>0)await this.processManager.sendPermissionResponse(Z,{request_id:X,behavior:"allow",updatedInput:{answers:$.answers},_opencode_question:K});else if($.approved)await this.processManager.sendPermissionResponse(Z,{request_id:X,behavior:"allow",updatedInput:W?.params,_opencode_question:K,alwaysAllow:!!$.addToAllowedTools});else{let G=$.denyMessage||"Permission denied by user",H=$.hardDeny!==!1;if(await this.processManager.sendPermissionResponse(Z,{request_id:X,behavior:"deny",message:G,_opencode_question:K}),H){let V=Y;setTimeout(()=>{this.processManager.stopSession(Z),this.publishStatus(V,Z,{type:"session_stopped",reason:"permission_denied",message:G,timestamp:Date.now()})},100)}}if(W)this.pendingPermissions.delete(X);b4.removePermission(X).catch(()=>{})}catch(Q){if(N0.error("[OpenCodeAgent] 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),b4.removePermission(X).catch(()=>{})}}async handleSessionStop(Z,J){let X=(await this.parseMessage(J))?.profileId||"";N0.info("[OpenCodeAgent] Session stop request:",{profileId:X,sessionId:Z});try{await this.processManager.stopSession(Z)}catch(Y){N0.error("[OpenCodeAgent] Failed to stop session",{sessionId:Z,error:Y})}}async handleProvidersList(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let X=await this.processManager.getProviders();this.publishProviderResponse(J,{providers:X.providers,connected:X.connected,defaults:X.defaults,blacklists:X.blacklists})}catch($){if(N0.error("[OpenCodeAgent] Error listing providers:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishProviderResponse(J,{error:$ instanceof Error?$.message:"Failed to list providers"})}}async handleToggleModel(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;let{data:X,profileId:Y}=$;J=Y;let{providerId:Q,modelId:W,enabled:K}=X;if(!Q||!W){this.publishProviderResponse(J,{error:"providerId and modelId are required"});return}let z=await this.processManager.getAnyServer(),G=await z.client.global.config.get(),F=((G.data||G)?.provider?.[Q]||{}).blacklist||[],B;if(K)B=F.filter((U)=>U!==W);else B=F.includes(W)?F:[...F,W];await z.client.global.config.update({config:{provider:{[Q]:{blacklist:B}}}}),this.publishProviderResponse(J,{success:!0,providerId:Q,modelId:W,enabled:K})}catch($){if(N0.error("[OpenCodeAgent] Error toggling model:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishProviderResponse(J,{error:$ instanceof Error?$.message:"Failed to toggle model"})}}async handleToggleOpenCode(Z){let J="";try{let $=await this.parseMessage(Z);if(!$)return;J=$.profileId;let{enabled:X}=$.data;if(X)N0.info("[OpenCodeAgent] Enabling OpenCode, starting server..."),await this.processManager.startServer(),OM("opencode_enabled",!0);else N0.info("[OpenCodeAgent] Disabling OpenCode, stopping server..."),OM("opencode_enabled",!1),await this.processManager.stopAll();this.publishToggleResponse(J,{enabled:!!X})}catch($){if(N0.error("[OpenCodeAgent] Error toggling OpenCode:",{profileId:J,error:$ instanceof Error?$.message:"Unknown error"}),J)this.publishToggleResponse(J,{enabled:!1,error:$ instanceof Error?$.message:"Failed to toggle OpenCode"})}}async handleGetEnabled(Z){let J=await this.parseMessage(Z);if(!J)return;let $=J.profileId,X=_M("opencode_enabled")||!1;this.publishToggleResponse($,{enabled:X})}publishToggleResponse(Z,J){if(!this.mqttClient)return;let $=`opencode/${Z}/toggle/response`;this.publishEncrypted($,J,Z).catch((X)=>{N0.error("[OpenCodeAgent] Failed to publish toggle response",{error:X instanceof Error?X.message:"Unknown error"})})}publishProviderResponse(Z,J){if(!this.mqttClient)return;let $=`opencode/${Z}/providers/response`;this.publishEncrypted($,J,Z).catch((X)=>{N0.error("[OpenCodeAgent] Failed to publish provider response",{error:X instanceof Error?X.message:"Unknown error"})})}handleSessionInitialized(Z,J){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,worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch,slashCommands:[],agents:[],skills:[],timestamp:Date.now()}),this.processManager.getCommandsAndAgents(Z.directoryPath).then(({slashCommands:$,agents:X,skills:Y})=>{if($.length||X.length||Y.length)this.publishStatus(Z.userId,Z.sessionId,{type:"commands_updated",sessionId:Z.sessionId,slashCommands:$,agents:X,skills:Y,timestamp:Date.now()})}).catch(($)=>{N0.debug("[OpenCodeAgent] Failed to fetch commands/agents/skills:",{error:$.message})}),this.sessionsService){let $=Z.worktreePath||Z.directoryPath;this.sessionsService.notifySessionCreated(Z.directoryPath,$).catch(()=>{}),this.sessionsService.notifyOpenCodeSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"OpenCode Session",status:Z.status}).catch(()=>{})}}handleTitleGenerated(Z,J){if(this.publishStatus(Z.userId,Z.sessionId,{type:"title_generated",title:J,timestamp:Date.now()}),this.sessionsService&&Z.sessionId)this.sessionsService.notifyOpenCodeSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:J,status:Z.status}).catch(()=>{})}handleAssistantMessage(Z,J){if(this.totalMessagesProcessed++,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(),...J._opencode_question&&{_opencode_question:!0}}),b4.addPermission({requestId:J.request_id,sessionId:Z.sessionId,projectPath:Z.directoryPath,action:J.action,params:J.params,createdAt:new Date().toISOString()}).catch(()=>{});let $=`opencode/${Z.userId}/permission/request/${Z.sessionId}`,X={request_id:J.request_id,action:J.action,params:J.params};N0.info("[OpenCodeAgent] Publishing permission request:",{topic:$,action:J.action,params:JSON.stringify(J.params)}),this.publishEncrypted($,X,Z.userId).catch((Y)=>{N0.error("[OpenCodeAgent] Failed to publish permission request",{error:Y instanceof Error?Y.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.notifyOpenCodeSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"OpenCode Session",status:"stopped"}).catch(()=>{})}}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){if(this.publishStatus(Z.userId,Z.sessionId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifyOpenCodeSessionUpdate(Z.directoryPath,{sessionId:Z.sessionId,title:Z.title||"OpenCode Session",status:"idle"}).catch(()=>{})}}handleContextUpdate(Z,J){if(Z.sessionId)this.publishContextUpdate(Z.userId,Z.sessionId,J)}publishStatus(Z,J,$){if(!this.mqttClient)return;let X=`opencode/${Z}/status/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{N0.error("[OpenCodeAgent] Failed to publish status",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishOutput(Z,J,$){if(!this.mqttClient)return;let X=`opencode/${Z}/output/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{N0.error("[OpenCodeAgent] Failed to publish output",{error:Y instanceof Error?Y.message:"Unknown error"})})}publishContextUpdate(Z,J,$){if(!this.mqttClient)return;let X=`opencode/${Z}/context/${J}`;this.publishEncrypted(X,$,Z).catch((Y)=>{N0.error("[OpenCodeAgent] Failed to publish context",{error:Y instanceof Error?Y.message:"Unknown error"})})}async handleCheckpointList(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{limit:Y,directoryPath:Q}=X.data,W=await this.processManager.getCheckpoints(Z,Q||"",Y||5),K=`opencode/${$}/checkpoints/response/${Z}`;await this.publishEncrypted(K,{sessionId:Z,checkpoints:W.checkpoints,hasAnyFileChanges:W.hasAnyFileChanges},$)}catch(X){if(N0.error("[OpenCodeAgent] Error handling checkpoint list:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`opencode/${$}/checkpoints/response/${Z}`;await this.publishEncrypted(Y,{sessionId:Z,checkpoints:[],hasAnyFileChanges:!1,error:X instanceof Error?X.message:"Failed to get checkpoints"},$)}}}async handleRewind(Z,J){let $="";try{let X=await this.parseMessage(J);if(!X)return;$=X.profileId;let{checkpointUuid:Y,mode:Q,directoryPath:W}=X.data,K=W||"",z;if(Q==="conversation_only")z=(await this.processManager.forkAtMessage(Z,Y,K))?.id;else if(Q==="both")await this.processManager.revertToMessage(Z,Y,K),z=(await this.processManager.forkAtMessage(Z,Y,K))?.id;let G=`opencode/${$}/rewind/response/${Z}`;await this.publishEncrypted(G,{type:"rewind_complete",sessionId:Z,checkpointUuid:Y,mode:Q,newSessionId:z},$)}catch(X){if(N0.error("[OpenCodeAgent] Error handling rewind:",{profileId:$,sessionId:Z,error:X instanceof Error?X.message:"Unknown error"}),$){let Y=`opencode/${$}/rewind/response/${Z}`;await this.publishEncrypted(Y,{type:"rewind_failed",sessionId:Z,error:X instanceof Error?X.message:"Rewind failed"},$)}}}async parseMessage(Z){try{let J=JSON.parse(Z.toString());if(h0.isEncryptedEnvelope(J)){let $=J.c;if(!$)return null;let X=h0.getClientKey($);if(!X)return null;let Y=await h0.decrypt(X,J);return{data:JSON.parse(Y),profileId:$}}return N0.warn("[OpenCodeAgent] Received unencrypted message \u2014 dropping"),null}catch(J){return N0.warn("[OpenCodeAgent] Failed to parse message",{error:J}),null}}async publishEncrypted(Z,J,$){if(!this.mqttClient)return;if(!$||!h0.hasKey($)){N0.warn(`[OpenCodeAgent] No encryption key for profile ${$} \u2014 dropping message on ${Z}`);return}let X=h0.getClientKey($),Y=await h0.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>RW.PENDING_PERMISSION_TTL_MS)this.pendingPermissions.delete(J),b4.removePermission(J).catch(()=>{})}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.processManager.getSessionCount(),activeServers:this.processManager.getServerCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}async listSessions(Z){let J=await this.processManager.listSessions(Z),$=this.processManager.getSessionMessageCounts(Z),X=[];for(let Y of J){let Q,W;try{let K=await this.worktreeManager.getWorktreeForSession(Y.id,Z);if(K)Q=K.path,W=K.branch}catch{}X.push({sessionId:Y.id,title:Y.title||"OpenCode Session",lastActivity:new Date(Y.time?.updated||Y.time?.created||0).toISOString(),messageCount:$.get(Y.id)||0,worktreePath:Q,worktreeBranch:W})}return X}async getSessionMessages(Z,J){return this.processManager.getSessionMessages(Z,J)}getActiveSessions(){return this.processManager.getAllSessions().filter((Z)=>Z.sessionId).map((Z)=>({sessionId:Z.sessionId,projectPath:Z.directoryPath,status:Z.status,title:Z.title,messageCount:Z.messageCount,lastActivity:Z.lastActivity.toISOString(),worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch}))}}import*as L1 from"fs/promises";import*as wM from"fs";import*as r1 from"path";import*as zZ from"fs/promises";var rX=y(),$K0=10485760;async function U1(Z,J={}){let{maxSize:$=$K0,encoding:X="utf-8",logWarnings:Y=!0}=J;try{let Q=await zZ.stat(Z);if(!Q.isFile()){if(Y)rX.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Q.size>$){if(Y)rX.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Q.size,maxSize:$});return null}return await zZ.readFile(Z,X)}catch(Q){if(Q.code!=="ENOENT"&&Y)rX.debug("[SafeFS] Error reading file",{filePath:Z,error:Q});return null}}async function XK0(Z,J={}){let{maxSize:$=$K0,logWarnings:X=!0}=J;try{let Y=await zZ.stat(Z);if(!Y.isFile()){if(X)rX.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Y.size>$){if(X)rX.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Y.size,maxSize:$});return null}return await zZ.readFile(Z)}catch(Y){if(Y.code!=="ENOENT"&&X)rX.debug("[SafeFS] Error reading file",{filePath:Z,error:Y});return null}}async function Z6(Z){try{return(await zZ.stat(Z)).isDirectory()}catch{return!1}}async function d9(Z){try{return await zZ.stat(Z)}catch{return null}}var c9=y();class gV{validatePath(Z,J){try{let $=r1.resolve(Z),X=r1.resolve($,J);if(!(X===$||X.startsWith($+r1.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};try{let Q=wM.realpathSync(X),W=wM.realpathSync($);if(!(Q===W||Q.startsWith(W+r1.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 L1.stat($.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let Y=await L1.readdir($.fullPath,{withFileTypes:!0}),Q=await Promise.all(Y.map(async(W)=>{let K=r1.join($.fullPath,W.name);try{let z=await L1.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 c9.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 d9($.fullPath);if(!X||!X.isFile())return{content:"",size:0,error:"Path is not a file"};let Y=await U1($.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 c9.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=r1.dirname(X.fullPath);return await L1.mkdir(Y,{recursive:!0}),await L1.writeFile(X.fullPath,$,"utf-8"),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return c9.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 L1.access($.fullPath),{success:!1,error:"File already exists"}}catch{}let X=r1.basename(J);if(!this.isValidFilename(X))return{success:!1,error:"Invalid filename"};let Y=r1.dirname($.fullPath);return await L1.mkdir(Y,{recursive:!0}),await L1.writeFile($.fullPath,"","utf-8"),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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=r1.basename(J);if(!this.isValidFilename(X))return{success:!1,error:"Invalid directory name"};try{if((await L1.stat($.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await L1.mkdir($.fullPath,{recursive:!0}),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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 L1.stat($.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await L1.unlink($.fullPath),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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===r1.resolve(Z))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await L1.stat($.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await L1.rm($.fullPath,{recursive:!0,force:!0}),{success:!0}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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 L1.access($.fullPath),!0}catch{return!1}}async getStats(Z,J){let $=this.validatePath(Z,J);if(!$.valid)return null;try{let X=await L1.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 d9($.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 XK0($.fullPath,{maxSize:Y});if(Q===null)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Failed to read file"};let W=this.getMimeType(r1.basename(J));return{content:Q,size:Number(X.size),mimeType:W}}catch(X){let Y=X instanceof Error?X.message:"Unknown error";return c9.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=r1.basename(J);if(!this.isValidFilename(Y))return{success:!1,error:"Invalid filename"};let Q=r1.dirname(X.fullPath);return await L1.mkdir(Q,{recursive:!0}),await L1.writeFile(X.fullPath,$),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return c9.error("[FileManager] writeFileBinary error",{error:Q,path:X.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}getMimeType(Z){let J=r1.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 jM from"path";var J6=y(),sX=51200,YK0=50,r$1=60000,QK0=300000;class mV extends J1{name="File Browser Service";get logPrefix(){return"[FileBrowser]"}fileManager;fileSaveOperations=new Map;binaryUploadOperations=new Map;staleOpCleanupInterval=null;constructor(){super();this.fileManager=new gV}async onStart(){this.staleOpCleanupInterval=setInterval(()=>{this.cleanupStaleOperations()},r$1)}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)}),J6.info("[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){J6.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/sX));for(let K=0;K<W;K++){let z=K*sX,G=Math.min(z+sX,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(YK0)}this.requestsHandled++}catch(J){J6.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){J6.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){J6.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){J6.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){J6.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){J6.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)J6.error("[FileBrowser] Binary upload write failed",{error:G.error});else this.requestsHandled++,J6.info("[FileBrowser] Binary upload completed",{path:$.relativePath,size:z.length})}}catch(J){J6.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:jM.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/sX)),z=jM.basename($.relativePath);for(let G=0;G<K;G++){let H=G*sX,V=Math.min(H+sX,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(YK0)}this.requestsHandled++,J6.info("[FileBrowser] Binary download completed",{path:$.relativePath,size:Q.size,chunks:K})}catch(J){J6.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>QK0)J6.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>QK0)J6.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 Z0=y();class uV extends J1{name="Git Service";get logPrefix(){return"[GitService]"}worktreeManager;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){super();this.worktreeManager=new KZ}async onStart(){if(this.ghAuthResult=await CQ0(),!this.ghAuthResult.authenticated)Z0.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else{Z0.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username,gitProtocol:this.ghAuthResult.gitProtocol});let Z=await PQ0();if(!Z.success)Z0.warn("[GitService] Could not sync gh config git_protocol",{error:Z.error});let J=await IQ0();if(!J.success)Z0.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)}),Z0.info("[GitService] MQTT handlers registered")}async handleOrgsRequest(Z){try{let J=await this.parseMessage(Z);if(!J)return;let{data:$,profileId:X}=J;if(Z0.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 XM(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(J){Z0.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(Z0.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 CV($.org,$.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${Y}/response`,W,X),this.requestsHandled++}catch(J){Z0.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(Z0.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 SQ0($.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),Z0.debug("[GitService] Sent search results",{source:W,count:Q.length,isComplete:K})},$.limit||50),this.requestsHandled++}catch(J){Z0.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(Z0.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 yQ0($.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){Z0.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(Z0.info("[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 kQ0($.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){Z0.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{Z0.debug("[GitService] Is-repo request",{clientId:$.clientId,path:$.path});let Y=await WZ($.path),Q;if(Y){let[W,K,z]=await Promise.all([M8($.path),fJ($.path),lQ0($.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){Z0.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{Z0.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){Z0.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;Z0.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){Z0.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;Z0.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){Z0.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{Z0.debug("[GitService] Status request",{clientId:$.clientId,path:$.path});let Q={success:!0,status:await YM($.path),timestamp:Date.now()};await this.publishResponse(`git/status/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z0.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{Z0.debug("[GitService] Diff request",{clientId:$.clientId,path:$.path,file:$.file,staged:$.staged});let Y=await vQ0($.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){Z0.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{Z0.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 YM(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){Z0.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){Z0.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{Z0.debug("[GitService] Stage request",{clientId:$.clientId,path:$.path,files:$.files}),await hQ0($.path,$.files);let Y={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${$.clientId}/response`,Y,X),this.requestsHandled++}catch(Y){Z0.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{Z0.debug("[GitService] Unstage request",{clientId:$.clientId,path:$.path,files:$.files}),await fQ0($.path,$.files);let Y={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${$.clientId}/response`,Y,X),this.requestsHandled++}catch(Y){Z0.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{Z0.info("[GitService] Commit request",{clientId:$.clientId,path:$.path,signoff:$.signoff});let Q={success:!0,commit:await bQ0($.path,$.message,$.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z0.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{Z0.debug("[GitService] Unpushed commits request",{clientId:$.clientId,path:$.path});let Y=await pX($.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){Z0.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{Z0.info("[GitService] Push request",{clientId:$.clientId,path:$.path,force:$.force});let Y=await pQ0($.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){Z0.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{Z0.info("[GitService] History request",{clientId:$.clientId,path:$.path,limit:$.limit});let Y=await iQ0($.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){Z0.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{Z0.debug("[GitService] Commit details request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash});let Q={success:!0,commit:await nQ0($.path,$.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${$.clientId}/response`,Q,X),this.requestsHandled++}catch(Y){Z0.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{Z0.debug("[GitService] Commit file diff request",{clientId:$.clientId,path:$.path,commitHash:$.commitHash,filePath:$.filePath});let Y=await oQ0($.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){Z0.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{Z0.info("[GitService] Sync request",{clientId:$.clientId,path:$.path});let Y=await aQ0($.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){Z0.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{Z0.info("[GitService] Create PR request",{clientId:$.clientId,path:$.path,title:$.title,baseBranch:$.baseBranch,draft:$.draft});let Y=await rQ0($.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){Z0.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{Z0.debug("[GitService] Default branch request",{clientId:$.clientId,path:$.path});let Y=await QM($.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){Z0.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{Z0.debug("[GitService] Existing PR request",{clientId:$.clientId,path:$.path});let Y=await sQ0($.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){Z0.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{Z0.debug("[GitService] Remote branches request",{clientId:$.clientId,path:$.path});let Y=await tQ0($.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){Z0.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{Z0.info("[GitService] Create branch request",{clientId:$.clientId,path:$.path,branchName:$.branchName,checkout:$.checkout});let Y=await gQ0($.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){Z0.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{Z0.debug("[GitService] Local branches request",{clientId:$.clientId,path:$.path});let Y=await uQ0($.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){Z0.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{Z0.info("[GitService] Checkout branch request",{clientId:$.clientId,path:$.path,branchName:$.branchName});let Y=await mQ0($.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){Z0.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 HK0 from"path";import*as dV from"path";import*as WK0 from"os";import*as cV from"fs";var D1=y(),EW=dV.join(WK0.homedir(),".ccc"),qW=dV.join(EW,"device-tokens.json"),CW=dV.join(EW,"notification-preferences.json");class KK0{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if(!cV.existsSync(EW))cV.mkdirSync(EW,{recursive:!0}),D1.debug("[NotificationStorage] Created .ccc directory:",EW)}catch(Z){throw D1.error("[NotificationStorage] Error ensuring directory:",Z),Z}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let Z=Bun.file(qW);if(await Z.exists()){let J=await Z.text(),$=JSON.parse(J);if($&&typeof $==="object"&&Array.isArray($.tokens)){let X=$;return this.tokensCache=X,D1.debug("[NotificationStorage] Loaded tokens:",{count:X.tokens.length}),X}else if($&&typeof $==="object")return D1.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{D1.error("[NotificationStorage] Completely invalid tokens file format, creating backup");let X=`${qW}.backup.${Date.now()}`;await Bun.write(X,J),D1.error("[NotificationStorage] Backup saved to:",X)}}}catch(Z){D1.error("[NotificationStorage] Error loading tokens:",Z);try{let J=Bun.file(qW);if(await J.exists()){let $=await J.text(),X=`${qW}.backup.${Date.now()}`;await Bun.write(X,$),D1.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(qW,JSON.stringify(Z,null,2)),this.tokensCache=Z,D1.debug("[NotificationStorage] Saved tokens:",{count:Z.tokens.length})}catch(J){throw D1.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,D1.info("[NotificationStorage] Updated device token:",{deviceId:Z,platform:X,hasExpoPushToken:!!$});else Q.tokens.push(G),D1.info("[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),D1.info("[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),D1.info("[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(CW);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,D1.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys(X.preferences).length}),X}else if($&&typeof $==="object")return D1.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{D1.error("[NotificationStorage] Completely invalid preferences file format, creating backup");let X=`${CW}.backup.${Date.now()}`;await Bun.write(X,J),D1.error("[NotificationStorage] Backup saved to:",X)}}}catch(Z){D1.error("[NotificationStorage] Error loading preferences:",Z);try{let J=Bun.file(CW);if(await J.exists()){let $=await J.text(),X=`${CW}.backup.${Date.now()}`;await Bun.write(X,$),D1.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(CW,JSON.stringify(Z,null,2)),this.preferencesCache=Z,D1.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(Z.preferences).length})}catch(J){throw D1.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),D1.info("[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($),D1.info("[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,D1.debug("[NotificationStorage] Cleared cache")}}var T8=new KK0;import{Expo as s$1}from"expo-server-sdk";function t$1(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 j6=y();class zK0{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;getExpo(){if(!this.expo)this.expo=new s$1;return this.expo}isValidToken(Z){return t$1(Z)}async sendNotification(Z,J){if(!this.isValidToken(Z))return j6.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 j6.debug("[ExpoPushClient] Sent notification:",{token:Z.substring(0,20)+"...",status:Q?.status}),Q??null}catch(X){return j6.error("[ExpoPushClient] Error sending notification:",X),null}}async sendBatchNotifications(Z,J){let $=[];for(let K of Z)if(!this.isValidToken(K))j6.warn("[ExpoPushClient] Skipping invalid token:",{token:K.substring(0,20)+"..."});else $.push(K);if($.length===0)return j6.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){j6.error("[ExpoPushClient] Error sending batch chunk:",z)}return j6.info("[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(j6.warn("[ExpoPushClient] Ticket error:",{message:Z.message,details:Z.details}),Z.details?.error==="DeviceNotRegistered"){j6.info("[ExpoPushClient] Removing invalid token:",{token:J.substring(0,20)+"..."});let X=(await T8.getAllTokens()).find((Y)=>Y.expoPushToken===J);if(X)await T8.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;j6.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")j6.debug("[ExpoPushClient] Receipt OK:",{ticketId:K});else if(H.status==="error"){let V=z;if(j6.warn("[ExpoPushClient] Receipt error:",{ticketId:K,message:V.message,details:V.details}),V.details?.error==="DeviceNotRegistered"&&G){let B=(await T8.getAllTokens()).find((U)=>U.expoPushToken===G.token);if(B)j6.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:B.deviceId}),await T8.unregisterToken(B.deviceId)}}this.pendingTickets.delete(K)}}catch(W){j6.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 PW=new zK0;var h1=y(),GK0=200,e$1=900000;class lV extends J1{name="Notification Service";get logPrefix(){return"[Notification]"}claudeAgentService=null;openCodeAgentService=null;receiptCheckInterval;setClaudeAgentService(Z){this.claudeAgentService=Z}setOpenCodeAgentService(Z){this.openCodeAgentService=Z}async onStart(){this.receiptCheckInterval=setInterval(()=>{PW.checkReceipts().catch((Z)=>{h1.error("[Notification] Error checking receipts:",Z)})},e$1),h1.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)),h1.info("[Notification] MQTT handlers registered")}async handleRegisterToken(Z,J){try{let $=await this.parseMessage(J);if(!$)return;let{data:X,profileId:Y}=$;h1.info("[Notification] Register token request:",{deviceId:X.deviceId,platform:X.platform,hasExpoPushToken:!!X.expoPushToken,hasFcmToken:!!X.fcmToken}),await T8.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),h1.info("[Notification] Token registered successfully:",{deviceId:X.deviceId})}catch($){h1.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}=$;h1.debug("[Notification] Get preferences request:",{deviceId:X.deviceId});let Q=await T8.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),h1.debug("[Notification] Sent preferences:",{deviceId:X.deviceId})}catch($){h1.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}=$;h1.info("[Notification] Update preferences request:",{deviceId:X.deviceId,preferences:X.preferences});let Q=await T8.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),h1.info("[Notification] Preferences updated:",{deviceId:X.deviceId})}catch($){h1.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){h1.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"}),h1.debug("[Notification] Sent message notification:",{sessionId:$,title:W})}catch($){h1.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){h1.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"}),h1.info("[Notification] Sent permission notification:",{sessionId:$,action:Y.action})}catch($){h1.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}}return null}buildNotificationTitle(Z){let J=HK0.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(`
2391
2391
  `);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(`
2392
2392
  `)}if(!J.trim())return null;if(J.length>GK0)J=J.substring(0,GK0)+"...";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 T8.getAllTokens();if($.length===0){h1.debug("[Notification] No registered devices");return}let X=[];for(let Y of $){if(!Y.expoPushToken)continue;if((await T8.getPreferences(Y.deviceId))[Z])X.push(Y.expoPushToken)}if(X.length===0){h1.debug("[Notification] No devices with preference enabled:",{preferenceType:Z});return}await PW.sendBatchNotifications(X,J),h1.debug("[Notification] Sent to devices:",{count:X.length,preferenceType:Z})}catch($){h1.error("[Notification] Error sending to devices:",$)}}getStatus(){let Z=PW.getStats();return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,registeredDevices:0,notificationsSent:Z.notificationsSent,lastNotificationAt:Z.lastNotificationAt}}}import*as HZ from"fs/promises";import*as t1 from"path";import*as MM from"os";var{YAML:XX1}=globalThis.Bun;import*as tX from"fs/promises";import*as eX from"path";import*as VK0 from"os";var ZX1=y();function JX1(){return eX.join(VK0.homedir(),".config","opencode")}function p5(){return eX.join(JX1(),"opencode.json")}function ZY(Z){return eX.join(Z,"opencode.json")}function $X1(Z){let J=Z.replace(/\/\*[\s\S]*?\*\//g,"");return J=J.replace(/(^|[^:])\/\/.*$/gm,"$1"),J}async function s1(Z){try{let J=await tX.readFile(Z,"utf-8"),$=$X1(J);return JSON.parse($)}catch(J){if(J.code==="ENOENT")return{};return ZX1.warn("[OpenCodeConfig] Failed to read config",{configPath:Z,error:J instanceof Error?J.message:"Unknown error"}),{}}}async function N8(Z,J){let $=eX.dirname(Z);await tX.mkdir($,{recursive:!0});let Y={...await s1(Z),...J};await tX.writeFile(Z,JSON.stringify(Y,null,2),"utf-8")}var GZ=y();class pV extends J1{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)}),GZ.info("[SlashCommands] MQTT handlers registered")}getCommandsDir(Z,J,$){if($==="opencode"){if(Z==="global")return t1.join(MM.homedir(),".config","opencode","commands");if(!J)throw Error("Project path is required for project-scoped commands");return t1.join(J,".opencode","commands")}if(Z==="global")return t1.join(MM.homedir(),".claude","commands");if(!J)throw Error("Project path is required for project-scoped commands");return t1.join(J,".claude","commands")}getOpenCodeConfigPath(Z,J){if(Z==="global")return p5();if(!J)throw Error("Project path is required for project-scoped commands");return ZY(J)}async listOpenCodeConfigCommands(Z,J){let $=this.getOpenCodeConfigPath(Z,J),Y=(await s1($)).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 s1(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 s1(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 N8(Q,{...W,command:K})}async deleteOpenCodeConfigCommand(Z,J,$){let X=this.getOpenCodeConfigPath(Z,$),Y=await s1(X),Q=Y.command||{};if(!Q[J])return!1;return delete Q[J],await N8(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=XX1.parse(X)}catch(K){GZ.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:
2393
2393
  `);if(O!==-1){let _=X.slice(O+7);z.hooks=this.parseHooksManually(_)}}}return{frontmatter:Object.keys(z).length>0?z:void 0,body:Y}}if(!Q||typeof Q!=="object")return{body:Y};let W={};if(Q["allowed-tools"])W["allowed-tools"]=String(Q["allowed-tools"]);if(Q["argument-hint"])W["argument-hint"]=String(Q["argument-hint"]);if(Q.description)W.description=String(Q.description);if(Q.model)W.model=String(Q.model);if(Q.context==="fork"||Q.context==="inline")W.context=Q.context;if(Q.agent)W.agent=String(Q.agent);if(Q["disable-model-invocation"]===!0)W["disable-model-invocation"]=!0;if(Q.hooks&&typeof Q.hooks==="object"){if(W.hooks={},Array.isArray(Q.hooks.PreToolUse))W.hooks.PreToolUse=Q.hooks.PreToolUse.map((K)=>({matcher:String(K.matcher||""),hooks:Array.isArray(K.hooks)?K.hooks.map((z)=>({command:String(z.command||"")})):[]}));if(Array.isArray(Q.hooks.PostToolUse))W.hooks.PostToolUse=Q.hooks.PostToolUse.map((K)=>({matcher:String(K.matcher||""),hooks:Array.isArray(K.hooks)?K.hooks.map((z)=>({command:String(z.command||"")})):[]}));if(Array.isArray(Q.hooks.Stop))W.hooks.Stop=Q.hooks.Stop.map((K)=>({command:String(K.command||"")}));if(Object.keys(W.hooks).length===0)delete W.hooks}return{frontmatter:Object.keys(W).length>0?W:void 0,body:Y}}catch(Q){return GZ.warn("[SlashCommands] Failed to parse frontmatter",{error:Q}),{body:Z}}}generateFrontmatter(Z){let J=["---"];if(Z.description)J.push(`description: "${Z.description}"`);if(Z["argument-hint"]){let $=Z["argument-hint"],X=/[<>:{}[\]|&*?#!%@`]/.test($)||$.startsWith("-")||$.startsWith(" ");J.push(`argument-hint: ${X?`"${$.replace(/"/g,"\\\"")}"`:$}`)}if(Z["allowed-tools"])J.push(`allowed-tools: ${Z["allowed-tools"]}`);if(Z.model)J.push(`model: ${Z.model}`);if(Z.context)J.push(`context: ${Z.context}`);if(Z.agent)J.push(`agent: ${Z.agent}`);if(Z["disable-model-invocation"])J.push("disable-model-invocation: true");if(Z.hooks){if(J.push("hooks:"),Z.hooks.PreToolUse&&Z.hooks.PreToolUse.length>0){J.push(" PreToolUse:");for(let $ of Z.hooks.PreToolUse)if(J.push(` - matcher: ${$.matcher}`),$.hooks&&$.hooks.length>0){J.push(" hooks:");for(let X of $.hooks)J.push(` - command: ${X.command}`)}}if(Z.hooks.PostToolUse&&Z.hooks.PostToolUse.length>0){J.push(" PostToolUse:");for(let $ of Z.hooks.PostToolUse)if(J.push(` - matcher: ${$.matcher}`),$.hooks&&$.hooks.length>0){J.push(" hooks:");for(let X of $.hooks)J.push(` - command: ${X.command}`)}}if(Z.hooks.Stop&&Z.hooks.Stop.length>0){J.push(" Stop:");for(let $ of Z.hooks.Stop)J.push(` - command: ${$.command}`)}}return J.push("---"),J.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naarang/ccc",
3
- "version": "3.1.0-beta.6",
3
+ "version": "3.1.0-beta.7",
4
4
  "description": "Code Chat Connect - Control Claude Code from your mobile device",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",