@naarang/ccc 2.1.0-beta.3 → 2.1.1-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/dist/scripts/build-binaries.ts +2 -8
- package/package.json +86 -87
- package/scripts/build-binaries.ts +2 -8
package/dist/index.js
CHANGED
|
@@ -50,7 +50,7 @@ Event: ${b9(Z)}`),!0}return!1}function rC0(Z,J){if(!J?.length)return!1;return tW
|
|
|
50
50
|
`;let K=gc($);$.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",bS0),J.secureEndpoint){nY("Upgrading socket connection to TLS");let V=J.servername||J.host;return dL.connect({...mc(J,"host","path","port"),socket:$,servername:e5.isIP(V)?void 0:V})}return $}$.destroy();let H=new e5.Socket({writable:!1});return H.readable=!0,Z.once("socket",(V)=>{nY("Replaying proxy buffer for failed request"),V.push(G),V.push(null)}),H}}pK.__initStatic();function bS0(Z){Z.resume()}function mc(Z,...J){let X={},$;for($ in Z)if(!J.includes($))X[$]=Z[$];return X}var cS0=32768;function lS0(Z){return new dS0({read(){this.push(Z),this.push(null)}})}function uL(Z){let J;try{J=new URL(Z.url)}catch(z){return y1(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),wZ(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",$=pS0(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),Y=X?mS0:gS0,Q=Z.keepAlive===void 0?!1:Z.keepAlive,W=$?new pK($):new Y.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),K=iS0(Z,Z.httpModule??Y,W);return wZ(Z,K)}function pS0(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some((Y)=>Z.host.endsWith(Y)||Z.hostname.endsWith(Y)))return;else return J}function iS0(Z,J,X){let{hostname:$,pathname:Y,port:Q,protocol:W,search:K}=new URL(Z.url);return function(G){return new Promise((H,V)=>{i9(()=>{let F=lS0(G.body),B={...Z.headers};if(G.body.length>cS0)B["content-encoding"]="gzip",F=F.pipe(uS0());let U=$.startsWith("["),D=J.request({method:"POST",agent:X,headers:B,hostname:U?$.slice(1,-1):$,path:`${Y}${K}`,port:Q,protocol:W,ca:Z.caCerts},(_)=>{_.on("data",()=>{}),_.on("end",()=>{}),_.setEncoding("utf8");let O=_.headers["retry-after"]??null,w=_.headers["x-sentry-rate-limits"]??null;H({statusCode:_.statusCode,headers:{"retry-after":O,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});D.on("error",V),F.pipe(D)})})}}var nS0=new Set(["false","f","n","no","off","0"]),oS0=new Set(["true","t","y","yes","on","1"]);function iK(Z,J){let X=String(Z).toLowerCase();if(nS0.has(X))return!1;if(oS0.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as aS0,sep as rS0}from"path";function dc(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function cL(Z=process.argv[1]?DU(process.argv[1]):process.cwd(),J=rS0==="\\"){let X=J?dc(Z):Z;return($)=>{if(!$)return;let Y=J?dc($):$,{dir:Q,base:W,ext:K}=aS0.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(X)){let H=Q.slice(X.length+1).replace(/\//g,".");return H?`${H}:${z}`:z}return z}}function lL(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(Q0.SENTRY_RELEASE?.id)return Q0.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,X=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,$=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 pL=RW(mU(cL()));var cc=k(f(),1),lc=k(H0(),1);import*as uc from"os";import{threadId as sS0,isMainThread as tS0}from"worker_threads";var eS0=60000;class nK extends ZK{constructor(Z){let J=Z.includeServerName===!1?void 0:Z.serverName||global.process.env.SENTRY_NAME||uc.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)lc.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});n5(X,"node"),A.log(`Initializing Sentry: process: ${process.pid}, thread: ${tS0?"main":`worker-${sS0}`}.`);super(X);if(this.getOptions().enableLogs){if(this._logOnExitFlushListener=()=>{BY(this)},J)this.on("beforeCaptureLog",($)=>{$.attributes={...$.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=N0,X=cc.trace.getTracer(Z,J);return this._tracer=X,X}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(()=>{_0&&A.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??eS0).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_setupIntegrations(){GU(),super._setupIntegrations()}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return xu(this,Z)}}var pc=k(aF(),1);import*as ic from"module";function iL(){if(!wc())return;if(!Q0._sentryEsmLoaderHookRegistered){Q0._sentryEsmLoaderHookRegistered=!0;try{let{addHookMessagePort:Z}=pc.createAddHookMessageChannel();ic.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 oK(){return[rJ(),aJ(),sJ(),tJ(),xL(),eJ(),su(),Xc(),TX(),qX(),MX(),IL(),jX(),hL(),bc(),AX()]}function nL(Z={}){return Zk0(Z,oK)}function Zk0(Z={},J){let X=Jk0(Z,J);if(X.debug===!0)if(_0)A.enable();else y1(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(X.registerEsmLoaderHooks!==!1)iL();if(fu(),u0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===SL))X.integrations.push(kL({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));n5(X,"node-core");let Y=new nK(X);if(u0().setClient(Y),Y.init(),Q0._sentryInjectLoaderHookRegister?.(),A.log(`SDK initialized from ${lY()?"CommonJS":"ESM"}`),Y.startClientReportTracking(),Yk0(),Mu(Y),hu(Y),process.env.VERCEL)process.on("SIGTERM",async()=>{await Y.flush(200)});return Y}function aK(){if(!_0)return;let Z=Cu(),J=["SentryContextManager","SentryPropagator"];if(L1())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))A.error(`You have to set up the ${X}. 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 Jk0(Z,J){let X=Xk0(Z.release),$;if(Z.spotlight===!1)$=!1;else if(typeof Z.spotlight==="string")$=Z.spotlight;else{let z=iK(process.env.SENTRY_SPOTLIGHT,{strict:!0}),G=z===null&&process.env.SENTRY_SPOTLIGHT?process.env.SENTRY_SPOTLIGHT:void 0;$=Z.spotlight===!0?G??!0:z??G}let Y=$k0(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??uL,stackParser:FB(Z.stackParser||pL),release:X,tracesSampleRate:Y,spotlight:$,debug:iK(Z.debug??process.env.SENTRY_DEBUG)},W=Z.integrations,K=Z.defaultIntegrations??J(Q);return{...Q,integrations:eB({defaultIntegrations:K,integrations:W})}}function Xk0(Z){if(Z!==void 0)return Z;let J=lL();if(J!==void 0)return J;return}function $k0(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function Yk0(){if(iK(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=BZ(Z,J);u0().setPropagationContext(X)}}function i0(Z,J){Z.setAttribute(X0,J)}var oL="Http",nc="@opentelemetry_sentry-patched/instrumentation-http",Qk0=a(`${oL}.sentry`,(Z)=>{return new _X(Z)}),Wk0=a(oL,(Z)=>{let J=new ac.HttpInstrumentation({...Z,disableIncomingRequestInstrumentation:!0});try{J._diag=oc.diag.createComponentLogger({namespace:nc}),J.instrumentationName=nc}catch{}return J});function Kk0(Z,J={}){if(typeof Z.spans==="boolean")return Z.spans;if(J.skipOpenTelemetrySetup)return!1;if(!L1(J)&&H7.major>=22)return!1;return!0}var oY=S((Z={})=>{let J=Z.spans??!0,X=Z.disableIncomingRequestSpans,$={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=WX($),W=zX(Y),K=J&&!X;return{name:oL,setup(z){let G=z.getOptions();if(K&&L1(G))W.setup(z)},setupOnce(){let z=u()?.getOptions()||{},G=Kk0(Z,z);Q.setupOnce();let H={breadcrumbs:Z.breadcrumbs,propagateTraceInOutgoingRequests:!G,ignoreOutgoingRequests:Z.ignoreOutgoingRequests};if(Qk0(H),G){let V=zk0(Z);Wk0(V)}},processEvent(z){return W.processEvent(z)}}});function zk0(Z={}){return{ignoreOutgoingRequestHook:(X)=>{let $=kY(X);if(!$)return!1;let Y=Z.ignoreOutgoingRequests;if(Y?.($,X))return!0;return!1},requireParentforOutgoingSpans:!1,requestHook:(X,$)=>{i0(X,"auto.http.otel.http"),Z.instrumentation?.requestHook?.(X,$)},responseHook:(X,$)=>{Z.instrumentation?.responseHook?.(X,$)},applyCustomAttributesOnSpan:(X,$,Y)=>{Z.instrumentation?.applyCustomAttributesOnSpan?.(X,$,Y)}}}var Ql=k(Yl(),1);var Wl="NodeFetch",Bk0=a(Wl,Ql.UndiciInstrumentation,(Z)=>{return Ok0(Z)}),Uk0=a(`${Wl}.sentry`,wX,(Z)=>{return Z}),Lk0=(Z={})=>{return{name:"NodeFetch",setupOnce(){if(_k0(Z,u()?.getOptions()))Bk0(Z);Uk0(Z)}}},rY=S(Lk0);function Dk0(Z,J="/"){let X=`${Z}`;if(X.endsWith("/")&&J.startsWith("/"))return`${X}${J.slice(1)}`;if(!X.endsWith("/")&&!J.startsWith("/"))return`${X}/${J.slice(1)}`;return`${X}${J}`}function _k0(Z,J={}){return typeof Z.spans==="boolean"?Z.spans:!J.skipOpenTelemetrySetup&&L1(J)}function Ok0(Z={}){return{requireParentforSpans:!1,ignoreRequestHook:(X)=>{let $=Dk0(X.origin,X.path),Y=Z.ignoreOutgoingRequests;return!!(Y&&$&&Y($))},startSpanHook:()=>{return{[X0]:"auto.http.otel.node_fetch"}},requestHook:Z.requestHook,responseHook:Z.responseHook}}var Pl=k(Rl(),1);var N1=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;var El="Express";function ck0(Z){i0(Z,"auto.http.otel.express");let J=J0(Z).data,X=J["express.type"];if(X)Z.setAttribute(K0,`${X}.express`);let $=J["express.name"];if(typeof $==="string")Z.updateName($)}function lk0(Z,J){if(R0()===B6())return N1&&A.warn("Isolation scope is still default isolation scope - skipping setting transactionName"),J;if(Z.layerType==="request_handler"){let X=Z.request,$=X.method?X.method.toUpperCase():"GET";R0().setTransactionName(`${$} ${Z.route}`)}return J}var Il=a(El,()=>new Pl.ExpressInstrumentation({requestHook:(Z)=>ck0(Z),spanNameHook:(Z,J)=>lk0(Z,J)})),pk0=()=>{return{name:El,setupOnce(){Il()}}},yl=S(pk0);import*as G2 from"diagnostics_channel";var k1=k(f(),1),$z=k(H1(),1),zp=k(H0(),1),d1=k(p0(),1);import $p from"diagnostics_channel";var tl=k(ll(),1);var eY=(Z)=>{if(typeof Z!=="string")throw TypeError("invalid pattern");if(Z.length>65536)throw TypeError("pattern is too long")};var ek0={"[: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]},Z3=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),Zx0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),pl=(Z)=>Z.join(""),il=(Z,J)=>{let X=J;if(Z.charAt(X)!=="[")throw Error("not in a brace expression");let $=[],Y=[],Q=X+1,W=!1,K=!1,z=!1,G=!1,H=X,V="";Z:while(Q<Z.length){let D=Z.charAt(Q);if((D==="!"||D==="^")&&Q===X+1){G=!0,Q++;continue}if(D==="]"&&W&&!z){H=Q+1;break}if(W=!0,D==="\\"){if(!z){z=!0,Q++;continue}}if(D==="["&&!z){for(let[_,[O,w,j]]of Object.entries(ek0))if(Z.startsWith(_,Q)){if(V)return["$.",!1,Z.length-X,!0];if(Q+=_.length,j)Y.push(O);else $.push(O);K=K||w;continue Z}}if(z=!1,V){if(D>V)$.push(Z3(V)+"-"+Z3(D));else if(D===V)$.push(Z3(D));V="",Q++;continue}if(Z.startsWith("-]",Q+1)){$.push(Z3(D+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){V=D,Q+=2;continue}$.push(Z3(D)),Q++}if(H<Q)return["",!1,0,!1];if(!$.length&&!Y.length)return["$.",!1,Z.length-X,!0];if(Y.length===0&&$.length===1&&/^\\?.$/.test($[0])&&!G){let D=$[0].length===2?$[0].slice(-1):$[0];return[Zx0(D),!1,H-X,!1]}let F="["+(G?"^":"")+pl($)+"]",B="["+(G?"":"^")+pl(Y)+"]";return[$.length&&Y.length?"("+F+"|"+B+")":$.length?F:B,K,H-X,!0]};var V7=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var Jx0=new Set(["!","?","+","*","@"]),nl=(Z)=>Jx0.has(Z),Xx0="(?!(?:^|/)\\.\\.?(?:$|/))",Jz="(?!\\.)",$x0=new Set(["[","."]),Yx0=new Set(["..","."]),Qx0=new Set("().*{}+?[]^$\\!"),Wx0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Y2="[^/]",ol=Y2+"*?",al=Y2+"+?";class H4{type;#J;#X;#G=!1;#$=[];#Y;#B;#Q;#H=!1;#K;#W;#Z=!1;constructor(Z,J,X={}){if(this.type=Z,Z)this.#X=!0;if(this.#Y=J,this.#J=this.#Y?this.#Y.#J:this,this.#K=this.#J===this?X: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.#$.length:0}get hasMagic(){if(this.#X!==void 0)return this.#X;for(let Z of this.#$){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#X=!0}return this.#X}toString(){if(this.#W!==void 0)return this.#W;if(!this.type)return this.#W=this.#$.map((Z)=>String(Z)).join("");else return this.#W=this.type+"("+this.#$.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,X=J.#Y;while(X){for(let $=J.#B+1;!X.type&&$<X.#$.length;$++)for(let Y of Z.#$){if(typeof Y==="string")throw Error("string part in extglob AST??");Y.copyIn(X.#$[$])}J=X,X=J.#Y}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof H4&&J.#Y===this))throw Error("invalid part: "+J);this.#$.push(J)}}toJSON(){let Z=this.type===null?this.#$.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#$.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 X=Z.#$[J];if(!(X instanceof H4&&X.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.#$.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 H4(this.type,Z);for(let X of this.#$)J.copyIn(X);return J}static#D(Z,J,X,$){let Y=!1,Q=!1,W=-1,K=!1;if(J.type===null){let F=X,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(!$.noext&&nl(U)&&Z.charAt(F)==="("){J.push(B),B="";let D=new H4(U,J);F=H4.#D(Z,D,F,$),J.push(D);continue}B+=U}return J.push(B),F}let z=X+1,G=new H4(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(nl(F)&&Z.charAt(z)==="("){G.push(V),V="";let B=new H4(F,G);G.push(B),z=H4.#D(Z,B,z,$);continue}if(F==="|"){G.push(V),V="",H.push(G),G=new H4(null,J);continue}if(F===")"){if(V===""&&J.#$.length===0)J.#Z=!0;return G.push(V),V="",J.push(...H,G),z}V+=F}return J.type=null,J.#X=void 0,J.#$=[Z.substring(X-1)],z}static fromGlob(Z,J={}){let X=new H4(null,void 0,J);return H4.#D(Z,X,0,J),X}toMMPattern(){if(this!==this.#J)return this.#J.toMMPattern();let Z=this.toString(),[J,X,$,Y]=this.toRegExpSource();if(!($||this.#X||this.#K.nocase&&!this.#K.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return X;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.#$.map((F)=>{let[B,U,D,_]=typeof F==="string"?H4.#V(F,this.#X,K):F.toRegExpSource(Z);return this.#X=this.#X||D,this.#G=this.#G||_,B}).join(""),G="";if(this.isStart()){if(typeof this.#$[0]==="string"){if(!(this.#$.length===1&&Yx0.has(this.#$[0]))){let B=$x0,U=J&&B.has(z.charAt(0))||z.startsWith("\\.")&&B.has(z.charAt(2))||z.startsWith("\\.\\.")&&B.has(z.charAt(4)),D=!J&&!Z&&B.has(z.charAt(0));G=U?Xx0:D?Jz:""}}}let H="";if(this.isEnd()&&this.#J.#H&&this.#Y?.type==="!")H="(?:$|\\/)";return[G+z+H,V7(z),this.#X=!!this.#X,this.#G]}let X=this.type==="*"||this.type==="+",$=this.type==="!"?"(?:(?!(?:":"(?:",Y=this.#F(J);if(this.isStart()&&this.isEnd()&&!Y&&this.type!=="!"){let K=this.toString();return this.#$=[K],this.type=null,this.#X=void 0,[K,V7(this.toString()),!1,!1]}let Q=!X||Z||J||!Jz?"":this.#F(!0);if(Q===Y)Q="";if(Q)Y=`(?:${Y})(?:${Q})*?`;let W="";if(this.type==="!"&&this.#Z)W=(this.isStart()&&!J?Jz:"")+al;else{let K=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?Jz:"")+ol+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;W=$+Y+K}return[W,V7(Y),this.#X=!!this.#X,this.#G]}#F(Z){return this.#$.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,X}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#V(Z,J,X=!1){let $=!1,Y="",Q=!1;for(let W=0;W<Z.length;W++){let K=Z.charAt(W);if($){$=!1,Y+=(Qx0.has(K)?"\\":"")+K;continue}if(K==="\\"){if(W===Z.length-1)Y+="\\\\";else $=!0;continue}if(K==="["){let[z,G,H,V]=il(Z,W);if(H){Y+=z,Q=Q||G,W+=H-1,J=J||V;continue}}if(K==="*"){if(X&&Z==="*")Y+=al;else Y+=ol;J=!0;continue}if(K==="?"){Y+=Y2,J=!0;continue}Y+=Wx0(K)}return[Y,V7(Z),!!J,Q]}}var Q2=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var V4=(Z,J,X={})=>{if(eY(J),!X.nocomment&&J.charAt(0)==="#")return!1;return new J3(J,X).match(Z)},Kx0=/^\*+([^+@!?\*\[\(]*)$/,zx0=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),Gx0=(Z)=>(J)=>J.endsWith(Z),Hx0=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},Vx0=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},Fx0=/^\*+\.\*+$/,Bx0=(Z)=>!Z.startsWith(".")&&Z.includes("."),Ux0=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),Lx0=/^\.\*+$/,Dx0=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),_x0=/^\*+$/,Ox0=(Z)=>Z.length!==0&&!Z.startsWith("."),wx0=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",jx0=/^\?+([^+@!?\*\[\(]*)?$/,Mx0=([Z,J=""])=>{let X=el([Z]);if(!J)return X;return J=J.toLowerCase(),($)=>X($)&&$.toLowerCase().endsWith(J)},Ax0=([Z,J=""])=>{let X=Zp([Z]);if(!J)return X;return J=J.toLowerCase(),($)=>X($)&&$.toLowerCase().endsWith(J)},Tx0=([Z,J=""])=>{let X=Zp([Z]);return!J?X:($)=>X($)&&$.endsWith(J)},qx0=([Z,J=""])=>{let X=el([Z]);return!J?X:($)=>X($)&&$.endsWith(J)},el=([Z])=>{let J=Z.length;return(X)=>X.length===J&&!X.startsWith(".")},Zp=([Z])=>{let J=Z.length;return(X)=>X.length===J&&X!=="."&&X!==".."},Jp=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",rl={win32:{sep:"\\"},posix:{sep:"/"}},Cx0=Jp==="win32"?rl.win32.sep:rl.posix.sep;V4.sep=Cx0;var l6=Symbol("globstar **");V4.GLOBSTAR=l6;var Nx0="[^/]",Rx0=Nx0+"*?",Px0="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Ex0="(?:(?!(?:\\/|^)\\.).)*?",Ix0=(Z,J={})=>(X)=>V4(X,Z,J);V4.filter=Ix0;var c6=(Z,J={})=>Object.assign({},Z,J),yx0=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return V4;let J=V4;return Object.assign(($,Y,Q={})=>J($,Y,c6(Z,Q)),{Minimatch:class extends J.Minimatch{constructor(Y,Q={}){super(Y,c6(Z,Q))}static defaults(Y){return J.defaults(c6(Z,Y)).Minimatch}},AST:class extends J.AST{constructor(Y,Q,W={}){super(Y,Q,c6(Z,W))}static fromGlob(Y,Q={}){return J.AST.fromGlob(Y,c6(Z,Q))}},unescape:($,Y={})=>J.unescape($,c6(Z,Y)),escape:($,Y={})=>J.escape($,c6(Z,Y)),filter:($,Y={})=>J.filter($,c6(Z,Y)),defaults:($)=>J.defaults(c6(Z,$)),makeRe:($,Y={})=>J.makeRe($,c6(Z,Y)),braceExpand:($,Y={})=>J.braceExpand($,c6(Z,Y)),match:($,Y,Q={})=>J.match($,Y,c6(Z,Q)),sep:J.sep,GLOBSTAR:l6})};V4.defaults=yx0;var Xp=(Z,J={})=>{if(eY(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return tl.default(Z)};V4.braceExpand=Xp;var Sx0=(Z,J={})=>new J3(Z,J).makeRe();V4.makeRe=Sx0;var kx0=(Z,J,X={})=>{let $=new J3(J,X);if(Z=Z.filter((Y)=>$.match(Y)),$.options.nonull&&!Z.length)Z.push(J);return Z};V4.match=kx0;var sl=/[?*]|[+@!]\(.*?\)|\[|\]/,xx0=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class J3{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(eY(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||Jp,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 X=this.globSet.map((Y)=>this.slashSplit(Y));this.globParts=this.preprocess(X),this.debug(this.pattern,this.globParts);let $=this.globParts.map((Y,Q,W)=>{if(this.isWindows&&this.windowsNoMagicRoot){let K=Y[0]===""&&Y[1]===""&&(Y[2]==="?"||!sl.test(Y[2]))&&!sl.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,$),this.set=$.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 X=0;X<Z.length;X++)for(let $=0;$<Z[X].length;$++)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 X=-1;while((X=J.indexOf("**",X+1))!==-1){let $=X;while(J[$+1]==="**")$++;if($!==X)J.splice(X,$-X)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce((X,$)=>{let Y=X[X.length-1];if($==="**"&&Y==="**")return X;if($===".."){if(Y&&Y!==".."&&Y!=="."&&Y!=="**")return X.pop(),X}return X.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 $=1;$<Z.length-1;$++){let Y=Z[$];if($===1&&Y===""&&Z[0]==="")continue;if(Y==="."||Y==="")J=!0,Z.splice($,1),$--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))J=!0,Z.pop()}let X=0;while((X=Z.indexOf("..",X+1))!==-1){let $=Z[X-1];if($&&$!=="."&&$!==".."&&$!=="**")J=!0,Z.splice(X-1,2),X-=2}}while(J);return Z.length===0?[""]:Z}firstPhasePreProcess(Z){let J=!1;do{J=!1;for(let X of Z){let $=-1;while(($=X.indexOf("**",$+1))!==-1){let Q=$;while(X[Q+1]==="**")Q++;if(Q>$)X.splice($+1,Q-$);let W=X[$+1],K=X[$+2],z=X[$+3];if(W!=="..")continue;if(!K||K==="."||K===".."||!z||z==="."||z==="..")continue;J=!0,X.splice($,1);let G=X.slice(0);G[$]="**",Z.push(G),$--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<X.length-1;Q++){let W=X[Q];if(Q===1&&W===""&&X[0]==="")continue;if(W==="."||W==="")J=!0,X.splice(Q,1),Q--}if(X[0]==="."&&X.length===2&&(X[1]==="."||X[1]===""))J=!0,X.pop()}let Y=0;while((Y=X.indexOf("..",Y+1))!==-1){let Q=X[Y-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let K=Y===1&&X[Y+1]==="**"?["."]:[];if(X.splice(Y-1,2,...K),X.length===0)X.push("");Y-=2}}}}while(J);return Z}secondPhasePreProcess(Z){for(let J=0;J<Z.length-1;J++)for(let X=J+1;X<Z.length;X++){let $=this.partsMatch(Z[J],Z[X],!this.preserveMultipleSlashes);if($){Z[J]=[],Z[X]=$;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,X=!1){let $=0,Y=0,Q=[],W="";while($<Z.length&&Y<J.length)if(Z[$]===J[Y])Q.push(W==="b"?J[Y]:Z[$]),$++,Y++;else if(X&&Z[$]==="**"&&J[Y]===Z[$+1])Q.push(Z[$]),$++;else if(X&&J[Y]==="**"&&Z[$]===J[Y+1])Q.push(J[Y]),Y++;else if(Z[$]==="*"&&J[Y]&&(this.options.dot||!J[Y].startsWith("."))&&J[Y]!=="**"){if(W==="b")return!1;W="a",Q.push(Z[$]),$++,Y++}else if(J[Y]==="*"&&Z[$]&&(this.options.dot||!Z[$].startsWith("."))&&Z[$]!=="**"){if(W==="a")return!1;W="b",Q.push(J[Y]),$++,Y++}else return!1;return Z.length===J.length&&Q}parseNegate(){if(this.nonegate)return;let Z=this.pattern,J=!1,X=0;for(let $=0;$<Z.length&&Z.charAt($)==="!";$++)J=!J,X++;if(X)this.pattern=Z.slice(X);this.negate=J}matchOne(Z,J,X=!1){let $=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),D=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),_=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=D?3:U?0:void 0,j=O?3:_?0:void 0;if(typeof w==="number"&&typeof j==="number"){let[q,R]=[Z[w],J[j]];if(q.toLowerCase()===R.toLowerCase()){if(J[j]=q,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===l6){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]===".."||!$.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),X))return this.debug("globstar found match!",V,K,B),!0;else{if(B==="."||B===".."||!$.dot&&B.charAt(0)==="."){this.debug("dot detected!",Z,V,J,F);break}this.debug("globstar swallow a segment, and continue"),V++}}if(X){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 X;else if(W===z)return Q===K-1&&Z[Q]==="";else throw Error("wtf?")}braceExpand(){return Xp(this.pattern,this.options)}parse(Z){eY(Z);let J=this.options;if(Z==="**")return l6;if(Z==="")return"";let X,$=null;if(X=Z.match(_x0))$=J.dot?wx0:Ox0;else if(X=Z.match(Kx0))$=(J.nocase?J.dot?Vx0:Hx0:J.dot?Gx0:zx0)(X[1]);else if(X=Z.match(jx0))$=(J.nocase?J.dot?Ax0:Mx0:J.dot?Tx0:qx0)(X);else if(X=Z.match(Fx0))$=J.dot?Ux0:Bx0;else if(X=Z.match(Lx0))$=Dx0;let Y=H4.fromGlob(Z,this.options).toMMPattern();if($&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:$});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,X=J.noglobstar?Rx0:J.dot?Px0:Ex0,$=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(""))$.add(H);return typeof G==="string"?xx0(G):G===l6?l6:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==l6||F===l6)return;if(F===void 0)if(V!==void 0&&V!==l6)z[H+1]="(?:\\/|"+X+"\\/)?"+V;else z[H]=X;else if(V===void 0)z[H-1]=F+"(?:\\/|"+X+")?";else if(V!==l6)z[H-1]=F+"(?:\\/|\\/"+X+"\\/)"+V,z[H+1]=l6}),z.filter((G)=>G!==l6).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...$].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 X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let $=this.slashSplit(Z);this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=$[$.length-1];if(!Q)for(let W=$.length-2;!Q&&W>=0;W--)Q=$[W];for(let W=0;W<Y.length;W++){let K=Y[W],z=$;if(X.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return V4.defaults(Z).Minimatch}}V4.AST=H4;V4.Minimatch=J3;V4.escape=Q2;V4.unescape=V7;var Yp="@fastify/otel",hx0="0.8.0",fx0=">=4.0.0 <6",Qp=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],$1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},F7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},Z9="anonymous",x4=Symbol("fastify otel instance"),B7=Symbol("fastify otel request spans"),X3=Symbol("fastify otel request context"),Wp=Symbol("fastify otel addhook original"),Kp=Symbol("fastify otel setnotfound original"),Xz=Symbol("fastify otel ignore path");class W2 extends zp.InstrumentationBase{constructor(Z){super(Yp,hx0,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[Xz]=null,this._logger=k1.diag.createComponentLogger({namespace:Yp}),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 X=V4;this[Xz]=($)=>{if(typeof J==="function")return J($);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)},$p.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)$p.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:fx0,name:"@fastify/otel"},J;function J(X,$,Y){X.decorate(x4,Z),X.decorate(Wp,X.addHook),X.decorate(Kp,X.setNotFoundHandler),X.decorateRequest("opentelemetry",function(){let V=this[X3];return{span:this[B7],tracer:Z.tracer,context:V,inject:(B,U)=>{return k1.propagation.inject(V,B,U)},extract:(B,U)=>{return k1.propagation.extract(V,B,U)}}}),X.decorateRequest(B7,null),X.decorateRequest(X3,null),X.addHook("onRoute",function(H){if(Z[Xz]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of Qp)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[$1.FASTIFY_TYPE]:F7.ROUTE,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:Z9});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[$1.FASTIFY_TYPE]:F7.ROUTE,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:Z9}));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,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route-handler`,[$1.FASTIFY_TYPE]:F7.HANDLER,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:Z9})}),X.addHook("onRequest",function(H,V,F){if(this[x4].isEnabled()===!1)return F();else if(this[x4][Xz]?.({url:H.url,method:H.method})===!0)return this[x4]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=k1.context.active();if(k1.trace.getSpan(B)==null)B=k1.propagation.extract(B,H.headers);let U=$z.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===$z.RPCType.HTTP)U.route=H.routeOptions.url;let D=this[x4].tracer.startSpan("request",{attributes:{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.ROOT]:"@fastify/otel",[d1.ATTR_HTTP_ROUTE]:H.url,[d1.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[X3]=k1.trace.setSpan(B,D),H[B7]=D,k1.context.with(H[X3],()=>{F()})}),X.addHook("onResponse",function(H,V,F){let B=H[B7];if(B!=null)B.setStatus({code:k1.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[d1.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[B7]=null,F()}),X.addHook=K,X.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[B7];if(U!=null){if(V.statusCode<500)U.setStatus({code:k1.SpanStatusCode.OK,message:"OK"});U.setAttributes({[d1.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[B7]=null,B(null,F)}function W(H,V,F,B){let U=H[B7];if(U!=null)U.setStatus({code:k1.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[Wp];if(Qp.includes(H))return F.call(this,H,G(V,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - ${H}`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:Z9}));else return F.call(this,H,V)}function z(H,V){let F=this[Kp];if(typeof H==="function")V=G(H,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:Z9}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:Z9});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:Z9});V=G(V,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:Z9}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[x4],[D]=B;if(U.isEnabled()===!1)return H.call(this,...B);let _=D[X3]??k1.context.active(),O=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??Z9}`,{attributes:V},_);return k1.context.with(k1.trace.setSpan(_,O),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((j)=>{return O.end(),j},(j)=>{return O.setStatus({code:k1.SpanStatusCode.ERROR,message:j.message}),O.recordException(j),O.end(),Promise.reject(j)});return O.end(),w}catch(w){throw O.setStatus({code:k1.SpanStatusCode.ERROR,message:w.message}),O.recordException(w),O.end(),w}},this)}}}}}var I8=k(f(),1),Qz=k(H1(),1),kZ=k(H0(),1),Bp=k(p0(),1);var J9;(function(Z){Z.FASTIFY_NAME="fastify.name";let X="fastify.type";Z.FASTIFY_TYPE=X;let $="hook.name";Z.HOOK_NAME=$;let Y="plugin.name";Z.PLUGIN_NAME=Y})(J9||(J9={}));var $3;(function(Z){Z.MIDDLEWARE="middleware";let X="request_handler";Z.REQUEST_HANDLER=X})($3||($3={}));var Y3;(function(Z){Z.MIDDLEWARE="middleware";let X="request handler";Z.REQUEST_HANDLER=X})(Y3||(Y3={}));var Hp=k(f(),1);var Q3=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function K2(Z,J,X,$={}){let Y=J.startSpan(X,{attributes:$}),Q=Z[Q3]||[];return Q.push(Y),Object.defineProperty(Z,Q3,{enumerable:!1,configurable:!0,value:Q}),Y}function Yz(Z,J){let X=Z[Q3]||[];if(!X.length)return;X.forEach(($)=>{if(J)$.setStatus({code:Hp.SpanStatusCode.ERROR,message:J.message}),$.recordException(J);$.end()}),delete Z[Q3]}function Vp(Z,J,X){let $,Y=void 0;try{if(Y=Z(),Gp(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){$=Q}finally{if(!Gp(Y)){if(J($,Y),$)throw $}return Y}}function Gp(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var bx0="0.1.0",gx0="@sentry/instrumentation-fastify-v3",Fp="anonymous",mx0=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class z2 extends kZ.InstrumentationBase{constructor(Z={}){super(gx0,bx0,Z)}init(){return[new kZ.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($,"send",Z._patchSend());let Q=X,W=Qz.getRPCMetadata(I8.context.active()),K=Q.routeOptions?Q.routeOptions.url:X.routerPath;if(K&&W?.type===Qz.RPCType.HTTP)W.route=K;let z=X.method||"GET";R0().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 X.apply(this,Q);let W=X.name||Z||Fp,K=`${Y3.MIDDLEWARE} - ${W}`,z=Q[1],G=K2(z,Y.tracer,K,{[J9.FASTIFY_TYPE]:$3.MIDDLEWARE,[J9.PLUGIN_NAME]:Z,[J9.HOOK_NAME]:J}),H=$&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){Yz(z),H.apply(this,V)};return I8.context.with(I8.trace.setSpan(I8.context.active(),G),()=>{return Vp(()=>{return X.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:I8.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!$)Yz(z)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function(...$){let Y=$[0],Q=$[1],W=this.pluginName;if(!mx0.has(Y))return J.apply(this,$);let K=typeof $[$.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,$);return Y.addHook("onRequest",J._hookOnRequest()),Y.addHook("preHandler",J._hookPreHandler()),dx0(),J._wrap(Y,"addHook",J._wrapAddHook()),Y}if(Z.errorCodes!==void 0)X.errorCodes=Z.errorCodes;return X.fastify=X,X.default=X,X}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function(X){return function(...Y){let Q=Y[0];if(!Z.isEnabled())return X.apply(this,Y);return kZ.safeExecuteInTheMiddle(()=>{return X.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;Yz(this,W)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function(X,$,Y){if(!Z.isEnabled())return Y();let Q=X,W=Q.routeOptions?.handler||Q.context?.handler,K=W?.name.startsWith("bound ")?W.name.substring(6):W?.name,z=`${Y3.REQUEST_HANDLER} - ${K||this.pluginName||Fp}`,G={[J9.PLUGIN_NAME]:this.pluginName,[J9.FASTIFY_TYPE]:$3.REQUEST_HANDLER,[Bp.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:X.routerPath};if(K)G[J9.FASTIFY_NAME]=K;let H=K2($,Z.tracer,z,G);Up(H);let{requestHook:V}=Z.getConfig();if(V)kZ.safeExecuteInTheMiddle(()=>V(H,{request:X}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return I8.context.with(I8.trace.setSpan(I8.context.active(),H),()=>{Y()})}}}function dx0(){let Z=u();if(Z)Z.on("spanStart",(J)=>{Up(J)})}function Up(Z){let J=J0(Z).data,X=J["fastify.type"];if(J[K0]||!X)return;Z.setAttributes({[X0]:"auto.http.otel.fastify",[K0]:`${X}.fastify`});let $=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof $==="string"){let Y=$.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(Y)}}var Wz="Fastify",Dp=a(`${Wz}.v3`,()=>new z2);function ux0(){let Z=u();if(!Z)return;else return Z.getIntegrationByName(Wz)}function Lp(Z,J,X,$){let Y=ux0()?.getShouldHandleError()||wp;if($==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&$==="onError-hook"){N1&&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,X))V0(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var _p=a(`${Wz}.v5`,()=>{let Z=new W2,J=Z.plugin();return G2.subscribe("fastify.initialization",(X)=>{let $=X.fastify;$?.register(J).after((Y)=>{if(Y)N1&&A.error("Failed to setup Fastify instrumentation",Y);else if(lx0(),$)px0($)})}),G2.subscribe("tracing:fastify.request.handler:error",(X)=>{let{error:$,request:Y,reply:Q}=X;Lp.call(Lp,$,Y,Q,"diagnostics-channel")}),Z}),cx0=({shouldHandleError:Z})=>{let J;return{name:Wz,setupOnce(){J=Z||wp,Dp(),_p()},getShouldHandleError(){return J},setShouldHandleError(X){J=X}}},Op=S((Z={})=>cx0(Z));function wp(Z,J,X){let $=X.statusCode;return $>=500||$<=299}function jp(Z){let J=J0(Z),X=J.description,$=J.data,Y=$["fastify.type"],Q=Y==="hook",W=Y===X?.startsWith("handler -"),K=X==="request"||Y==="request-handler";if($[K0]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[X0]:"auto.http.otel.fastify",[K0]:`${z}.fastify`});let G=$["fastify.name"]||$["plugin.name"]||$["hook.name"];if(typeof G==="string"){let H=G.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(H)}}function lx0(){let Z=u();if(Z)Z.on("spanStart",(J)=>{jp(J)})}function px0(Z){Z.addHook("onRequest",async(J,X)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)jp(Q)}let $=J.routeOptions?.url,Y=J.method||"GET";R0().setTransactionName(`${Y} ${$}`)})}var $i=k(f(),1),Yi=k(Xi(),1);var Qi="Graphql",Wi=a(Qi,Yi.GraphQLInstrumentation,(Z)=>{let J=zi(Z);return{...J,responseHook(X,$){if(i0(X,"auto.graphql.otel.graphql"),$.errors?.length&&!J0(X).status)X.setStatus({code:$i.SpanStatusCode.ERROR});let Q=J0(X).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=q1(X),H=J0(z).data[LX]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute(LX,H);else if(typeof H==="string")z.setAttribute(LX,[H,V]);else z.setAttribute(LX,V);if(!J0(z).data["original-description"])z.setAttribute("original-description",J0(z).description);z.updateName(`${J0(z).data["original-description"]} (${Mv0(H)})`)}}}}),jv0=(Z={})=>{return{name:Qi,setupOnce(){Wi(zi(Z))}}},Ki=S(jv0);function zi(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function Mv0(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 yi=k(Ii(),1);var Si="Kafka",ki=a(Si,()=>new yi.KafkaJsInstrumentation({consumerHook(Z){i0(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){i0(Z,"auto.kafkajs.otel.producer")}})),dv0=()=>{return{name:Si,setupOnce(){ki()}}},xi=S(dv0);var ii=k(pi(),1);var ni="LruMemoizer",oi=a(ni,()=>new ii.LruMemoizerInstrumentation),pv0=()=>{return{name:ni,setupOnce(){oi()}}},ai=S(pv0);var Fn=k(Vn(),1);var Bn="Mongo",Un=a(Bn,()=>new Fn.MongoDBInstrumentation({dbStatementSerializer:Kh0,responseHook(Z){i0(Z,"auto.db.otel.mongo")}}));function Kh0(Z){let J=A2(Z);return JSON.stringify(J)}function A2(Z){if(Array.isArray(Z))return Z.map((J)=>A2(J));if(zh0(Z)){let J={};return Object.entries(Z).map(([X,$])=>[X,A2($)]).reduce((X,$)=>{if(Hh0($))X[$[0]]=$[1];return X},J)}return"?"}function zh0(Z){return typeof Z==="object"&&Z!==null&&!Gh0(Z)}function Gh0(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function Hh0(Z){return Array.isArray(Z)}var Vh0=()=>{return{name:Bn,setupOnce(){Un()}}},Ln=S(Vh0);var vn=k(xn(),1);var hn="Mongoose",fn=a(hn,()=>new vn.MongooseInstrumentation({responseHook(Z){i0(Z,"auto.db.otel.mongoose")}})),Sh0=()=>{return{name:hn,setupOnce(){fn()}}},bn=S(Sh0);var Xo=k(Jo(),1);var $o="Mysql",Yo=a($o,()=>new Xo.MySQLInstrumentation({})),$f0=()=>{return{name:$o,setupOnce(){Yo()}}},Qo=S($f0);var qo=k(To(),1);var Co="Mysql2",No=a(Co,()=>new qo.MySQL2Instrumentation({responseHook(Z){i0(Z,"auto.db.otel.mysql2")}})),yf0=()=>{return{name:Co,setupOnce(){No()}}},Ro=S(yf0);var Ra=k(no(),1),Pa=k(Aa(),1);var Bb0=["get","set","setex"],l2=["get","mget"],Ub0=["set","setex"];function L3(Z,J){return Z.includes(J.toLowerCase())}function p2(Z){if(L3(l2,Z))return"cache.get";else if(L3(Ub0,Z))return"cache.put";else return}function Lb0(Z,J){return J.some((X)=>Z.startsWith(X))}function qa(Z,J){try{if(J.length===0)return;let X=(Y)=>{if(typeof Y==="string"||typeof Y==="number"||Buffer.isBuffer(Y))return[Y.toString()];else if(Array.isArray(Y))return Ta(Y.map((Q)=>X(Q)));else return["<unknown>"]},$=J[0];if(L3(Bb0,Z)&&$!=null)return X($);return Ta(J.map((Y)=>X(Y)))}catch{return}}function Ca(Z,J,X){if(!p2(Z))return!1;for(let $ of J)if(Lb0($,X))return!0;return!1}function Na(Z){let J=(X)=>{try{if(Buffer.isBuffer(X))return X.byteLength;else if(typeof X==="string")return X.length;else if(typeof X==="number")return X.toString().length;else if(X===null||X===void 0)return 0;return JSON.stringify(X).length}catch{return}};return Array.isArray(Z)?Z.reduce((X,$)=>{let Y=J($);return typeof Y==="number"?X!==void 0?X+Y:Y:X},0):J(Z)}function Ta(Z){let J=[],X=($)=>{$.forEach((Y)=>{if(Array.isArray(Y))X(Y);else J.push(Y)})};return X(Z),J}var Mz="Redis",D3={},Ea=(Z,J,X,$)=>{Z.setAttribute(X0,"auto.db.otel.redis");let Y=qa(J,X),Q=p2(J);if(!Y||!Q||!D3.cachePrefixes||!Ca(J,Y,D3.cachePrefixes))return;let W=J0(Z).data["net.peer.name"],K=J0(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=Na($);if(z)Z.setAttribute(hB,z);if(L3(l2,J)&&z!==void 0)Z.setAttribute(xB,z>0);Z.setAttributes({[K0]:Q,[vB]:Y});let G=Y.join(", ");Z.updateName(D3.maxCacheKeyLength?h9(G,D3.maxCacheKeyLength):G)},Db0=a(`${Mz}.IORedis`,()=>{return new Ra.IORedisInstrumentation({responseHook:Ea})}),_b0=a(`${Mz}.Redis`,()=>{return new Pa.RedisInstrumentation({responseHook:Ea})}),Ia=Object.assign(()=>{Db0(),_b0()},{id:Mz}),Ob0=(Z={})=>{return{name:Mz,setupOnce(){D3=Z,Ia()}}},ya=S(Ob0);var Kr=k(Wr(),1);var zr="Postgres",Gr=a(zr,()=>new Kr.PgInstrumentation({requireParentSpan:!0,requestHook(Z){i0(Z,"auto.db.otel.postgres")}})),Hg0=()=>{return{name:zr,setupOnce(){Gr()}}},Hr=S(Hg0);var hX=k(f(),1),Q9=k(H0(),1),x1=k(p0(),1);var Pz="PostgresJs",Vr=[">=3.0.0 <4"],Vg0=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,Rz=Symbol("sentryPostgresConnectionContext"),t2=Symbol.for("sentry.instrumented.postgresjs"),Fr=Symbol.for("sentry.query.from.instrumented.sql"),Br=a(Pz,(Z)=>new Ur({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class Ur extends Q9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",N0,Z)}init(){let Z=new Q9.InstrumentationNodeModuleDefinition("postgres",Vr,(J)=>{try{return this._patchPostgres(J)}catch(X){return N1&&A.error("Failed to patch postgres module:",X),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new Q9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,Vr,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",X=J?Z:Z.default;if(typeof X!=="function")return N1&&A.warn("postgres module does not export a function. Skipping instrumentation."),Z;let $=this,Y=function(...Q){let W=Reflect.construct(X,Q);if(!W||typeof W!=="function")return N1&&A.warn("postgres() did not return a valid instance"),W;return $._instrumentSqlInstance(W)};Object.setPrototypeOf(Y,X),Object.setPrototypeOf(Y.prototype,X.prototype);for(let Q of Object.getOwnPropertyNames(X))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor(X,Q);if(W)Object.defineProperty(Y,Q,W)}if(J)return Y;else return RY(Z,"default",Y),Z}_wrapQueryMethod(Z,J,X){let $=this;return function(...Y){let Q=Reflect.apply(Z,J,Y);if(Q&&typeof Q==="object"&&"handle"in Q)$._wrapSingleQueryHandle(Q,X);return Q}}_wrapCallbackMethod(Z,J,X){let $=this;return function(...Y){let Q=X[Rz];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 $._instrumentSqlInstance(V,Q)});return H}let K=Y.length===1?Y[0]:Y[1],z=function(H){let V=$._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(x1.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(x1.ATTR_SERVER_ADDRESS,J.ATTR_SERVER_ADDRESS);if(J.ATTR_SERVER_PORT!==void 0){let X=parseInt(J.ATTR_SERVER_PORT,10);if(!isNaN(X))Z.setAttribute(x1.ATTR_SERVER_PORT,X)}}_setOperationName(Z,J,X){if(X){Z.setAttribute(x1.ATTR_DB_OPERATION_NAME,X);return}let $=J?.match(Vg0);if($?.[1])Z.setAttribute(x1.ATTR_DB_OPERATION_NAME,$[1].toUpperCase())}_attachConnectionContext(Z,J){let X=Z;if(!X.options||typeof X.options!=="object")return;let $=X.options,Y=$.host?.[0]||"localhost",Q=$.port?.[0]||5432,W={ATTR_DB_NAMESPACE:typeof $.database==="string"&&$.database!==""?$.database:void 0,ATTR_SERVER_ADDRESS:Y,ATTR_SERVER_PORT:String(Q)};J[Rz]=W}_instrumentSqlInstance(Z,J){if(Z[t2])return Z;let X=this,$=new Proxy(Z,{apply(Y,Q,W){let K=Reflect.apply(Y,Q,W);if(K&&typeof K==="object"&&"handle"in K)X._wrapSingleQueryHandle(K,$);return K},get(Y,Q){let W=Y[Q];if(typeof Q!=="string"||typeof W!=="function")return W;if(Q==="unsafe"||Q==="file")return X._wrapQueryMethod(W,Y,$);if(Q==="begin"||Q==="reserve")return X._wrapCallbackMethod(W,Y,$);return W}});if(J)$[Rz]=J;else this._attachConnectionContext(Z,$);return Z[t2]=!0,$[t2]=!0,$}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Fr]=!0;let X=Z.handle,$=this,Y=async function(...Q){if(!$._shouldCreateSpans())return X.apply(this,Q);let W=$._reconstructQuery(Z.strings),K=$._sanitizeSqlQuery(W);return z4({name:K||"postgresjs.query",op:"db"},(z)=>{i0(z,"auto.db.postgresjs"),z.setAttributes({[x1.ATTR_DB_SYSTEM_NAME]:"postgres",[x1.ATTR_DB_QUERY_TEXT]:K});let G=J?J[Rz]:void 0;$._setConnectionAttributes(z,G);let H=$.getConfig(),{requestHook:V}=H;if(V)Q9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),N1&&A.error(`Error in requestHook for ${Pz} integration:`,B)},!0);let F=this;F.resolve=new Proxy(F.resolve,{apply:(B,U,D)=>{try{$._setOperationName(z,K,D?.[0]?.command),z.end()}catch(_){N1&&A.error("Error ending span in resolve callback:",_)}return Reflect.apply(B,U,D)}}),F.reject=new Proxy(F.reject,{apply:(B,U,D)=>{try{z.setStatus({code:A0,message:D?.[0]?.message||"unknown_error"}),z.setAttribute(x1.ATTR_DB_RESPONSE_STATUS_CODE,D?.[0]?.code||"unknown"),z.setAttribute(x1.ATTR_ERROR_TYPE,D?.[0]?.name||"unknown"),$._setOperationName(z,K),z.end()}catch(_){N1&&A.error("Error ending span in reject callback:",_)}return Reflect.apply(B,U,D)}});try{return X.apply(this,Q)}catch(B){throw z.setStatus({code:A0,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return hX.trace.getSpan(hX.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,$)=>$===0?X:`${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,X=Z.Query.prototype.handle;return Z.Query.prototype.handle=async function(...$){if(this[Fr])return X.apply(this,$);if(!J._shouldCreateSpans())return X.apply(this,$);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return z4({name:Q||"postgresjs.query",op:"db"},(W)=>{i0(W,"auto.db.postgresjs"),W.setAttributes({[x1.ATTR_DB_SYSTEM_NAME]:"postgres",[x1.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)Q9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),N1&&A.error(`Error in requestHook for ${Pz} 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){N1&&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:A0,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(x1.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(x1.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){N1&&A.error("Error ending span in reject callback:",U)}return Reflect.apply(V,F,B)}});try{return X.apply(this,$)}catch(V){throw W.setStatus({code:A0,message:V instanceof Error?V.message:"unknown_error"}),W.end(),V}})},Z.Query.prototype.handle.__sentry_original__=X,Z}_unpatchQueryPrototype(Z){if(Z.Query.prototype.handle.__sentry_original__)Z.Query.prototype.handle=Z.Query.prototype.handle.__sentry_original__;return Z}}var Fg0=(Z)=>{return{name:Pz,setupOnce(){Br(Z)}}},Lr=S(Fg0);var r6=k(f(),1);var Or=k(f(),1),Ez=k(H0(),1),O7=k(f(),1);var Bg0=process.env.PRISMA_SHOW_ALL_TRACES==="true",Ug0="00-10-10-00";function Lg0(Z){switch(Z){case"client":return O7.SpanKind.CLIENT;case"internal":default:return O7.SpanKind.INTERNAL}}var Dg0=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=O7.trace.getSpanContext(Z??O7.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return Ug0}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),X=new Map,$=Z.filter((Y)=>Y.parentId===null);for(let Y of $)wr(J,Y,Z,X,this.ignoreSpanTypes)}getActiveContext(){return O7.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!Bg0)return J();let X=this.tracerProvider.getTracer("prisma"),$=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(jr(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=X.startSpan(Y,Z,$);return Dr(Q,J(Q,$))}return X.startActiveSpan(Y,Z,(Q)=>Dr(Q,J(Q,$)))}};function wr(Z,J,X,$,Y){if(jr(J.name,Y))return;let Q={attributes:J.attributes,kind:Lg0(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(W)=>{if($.set(J.id,W.spanContext().spanId),J.links)W.addLinks(J.links.flatMap((z)=>{let G=$.get(z);if(!G)return[];return{context:{spanId:G,traceId:W.spanContext().traceId,traceFlags:W.spanContext().traceFlags}}}));let K=X.filter((z)=>z.parentId===J.id);for(let z of K)wr(Z,z,X,$,Y);W.end(J.endTime)})}function Dr(Z,J){if(_g0(J))return J.then((X)=>{return Z.end(),X},(X)=>{throw Z.end(),X});return Z.end(),J}function _g0(Z){return Z!=null&&typeof Z.then==="function"}function jr(Z,J){return J.some((X)=>typeof X==="string"?X===Z:X.test(Z))}var Mr={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},ZD=Mr.version,Og0=ZD.split(".")[0],_r="PRISMA_INSTRUMENTATION",e2=`V${Og0}_PRISMA_INSTRUMENTATION`,wg0=Mr.name,jg0="@prisma/client",Ar=class extends Ez.InstrumentationBase{tracerProvider;constructor(Z={}){super(wg0,ZD,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new Ez.InstrumentationNodeModuleDefinition(jg0,[ZD])]}enable(){let Z=this._config,J={helper:new Dg0({tracerProvider:this.tracerProvider??Or.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[_r]=J,global[e2]=J}disable(){delete global[_r],delete global[e2]}isEnabled(){return Boolean(global[e2])}};var Tr="Prisma";function Mg0(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function qr(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class Cr extends Ar{constructor(){super()}enable(){super.enable();let Z=qr();if(Mg0(Z))Z.createEngineSpan=(J)=>{let X=r6.trace.getTracer("prismaV5Compatibility"),$=X._idGenerator;if(!$){y1(()=>{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=Ag0(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:r6.TraceFlags.SAMPLED}}}),H=r6.trace.setSpanContext(r6.context.active(),{traceId:z,spanId:W,traceFlags:r6.TraceFlags.SAMPLED});r6.context.with(H,()=>{let V={generateTraceId:()=>{return z},generateSpanId:()=>{return K}};X._idGenerator=V,X.startSpan(Y.name,{kind:Q,links:G,startTime:Y.start_time,attributes:Y.attributes}).end(Y.end_time),X._idGenerator=$})})}finally{X._idGenerator=$}}}}function Ag0(Z){switch(Z){case"client":return r6.SpanKind.CLIENT;case"internal":default:return r6.SpanKind.INTERNAL}}var Tg0=a(Tr,(Z)=>{return new Cr}),Nr=S((Z)=>{return{name:Tr,setupOnce(){Tg0()},setup(J){if(!qr())return;J.on("spanStart",(X)=>{let $=J0(X);if($.description?.startsWith("prisma:"))X.setAttribute(X0,"auto.db.otel.prisma");if($.description==="prisma:engine:db_query"&&$.data["db.query.text"])X.updateName($.data["db.query.text"]);if($.description==="prisma:engine:db_query"&&!$.data["db.system"])X.setAttribute("db.system","prisma")})}}});var or=k(nr(),1);var ar="Hapi",rr=a(ar,()=>new or.HapiInstrumentation),ng0=()=>{return{name:ar,setupOnce(){rr()}}},sr=S(ng0);var Sz=k(p0(),1);var j7={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},M3={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var hZ=k(f(),1),yz=k(H0(),1);var og0="@sentry/instrumentation-hono",ag0="0.0.1";class QD extends yz.InstrumentationBase{constructor(Z={}){super(og0,ag0,Z)}init(){return[new yz.InstrumentationNodeModuleDefinition("hono",[">=4.0.0 <5"],(Z)=>this._patch(Z))]}_patch(Z){let J=this;class X extends Z.Hono{constructor(...$){super(...$);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=X}catch{return{...Z,Hono:X}}return Z}_patchHandler(){let Z=this;return function(J){return function(...$){if(typeof $[0]==="string"){let Y=$[0];if($.length===1)return J.apply(this,[Y]);let Q=$.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,$.map((Y)=>Z._wrapHandler(Y)))}}}_patchOnHandler(){let Z=this;return function(J){return function(...$){let Y=$.slice(2);return J.apply(this,[...$.slice(0,2),...Y.map((Q)=>Z._wrapHandler(Q))])}}}_patchMiddlewareHandler(){let Z=this;return function(J){return function(...$){if(typeof $[0]==="string"){let Y=$[0];if($.length===1)return J.apply(this,[Y]);let Q=$.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,$.map((Y)=>Z._wrapHandler(Y)))}}}_wrapHandler(Z){let J=this;return function(X,$){if(!J.isEnabled())return Z.apply(this,[X,$]);let Y=X.req.path,Q=J.tracer.startSpan(Y);return hZ.context.with(hZ.trace.setSpan(hZ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[X,$]);if(I4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[j7.HONO_TYPE]:z,[j7.HONO_NAME]:z===M3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[j7.HONO_TYPE]:K,[j7.HONO_NAME]:K===M3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),W}},()=>Q.end(),(W)=>{J._handleError(Q,W),Q.end()})})}}_safeExecute(Z,J,X){try{let $=Z();if(I4($))$.then(()=>J(),(Y)=>X(Y));else J();return $}catch($){throw X($),$}}_determineHandlerType(Z){return Z===void 0?M3.MIDDLEWARE:M3.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:hZ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var tr="Hono";function rg0(Z){let J=J0(Z).data,X=J[j7.HONO_TYPE];if(J[K0]||!X)return;Z.setAttributes({[X0]:"auto.http.otel.hono",[K0]:`${X}.hono`});let $=J[j7.HONO_NAME];if(typeof $==="string")Z.updateName($);if(R0()===B6()){N1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[Sz.ATTR_HTTP_ROUTE],Q=J[Sz.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")R0().setTransactionName(`${Q} ${Y}`)}var er=a(tr,()=>new QD({responseHook:(Z)=>{rg0(Z)}})),sg0=()=>{return{name:tr,setupOnce(){er()}}},Zs=S(sg0);var Ts=k(As(),1),qs=k(p0(),1);var Cs="Koa",Ns=a(Cs,Ts.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,X){i0(J,"auto.http.otel.koa");let $=J0(J).data,Y=$["koa.type"];if(Y)J.setAttribute(K0,`${Y}.koa`);let Q=$["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(R0()===B6()){N1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=$[qs.ATTR_HTTP_ROUTE],K=X.context?.request?.method?.toUpperCase()||"GET";if(W)R0().setTransactionName(`${K} ${W}`)}}}),Gm0=(Z={})=>{return{name:Cs,setupOnce(){Ns(Z)}}},Rs=S(Gm0);var os=k(ns(),1);var as="Connect",rs=a(as,()=>new os.ConnectInstrumentation),Tm0=()=>{return{name:as,setupOnce(){rs()}}},ss=S(Tm0);var Lt=k(Ut(),1);var bm0=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),Dt="Tedious",_t=a(Dt,()=>new Lt.TediousInstrumentation({})),gm0=()=>{let Z;return{name:Dt,setupOnce(){let J=_t();Z=EY(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{description:$,data:Y}=J0(X);if(!$||Y["db.system"]!=="mssql")return;let Q=$.split(" ")[0]||"";if(bm0.has(Q))X.setAttribute(X0,"auto.db.otel.tedious")}))}}},Ot=S(gm0);var Pt=k(Rt(),1);var Et="GenericPool",It=a(Et,()=>new Pt.GenericPoolInstrumentation({})),cm0=()=>{let Z;return{name:Et,setupOnce(){let J=It();Z=EY(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let Y=J0(X).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")X.setAttribute(X0,"auto.db.otel.generic_pool")}))}}},yt=S(cm0);var Je=k(Ze(),1);var Xe="Amqplib",Td0={consumeEndHook:(Z)=>{i0(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{i0(Z,"auto.amqplib.otel.publisher")}},$e=a(Xe,()=>new Je.AmqplibInstrumentation(Td0)),qd0=()=>{return{name:Xe,setupOnce(){$e()}}},Ye=S(qd0);var N3="VercelAI";var dz=k(H0(),1);var Cd0=[">=3.0.0 <7"],Qe=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function Nd0(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 Rd0(Z){if(typeof Z!=="object"||Z===null||!("content"in Z))return;let J=Z;if(!Array.isArray(J.content))return;for(let X of J.content)if(Nd0(X)){let $=PU(X.toolCallId);if($){let Y=$.spanContext();s4((Q)=>{Q.setContext("trace",{trace_id:Y.traceId,span_id:Y.spanId}),Q.setTag("vercel.ai.tool.name",X.toolName),Q.setTag("vercel.ai.tool.callId",X.toolCallId),Q.setLevel("error"),V0(X.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),EU(X.toolCallId)}else s4((Y)=>{Y.setTag("vercel.ai.tool.name",X.toolName),Y.setTag("vercel.ai.tool.callId",X.toolCallId),Y.setLevel("error"),V0(X.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function Pd0(Z,J,X,$){let Y=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:X===!0?!0:$,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:X===!0?!0:$;return{recordInputs:Y,recordOutputs:Q}}class R3 extends dz.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",N0,Z);R3.prototype.__init.call(this),R3.prototype.__init2.call(this)}init(){return new dz.InstrumentationNodeModuleDefinition("ai",Cd0,this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach((X)=>X()),this._callbacks=[];let J=(X)=>{return new Proxy(X,{apply:($,Y,Q)=>{let W=Q[0].experimental_telemetry||{},K=W.isEnabled,z=u(),G=z?.getIntegrationByName(N3),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=Pd0(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},D6(()=>Reflect.apply($,Y,Q),(U)=>{if(U&&typeof U==="object")f1(U,"_sentry_active_span",t8())},()=>{},(U)=>{Rd0(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let X of Qe)Z[X]=J(Z[X]);return Z}else{let X=Qe.reduce(($,Y)=>{return $[Y]=J(Z[Y]),$},{});return{...Z,...X}}}}var We=a(N3,()=>new R3({}));function Ed0(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var Id0=(Z={})=>{let J;return{name:N3,options:Z,setupOnce(){J=We()},afterAllSetup(X){if(Z.force??Ed0(X))GK(X);else J?.callWhenPatched(()=>GK(X))}}},Ke=S(Id0);var uz=k(H0(),1);var yd0=[">=4.0.0 <7"];class qD extends uz.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",N0,Z)}init(){return new uz.InstrumentationNodeModuleDefinition("openai",yd0,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 X=Z[J];if(!X)return Z;let $=this.getConfig(),Y=function(...Q){if(jZ(Y7))return Reflect.construct(X,Q);let W=Reflect.construct(X,Q),K=u(),z=Boolean(K?.getOptions().sendDefaultPii),G=$.recordInputs??z,H=$.recordOutputs??z;return FK(W,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(Y,X),Object.setPrototypeOf(Y.prototype,X.prototype);for(let Q of Object.getOwnPropertyNames(X))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor(X,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===X)try{Z.default=Y}catch(Q){Object.defineProperty(Z,"default",{value:Y,writable:!0,configurable:!0,enumerable:!0})}return Z}}var ze=a(Y7,(Z)=>new qD(Z)),Sd0=(Z={})=>{return{name:Y7,setupOnce(){ze(Z)}}},Ge=S(Sd0);var cz=k(H0(),1);var kd0=[">=0.19.2 <1.0.0"];class CD extends cz.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",N0,Z)}init(){return new cz.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",kd0,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,X=this.getConfig(),$=function(...Y){if(jZ(Q7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=u(),K=Boolean(W?.getOptions().sendDefaultPii),z=X.recordInputs??K,G=X.recordOutputs??K;return SU(Q,{recordInputs:z,recordOutputs:G})};Object.setPrototypeOf($,J),Object.setPrototypeOf($.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($,Y,Q)}try{Z.Anthropic=$}catch(Y){Object.defineProperty(Z,"Anthropic",{value:$,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===J)try{Z.default=$}catch(Y){Object.defineProperty(Z,"default",{value:$,writable:!0,configurable:!0,enumerable:!0})}return Z}}var He=a(Q7,(Z)=>new CD(Z)),xd0=(Z={})=>{return{name:Q7,options:Z,setupOnce(){He(Z)}}},Ve=S(xd0);var dX=k(H0(),1);var Fe=[">=0.10.0 <2"];class ND extends dX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",N0,Z)}init(){return new dX.InstrumentationNodeModuleDefinition("@google/genai",Fe,(J)=>this._patch(J),(J)=>J,[new dX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",Fe,(J)=>this._patch(J),(J)=>J)])}_patch(Z){let J=Z.GoogleGenAI,X=this.getConfig();if(typeof J!=="function")return Z;let $=function(...Y){if(jZ(W7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=u(),K=Boolean(W?.getOptions().sendDefaultPii),z=X,G=z?.recordInputs??K,H=z?.recordOutputs??K;return hU(Q,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf($,J),Object.setPrototypeOf($.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($,Y,Q)}return RY(Z,"GoogleGenAI",$),Z}}var Be=a(W7,(Z)=>new ND(Z)),vd0=(Z={})=>{return{name:W7,setupOnce(){Be(Z)}}},Ue=S(vd0);var T7=k(H0(),1);var lz=[">=0.1.0 <2.0.0"];function hd0(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 fd0(Z,J,X){return new Proxy(Z,{apply($,Y,Q){let K=Q[1];if(!K||typeof K!=="object"||Array.isArray(K))K={},Q[1]=K;let z=K.callbacks,G=hd0(z,J);return K.callbacks=G,Reflect.apply($,Y,Q)}})}class RD extends T7.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",N0,Z)}init(){let Z=[],J=["@langchain/anthropic","@langchain/openai","@langchain/google-genai","@langchain/mistralai","@langchain/google-vertexai","@langchain/groq"];for(let X of J)Z.push(new T7.InstrumentationNodeModuleDefinition(X,lz,this._patch.bind(this),($)=>$,[new T7.InstrumentationNodeModuleFile(`${X}/dist/index.cjs`,lz,this._patch.bind(this),($)=>$)]));return Z.push(new T7.InstrumentationNodeModuleDefinition("langchain",lz,this._patch.bind(this),(X)=>X,[new T7.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",lz,this._patch.bind(this),(X)=>X)])),Z}_patch(Z){zU([Y7,Q7,W7]);let J=u(),X=Boolean(J?.getOptions().sendDefaultPii),$=this.getConfig(),Y=$?.recordInputs??X,Q=$?.recordOutputs??X,W=UK({recordInputs:Y,recordOutputs:Q});return this._patchRunnableMethods(Z,W),Z}_patchRunnableMethods(Z,J){let X=["ChatAnthropic","ChatOpenAI","ChatGoogleGenerativeAI","ChatMistralAI","ChatVertexAI","ChatGroq","ConfigurableModel"],$=Z.universal_exports??Z,Y=Object.values($).find((K)=>{return typeof K==="function"&&X.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]=fd0(z,J)}}}var Le=a(BK,(Z)=>new RD(Z)),bd0=(Z={})=>{return{name:BK,setupOnce(){Le(Z)}}},De=S(bd0);var uX=k(H0(),1);var _e=[">=0.0.0 <2.0.0"];class PD extends uX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",N0,Z)}init(){return new uX.InstrumentationNodeModuleDefinition("@langchain/langgraph",_e,this._patch.bind(this),(J)=>J,[new uX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",_e,this._patch.bind(this),(J)=>J)])}_patch(Z){let J=u(),X=Boolean(J?.getOptions().sendDefaultPii),$=this.getConfig(),Y=$.recordInputs??X,Q=$.recordOutputs??X,W={recordInputs:Y,recordOutputs:Q};if(Z.StateGraph&&typeof Z.StateGraph==="function"){let K=Z.StateGraph;K.prototype.compile=gU(K.prototype.compile,W)}return Z}}var Oe=a(LK,(Z)=>new PD(Z)),gd0=(Z={})=>{return{name:LK,setupOnce(){Oe(Z)}}},we=S(gd0);var Re=k(H0(),1);var K9=k(f(),1),z9=k(H0(),1),s6=k(p0(),1);import*as Me from"net";function Ae(Z,J,X,$,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{z9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;K9.diag.error(V?.message)},!0)};let z=new z9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>je(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 z9.InstrumentationNodeModuleFile(H,J,(V)=>je(V,X,$,Z,W),(V)=>Te(V,$)));return z}function je(Z,J,X,$,Y){return Te(Z,X),J(Z,"addDoc",md0($,Y)),J(Z,"getDocs",ud0($,Y)),J(Z,"setDoc",cd0($,Y)),J(Z,"deleteDoc",dd0($,Y)),Z}function Te(Z,J){for(let X of["addDoc","getDocs","setDoc","deleteDoc"])if(z9.isWrapped(Z[X]))J(Z,X);return Z}function md0(Z,J){return function($){return function(Y,Q){let W=iz(Z,"addDoc",Y);return J(W),pz(W,()=>{return $(Y,Q)})}}}function dd0(Z,J){return function($){return function(Y){let Q=iz(Z,"deleteDoc",Y.parent||Y);return J(Q),pz(Q,()=>{return $(Y)})}}}function ud0(Z,J){return function($){return function(Y){let Q=iz(Z,"getDocs",Y);return J(Q),pz(Q,()=>{return $(Y)})}}}function cd0(Z,J){return function($){return function(Y,Q,W){let K=iz(Z,"setDoc",Y.parent||Y);return J(K),pz(K,()=>{return typeof W<"u"?$(Y,Q,W):$(Y,Q)})}}}function pz(Z,J){return K9.context.with(K9.trace.setSpan(K9.context.active(),Z),()=>{return z9.safeExecuteInTheMiddle(()=>{return J()},(X)=>{if(X)Z.recordException(X);Z.end()},!0)})}function iz(Z,J,X){let $=Z.startSpan(`${J} ${X.path}`,{kind:K9.SpanKind.CLIENT});return pd0($,X),$.setAttribute(s6.ATTR_DB_OPERATION_NAME,J),$}function ld0(Z){let J,X;if(typeof Z.host==="string")if(Z.host.startsWith("[")){if(Z.host.endsWith("]"))J=Z.host.replace(/^\[|\]$/g,"");else if(Z.host.includes("]:")){let $=Z.host.lastIndexOf(":");if($!==-1)J=Z.host.slice(1,$).replace(/^\[|\]$/g,""),X=Z.host.slice($+1)}}else if(Me.isIPv6(Z.host))J=Z.host;else{let $=Z.host.lastIndexOf(":");if($!==-1)J=Z.host.slice(0,$),X=Z.host.slice($+1);else J=Z.host}return{address:J,port:X?parseInt(X,10):void 0}}function pd0(Z,J){let X=J.firestore.app,$=X.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[s6.ATTR_DB_COLLECTION_NAME]:J.path,[s6.ATTR_DB_NAMESPACE]:X.name,[s6.ATTR_DB_SYSTEM_NAME]:"firebase.firestore","firebase.firestore.type":J.type,"firebase.firestore.options.projectId":$.projectId,"firebase.firestore.options.appId":$.appId,"firebase.firestore.options.messagingSenderId":$.messagingSenderId,"firebase.firestore.options.storageBucket":$.storageBucket},{address:K,port:z}=ld0(Q);if(K)W[s6.ATTR_SERVER_ADDRESS]=K;if(z)W[s6.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var G5=k(f(),1),G9=k(H0(),1);function qe(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)=>{G9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;G5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{G9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;G5.diag.error(B?.message)},!0)};let H=new G9.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 G9.InstrumentationNodeModuleFile(F,J,(U)=>id0(U,X,$,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>Ce(U,$)))}),H}function f4(Z,J,X){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.${X}`,{kind:G5.SpanKind.SERVER}),F={"faas.name":H,"faas.trigger":X,"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),G5.context.with(G5.trace.setSpan(G5.context.active(),V),async()=>{let B,U;try{U=await W.apply(this,G)}catch(D){B=D}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 id0(Z,J,X,$,Y,Q){switch(Ce(Z,X),Q){case"function":J(Z,"onRequest",f4($,Y,"http.request")),J(Z,"onCall",f4($,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",f4($,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",f4($,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",f4($,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",f4($,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",f4($,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",f4($,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",f4($,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",f4($,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",f4($,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",f4($,Y,"storage.object.finalized")),J(Z,"onObjectArchived",f4($,Y,"storage.object.archived")),J(Z,"onObjectDeleted",f4($,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",f4($,Y,"storage.object.metadataUpdated"));break}return Z}function Ce(Z,J){let X=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let $ of X)if(G9.isWrapped(Z[$]))J(Z,$);return Z}var Ne={},nd0=[">=3.0.0 <5"],od0=[">=6.0.0 <7"];class ED extends Re.InstrumentationBase{constructor(Z=Ne){super("@sentry/instrumentation-firebase",N0,Z)}setConfig(Z={}){super.setConfig({...Ne,...Z})}init(){let Z=[];return Z.push(Ae(this.tracer,nd0,this._wrap,this._unwrap,this.getConfig())),Z.push(qe(this.tracer,od0,this._wrap,this._unwrap,this.getConfig())),Z}}var Pe="Firebase",ad0={firestoreSpanCreationHook:(Z)=>{i0(Z,"auto.firebase.otel.firestore"),Z.setAttribute(K0,"db.query")},functions:{requestHook:(Z)=>{i0(Z,"auto.firebase.otel.functions"),Z.setAttribute(K0,"http.request")},errorHook:async(Z,J)=>{if(J)V0(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await oW(2000)}}},Ee=a(Pe,()=>new ED(ad0)),rd0=()=>{return{name:Pe,setupOnce(){Ee()}}},Ie=S(rd0);function P3(){return[yl(),Op(),Ki(),Zs(),Ln(),bn(),Qo(),Ro(),ya(),Hr(),Nr(),sr(),Rs(),ss(),Ot(),yt(),xi(),Ye(),ai(),De(),we(),Ke(),Ge(),Ve(),Ue(),Lr(),Ie()]}var cX=k(f(),1);var lX=k(p0(),1);var ID=1e6;function ye(Z,J={}){if(Z.getOptions().debug)bL();let[X,$]=sd0(Z,J);Z.traceProvider=X,Z.asyncLocalStorageLookup=$}function sd0(Z,J={}){let X=new hK({sampler:new TL(Z),resource:xY().merge(IK({[lX.ATTR_SERVICE_NAME]:"node",[lX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[lX.ATTR_SERVICE_VERSION]:N0})),forceFlushTimeoutMillis:500,spanProcessors:[new AL({timeout:td0(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});cX.trace.setGlobalTracerProvider(X),cX.propagation.setGlobalPropagator(new ML);let $=new cK;return cX.context.setGlobalContextManager($),[X,$.getAsyncLocalStorageLookup()]}function td0(Z){if(Z==null)return;if(Z>ID)return N1&&A.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${ID}`),ID;else if(Z<=0||Number.isNaN(Z)){N1&&A.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function Se(){return oK().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(oY(),rY())}function ke(Z){return[...Se(),...L1(Z)?P3():[]]}function yD(Z={}){return ed0(Z,ke)}function ed0(Z={},J){n5(Z,"node");let X=nL({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if(X&&!Z.skipOpenTelemetrySetup)ye(X,{spanProcessors:Z.openTelemetrySpanProcessors}),aK();return X}import*as be from"os";var Zu0="BunServer",Ju0=()=>{return{name:Zu0,setupOnce(){Xu0()}}},he=S(Ju0),xe=!1;function Xu0(){if(xe)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,X){ve(X[0]);let $=Z.apply(J,X),Y=$.reload.bind($);return $.reload=(Q)=>{return ve(Q),Y(Q)},$}}),xe=!0}function ve(Z){$u0(Z),Yu0(Z)}function $u0(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,X,$){return SD(J,X,$)}})}function Yu0(Z){if(!Z.routes)return;if(typeof Z.routes!=="object")return;Object.keys(Z.routes).forEach((J)=>{let X=Z.routes[J];if(typeof X==="function")Z.routes[J]=new Proxy(X,{apply:($,Y,Q)=>{return SD($,Y,Q,J)}});if(X instanceof Response)return;if(typeof X==="object")Object.entries(X).forEach(([$,Y])=>{if(typeof Y==="function")Z.routes[J][$]=new Proxy(Y,{apply:(Q,W,K)=>{return SD(Q,W,K,J)}})})})}function SD(Z,J,X,$){return GZ((Y)=>{let Q=X[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,X);let K=LY(Q.url),z=Qu0(K,Q),G=K?.pathname||"/";if(Q.params){if(Object.keys(Q.params).forEach((H)=>{z[`url.path.parameter.${H}`]=Q.params[H]}),$)z[U1]="route",z["url.template"]=$,G=$}if($?.endsWith("/*"))z[U1]="route",z["url.template"]=$,G=$;return Object.assign(z,oJ(Q.headers.toJSON(),u()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),pW({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>_6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,X);if(V?.status)xW(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw V0(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function Qu0(Z,J){let X={[X0]:"auto.http.bun.serve",[fB]:J.method||"GET",[U1]:"url"};if(Z){if(Z.search)X["url.query"]=Z.search;if(Z.hash)X["url.fragment"]=Z.hash;if(Z.pathname)X["url.path"]=Z.pathname;if(!HU(Z)){if(X["url.full"]=Z.href,Z.port)X["url.port"]=Z.port;if(Z.protocol)X["url.scheme"]=Z.protocol;if(Z.hostname)X["url.domain"]=Z.hostname}}return X}function fe(Z){function J(X){let $={body:X.body,method:"POST",headers:Z.headers};try{return i9(()=>{return fetch(Z.url,$).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 wZ(Z,J)}function ge(Z){return[rJ(),aJ(),sJ(),tJ(),eJ(),oY(),rY(),TX(),qX(),MX(),jX(),AX(),he(),...L1(Z)?P3():[]]}function kD(Z={}){n5(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||be.hostname()};if(J.transport=J.transport||fe,J.defaultIntegrations===void 0)J.defaultIntegrations=ge(J);return yD(J)}kD({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as me}from"fs";import{join as de}from"path";function Q6(){return"2.1.0-beta.3"}function xD(Z){let[J,X]=Z.split("-"),$=(J||"0.0.0").split(".").map(Number),Y=null,Q=0;if(X){let W=X.match(/^([a-z]+)\.?(\d+)?$/i);if(W)Y=W[1]||null,Q=parseInt(W[2]||"0",10);else Y=X}return{major:$[0]||0,minor:$[1]||0,patch:$[2]||0,preRelease:Y,preReleaseNum:Q}}function H9(Z){let J=xD(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function E3(Z,J){try{let X=xD(Z),$=xD(J);if(X.major>$.major)return!1;if(X.major<$.major)return!1;if($.preRelease&&!X.preRelease)return!1;if(!$.preRelease&&X.preRelease)return!1;if($.preRelease&&X.preRelease){if(X.minor<$.minor)return!1;if(X.minor>$.minor)return!0;if(X.patch>$.patch)return!0;if(X.patch<$.patch)return!1;return X.preReleaseNum>$.preReleaseNum}if(X.minor>$.minor)return!0;if(X.minor<$.minor)return!1;if(X.patch>$.patch)return!0;return!1}catch(X){return!1}}import{parseArgs as Ku0}from"util";var zu0={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 ue(){let Z=Ku0({options:zu0,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${Q6()}`),process.exit(0);if(Z.values.help)Gu0(),process.exit(0);let J=process.env.CCC_USERNAME||Z.values.username,X=process.env.CCC_PASSWORD||Z.values.password,$=process.env.CCC_NGROK_TOKEN||Z.values["ngrok-token"],Y=process.env.CCC_NGROK_DOMAIN||Z.values["ngrok-domain"];if(!J||!X)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:X,ngrokToken:$,ngrokDomain:Y,autoUpdate:!Z.values["no-auto-update"],autoUpdateCheckInterval:parseInt(Z.values["auto-update-check-interval"],10),terminalAudit:Z.values["terminal-audit"]}}function Gu0(){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 X;else if(W===z)return Q===K-1&&Z[Q]==="";else throw Error("wtf?")}braceExpand(){return Xp(this.pattern,this.options)}parse(Z){eY(Z);let J=this.options;if(Z==="**")return l6;if(Z==="")return"";let X,$=null;if(X=Z.match(_x0))$=J.dot?wx0:Ox0;else if(X=Z.match(Kx0))$=(J.nocase?J.dot?Vx0:Hx0:J.dot?Gx0:zx0)(X[1]);else if(X=Z.match(jx0))$=(J.nocase?J.dot?Ax0:Mx0:J.dot?Tx0:qx0)(X);else if(X=Z.match(Fx0))$=J.dot?Ux0:Bx0;else if(X=Z.match(Lx0))$=Dx0;let Y=H4.fromGlob(Z,this.options).toMMPattern();if($&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:$});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,X=J.noglobstar?Rx0:J.dot?Px0:Ex0,$=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(""))$.add(H);return typeof G==="string"?xx0(G):G===l6?l6:G._src});return z.forEach((G,H)=>{let V=z[H+1],F=z[H-1];if(G!==l6||F===l6)return;if(F===void 0)if(V!==void 0&&V!==l6)z[H+1]="(?:\\/|"+X+"\\/)?"+V;else z[H]=X;else if(V===void 0)z[H-1]=F+"(?:\\/|"+X+")?";else if(V!==l6)z[H-1]=F+"(?:\\/|\\/"+X+"\\/)"+V,z[H+1]=l6}),z.filter((G)=>G!==l6).join("/")}).join("|"),[Q,W]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+W+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...$].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 X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let $=this.slashSplit(Z);this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=$[$.length-1];if(!Q)for(let W=$.length-2;!Q&&W>=0;W--)Q=$[W];for(let W=0;W<Y.length;W++){let K=Y[W],z=$;if(X.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return V4.defaults(Z).Minimatch}}V4.AST=H4;V4.Minimatch=J3;V4.escape=Q2;V4.unescape=V7;var Yp="@fastify/otel",hx0="0.8.0",fx0=">=4.0.0 <6",Qp=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],$1={HOOK_NAME:"hook.name",FASTIFY_TYPE:"fastify.type",HOOK_CALLBACK_NAME:"hook.callback.name",ROOT:"fastify.root"},F7={ROUTE:"route-hook",INSTANCE:"hook",HANDLER:"request-handler"},Z9="anonymous",x4=Symbol("fastify otel instance"),B7=Symbol("fastify otel request spans"),X3=Symbol("fastify otel request context"),Wp=Symbol("fastify otel addhook original"),Kp=Symbol("fastify otel setnotfound original"),Xz=Symbol("fastify otel ignore path");class W2 extends zp.InstrumentationBase{constructor(Z){super(Yp,hx0,Z);if(this.servername=Z?.servername??process.env.OTEL_SERVICE_NAME??"fastify",this[Xz]=null,this._logger=k1.diag.createComponentLogger({namespace:Yp}),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 X=V4;this[Xz]=($)=>{if(typeof J==="function")return J($);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)},$p.subscribe("fastify.initialization",this._handleInitialization)}return super.enable()}disable(){if(this._handleInitialization)$p.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:fx0,name:"@fastify/otel"},J;function J(X,$,Y){X.decorate(x4,Z),X.decorate(Wp,X.addHook),X.decorate(Kp,X.setNotFoundHandler),X.decorateRequest("opentelemetry",function(){let V=this[X3];return{span:this[B7],tracer:Z.tracer,context:V,inject:(B,U)=>{return k1.propagation.inject(V,B,U)},extract:(B,U)=>{return k1.propagation.extract(V,B,U)}}}),X.decorateRequest(B7,null),X.decorateRequest(X3,null),X.addHook("onRoute",function(H){if(Z[Xz]?.(H)===!0){Z._logger.debug(`Ignoring route instrumentation ${H.method} ${H.url} because it matches the ignore path`);return}for(let V of Qp)if(H[V]!=null){let F=H[V];if(typeof F==="function")H[V]=G(F,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[$1.FASTIFY_TYPE]:F7.ROUTE,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:F.name?.length>0?F.name:Z9});else if(Array.isArray(F)){let B=[];for(let U of F)B.push(G(U,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route -> ${V}`,[$1.FASTIFY_TYPE]:F7.ROUTE,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:U.name?.length>0?U.name:Z9}));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,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - route-handler`,[$1.FASTIFY_TYPE]:F7.HANDLER,[d1.ATTR_HTTP_ROUTE]:H.url,[$1.HOOK_CALLBACK_NAME]:H.handler.name.length>0?H.handler.name:Z9})}),X.addHook("onRequest",function(H,V,F){if(this[x4].isEnabled()===!1)return F();else if(this[x4][Xz]?.({url:H.url,method:H.method})===!0)return this[x4]._logger.debug(`Ignoring request ${H.method} ${H.url} because it matches the ignore path`),F();let B=k1.context.active();if(k1.trace.getSpan(B)==null)B=k1.propagation.extract(B,H.headers);let U=$z.getRPCMetadata(B);if(H.routeOptions.url!=null&&U?.type===$z.RPCType.HTTP)U.route=H.routeOptions.url;let D=this[x4].tracer.startSpan("request",{attributes:{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.ROOT]:"@fastify/otel",[d1.ATTR_HTTP_ROUTE]:H.url,[d1.ATTR_HTTP_REQUEST_METHOD]:H.method}},B);H[X3]=k1.trace.setSpan(B,D),H[B7]=D,k1.context.with(H[X3],()=>{F()})}),X.addHook("onResponse",function(H,V,F){let B=H[B7];if(B!=null)B.setStatus({code:k1.SpanStatusCode.OK,message:"OK"}),B.setAttributes({[d1.ATTR_HTTP_RESPONSE_STATUS_CODE]:404}),B.end();H[B7]=null,F()}),X.addHook=K,X.setNotFoundHandler=z,Y();function Q(H,V,F,B){let U=H[B7];if(U!=null){if(V.statusCode<500)U.setStatus({code:k1.SpanStatusCode.OK,message:"OK"});U.setAttributes({[d1.ATTR_HTTP_RESPONSE_STATUS_CODE]:V.statusCode}),U.end()}H[B7]=null,B(null,F)}function W(H,V,F,B){let U=H[B7];if(U!=null)U.setStatus({code:k1.SpanStatusCode.ERROR,message:F.message}),U.recordException(F);B()}function K(H,V){let F=this[Wp];if(Qp.includes(H))return F.call(this,H,G(V,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - ${H}`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:Z9}));else return F.call(this,H,V)}function z(H,V){let F=this[Kp];if(typeof H==="function")V=G(H,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.name?.length>0?H.name:Z9}),F.call(this,V);else{if(H.preValidation!=null)H.preValidation=G(H.preValidation,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preValidation`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.preValidation.name?.length>0?H.preValidation.name:Z9});if(H.preHandler!=null)H.preHandler=G(H.preHandler,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler - preHandler`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:H.preHandler.name?.length>0?H.preHandler.name:Z9});V=G(V,{[d1.ATTR_SERVICE_NAME]:X[x4].servername,[$1.HOOK_NAME]:`${this.pluginName} - not-found-handler`,[$1.FASTIFY_TYPE]:F7.INSTANCE,[$1.HOOK_CALLBACK_NAME]:V.name?.length>0?V.name:Z9}),F.call(this,H,V)}}function G(H,V={}){return function(...B){let U=this[x4],[D]=B;if(U.isEnabled()===!1)return H.call(this,...B);let _=D[X3]??k1.context.active(),O=U.tracer.startSpan(`handler - ${H.name?.length>0?H.name:this.pluginName??Z9}`,{attributes:V},_);return k1.context.with(k1.trace.setSpan(_,O),function(){try{let w=H.call(this,...B);if(typeof w?.then==="function")return w.then((j)=>{return O.end(),j},(j)=>{return O.setStatus({code:k1.SpanStatusCode.ERROR,message:j.message}),O.recordException(j),O.end(),Promise.reject(j)});return O.end(),w}catch(w){throw O.setStatus({code:k1.SpanStatusCode.ERROR,message:w.message}),O.recordException(w),O.end(),w}},this)}}}}}var I8=k(f(),1),Qz=k(H1(),1),kZ=k(H0(),1),Bp=k(p0(),1);var J9;(function(Z){Z.FASTIFY_NAME="fastify.name";let X="fastify.type";Z.FASTIFY_TYPE=X;let $="hook.name";Z.HOOK_NAME=$;let Y="plugin.name";Z.PLUGIN_NAME=Y})(J9||(J9={}));var $3;(function(Z){Z.MIDDLEWARE="middleware";let X="request_handler";Z.REQUEST_HANDLER=X})($3||($3={}));var Y3;(function(Z){Z.MIDDLEWARE="middleware";let X="request handler";Z.REQUEST_HANDLER=X})(Y3||(Y3={}));var Hp=k(f(),1);var Q3=Symbol("opentelemetry.instrumentation.fastify.request_active_span");function K2(Z,J,X,$={}){let Y=J.startSpan(X,{attributes:$}),Q=Z[Q3]||[];return Q.push(Y),Object.defineProperty(Z,Q3,{enumerable:!1,configurable:!0,value:Q}),Y}function Yz(Z,J){let X=Z[Q3]||[];if(!X.length)return;X.forEach(($)=>{if(J)$.setStatus({code:Hp.SpanStatusCode.ERROR,message:J.message}),$.recordException(J);$.end()}),delete Z[Q3]}function Vp(Z,J,X){let $,Y=void 0;try{if(Y=Z(),Gp(Y))Y.then((Q)=>J(void 0,Q),(Q)=>J(Q))}catch(Q){$=Q}finally{if(!Gp(Y)){if(J($,Y),$)throw $}return Y}}function Gp(Z){return typeof Z==="object"&&Z&&typeof Object.getOwnPropertyDescriptor(Z,"then")?.value==="function"||!1}var bx0="0.1.0",gx0="@sentry/instrumentation-fastify-v3",Fp="anonymous",mx0=new Set(["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError"]);class z2 extends kZ.InstrumentationBase{constructor(Z={}){super(gx0,bx0,Z)}init(){return[new kZ.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($,"send",Z._patchSend());let Q=X,W=Qz.getRPCMetadata(I8.context.active()),K=Q.routeOptions?Q.routeOptions.url:X.routerPath;if(K&&W?.type===Qz.RPCType.HTTP)W.route=K;let z=X.method||"GET";R0().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 X.apply(this,Q);let W=X.name||Z||Fp,K=`${Y3.MIDDLEWARE} - ${W}`,z=Q[1],G=K2(z,Y.tracer,K,{[J9.FASTIFY_TYPE]:$3.MIDDLEWARE,[J9.PLUGIN_NAME]:Z,[J9.HOOK_NAME]:J}),H=$&&Q[Q.length-1];if(H)Q[Q.length-1]=function(...V){Yz(z),H.apply(this,V)};return I8.context.with(I8.trace.setSpan(I8.context.active(),G),()=>{return Vp(()=>{return X.apply(this,Q)},(V)=>{if(V instanceof Error)G.setStatus({code:I8.SpanStatusCode.ERROR,message:V.message}),G.recordException(V);if(!$)Yz(z)})})}}_wrapAddHook(){let Z=this;return this._diag.debug("Patching fastify server.addHook function"),function(J){return function(...$){let Y=$[0],Q=$[1],W=this.pluginName;if(!mx0.has(Y))return J.apply(this,$);let K=typeof $[$.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,$);return Y.addHook("onRequest",J._hookOnRequest()),Y.addHook("preHandler",J._hookPreHandler()),dx0(),J._wrap(Y,"addHook",J._wrapAddHook()),Y}if(Z.errorCodes!==void 0)X.errorCodes=Z.errorCodes;return X.fastify=X,X.default=X,X}_patchSend(){let Z=this;return this._diag.debug("Patching fastify reply.send function"),function(X){return function(...Y){let Q=Y[0];if(!Z.isEnabled())return X.apply(this,Y);return kZ.safeExecuteInTheMiddle(()=>{return X.apply(this,Y)},(W)=>{if(!W&&Q instanceof Error)W=Q;Yz(this,W)})}}}_hookPreHandler(){let Z=this;return this._diag.debug("Patching fastify preHandler function"),function(X,$,Y){if(!Z.isEnabled())return Y();let Q=X,W=Q.routeOptions?.handler||Q.context?.handler,K=W?.name.startsWith("bound ")?W.name.substring(6):W?.name,z=`${Y3.REQUEST_HANDLER} - ${K||this.pluginName||Fp}`,G={[J9.PLUGIN_NAME]:this.pluginName,[J9.FASTIFY_TYPE]:$3.REQUEST_HANDLER,[Bp.SEMATTRS_HTTP_ROUTE]:Q.routeOptions?Q.routeOptions.url:X.routerPath};if(K)G[J9.FASTIFY_NAME]=K;let H=K2($,Z.tracer,z,G);Up(H);let{requestHook:V}=Z.getConfig();if(V)kZ.safeExecuteInTheMiddle(()=>V(H,{request:X}),(F)=>{if(F)Z._diag.error("request hook failed",F)},!0);return I8.context.with(I8.trace.setSpan(I8.context.active(),H),()=>{Y()})}}}function dx0(){let Z=u();if(Z)Z.on("spanStart",(J)=>{Up(J)})}function Up(Z){let J=J0(Z).data,X=J["fastify.type"];if(J[K0]||!X)return;Z.setAttributes({[X0]:"auto.http.otel.fastify",[K0]:`${X}.fastify`});let $=J["fastify.name"]||J["plugin.name"]||J["hook.name"];if(typeof $==="string"){let Y=$.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(Y)}}var Wz="Fastify",Dp=a(`${Wz}.v3`,()=>new z2);function ux0(){let Z=u();if(!Z)return;else return Z.getIntegrationByName(Wz)}function Lp(Z,J,X,$){let Y=ux0()?.getShouldHandleError()||wp;if($==="diagnostics-channel")this.diagnosticsChannelExists=!0;if(this.diagnosticsChannelExists&&$==="onError-hook"){N1&&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,X))V0(Z,{mechanism:{handled:!1,type:"auto.function.fastify"}})}var _p=a(`${Wz}.v5`,()=>{let Z=new W2,J=Z.plugin();return G2.subscribe("fastify.initialization",(X)=>{let $=X.fastify;$?.register(J).after((Y)=>{if(Y)N1&&A.error("Failed to setup Fastify instrumentation",Y);else if(lx0(),$)px0($)})}),G2.subscribe("tracing:fastify.request.handler:error",(X)=>{let{error:$,request:Y,reply:Q}=X;Lp.call(Lp,$,Y,Q,"diagnostics-channel")}),Z}),cx0=({shouldHandleError:Z})=>{let J;return{name:Wz,setupOnce(){J=Z||wp,Dp(),_p()},getShouldHandleError(){return J},setShouldHandleError(X){J=X}}},Op=S((Z={})=>cx0(Z));function wp(Z,J,X){let $=X.statusCode;return $>=500||$<=299}function jp(Z){let J=J0(Z),X=J.description,$=J.data,Y=$["fastify.type"],Q=Y==="hook",W=Y===X?.startsWith("handler -"),K=X==="request"||Y==="request-handler";if($[K0]||!W&&!K&&!Q)return;let z=Q?"hook":W?"middleware":K?"request-handler":"<unknown>";Z.setAttributes({[X0]:"auto.http.otel.fastify",[K0]:`${z}.fastify`});let G=$["fastify.name"]||$["plugin.name"]||$["hook.name"];if(typeof G==="string"){let H=G.replace(/^fastify -> /,"").replace(/^@fastify\/otel -> /,"");Z.updateName(H)}}function lx0(){let Z=u();if(Z)Z.on("spanStart",(J)=>{jp(J)})}function px0(Z){Z.addHook("onRequest",async(J,X)=>{if(J.opentelemetry){let{span:Q}=J.opentelemetry();if(Q)jp(Q)}let $=J.routeOptions?.url,Y=J.method||"GET";R0().setTransactionName(`${Y} ${$}`)})}var $i=k(f(),1),Yi=k(Xi(),1);var Qi="Graphql",Wi=a(Qi,Yi.GraphQLInstrumentation,(Z)=>{let J=zi(Z);return{...J,responseHook(X,$){if(i0(X,"auto.graphql.otel.graphql"),$.errors?.length&&!J0(X).status)X.setStatus({code:$i.SpanStatusCode.ERROR});let Q=J0(X).data,W=Q["graphql.operation.type"],K=Q["graphql.operation.name"];if(J.useOperationNameForRootSpan&&W){let z=q1(X),H=J0(z).data[LX]||[],V=K?`${W} ${K}`:`${W}`;if(Array.isArray(H))H.push(V),z.setAttribute(LX,H);else if(typeof H==="string")z.setAttribute(LX,[H,V]);else z.setAttribute(LX,V);if(!J0(z).data["original-description"])z.setAttribute("original-description",J0(z).description);z.updateName(`${J0(z).data["original-description"]} (${Mv0(H)})`)}}}}),jv0=(Z={})=>{return{name:Qi,setupOnce(){Wi(zi(Z))}}},Ki=S(jv0);function zi(Z){return{ignoreResolveSpans:!0,ignoreTrivialResolveSpans:!0,useOperationNameForRootSpan:!0,...Z}}function Mv0(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 yi=k(Ii(),1);var Si="Kafka",ki=a(Si,()=>new yi.KafkaJsInstrumentation({consumerHook(Z){i0(Z,"auto.kafkajs.otel.consumer")},producerHook(Z){i0(Z,"auto.kafkajs.otel.producer")}})),dv0=()=>{return{name:Si,setupOnce(){ki()}}},xi=S(dv0);var ii=k(pi(),1);var ni="LruMemoizer",oi=a(ni,()=>new ii.LruMemoizerInstrumentation),pv0=()=>{return{name:ni,setupOnce(){oi()}}},ai=S(pv0);var Fn=k(Vn(),1);var Bn="Mongo",Un=a(Bn,()=>new Fn.MongoDBInstrumentation({dbStatementSerializer:Kh0,responseHook(Z){i0(Z,"auto.db.otel.mongo")}}));function Kh0(Z){let J=A2(Z);return JSON.stringify(J)}function A2(Z){if(Array.isArray(Z))return Z.map((J)=>A2(J));if(zh0(Z)){let J={};return Object.entries(Z).map(([X,$])=>[X,A2($)]).reduce((X,$)=>{if(Hh0($))X[$[0]]=$[1];return X},J)}return"?"}function zh0(Z){return typeof Z==="object"&&Z!==null&&!Gh0(Z)}function Gh0(Z){let J=!1;if(typeof Buffer<"u")J=Buffer.isBuffer(Z);return J}function Hh0(Z){return Array.isArray(Z)}var Vh0=()=>{return{name:Bn,setupOnce(){Un()}}},Ln=S(Vh0);var vn=k(xn(),1);var hn="Mongoose",fn=a(hn,()=>new vn.MongooseInstrumentation({responseHook(Z){i0(Z,"auto.db.otel.mongoose")}})),Sh0=()=>{return{name:hn,setupOnce(){fn()}}},bn=S(Sh0);var Xo=k(Jo(),1);var $o="Mysql",Yo=a($o,()=>new Xo.MySQLInstrumentation({})),$f0=()=>{return{name:$o,setupOnce(){Yo()}}},Qo=S($f0);var qo=k(To(),1);var Co="Mysql2",No=a(Co,()=>new qo.MySQL2Instrumentation({responseHook(Z){i0(Z,"auto.db.otel.mysql2")}})),yf0=()=>{return{name:Co,setupOnce(){No()}}},Ro=S(yf0);var Ra=k(no(),1),Pa=k(Aa(),1);var Bb0=["get","set","setex"],l2=["get","mget"],Ub0=["set","setex"];function L3(Z,J){return Z.includes(J.toLowerCase())}function p2(Z){if(L3(l2,Z))return"cache.get";else if(L3(Ub0,Z))return"cache.put";else return}function Lb0(Z,J){return J.some((X)=>Z.startsWith(X))}function qa(Z,J){try{if(J.length===0)return;let X=(Y)=>{if(typeof Y==="string"||typeof Y==="number"||Buffer.isBuffer(Y))return[Y.toString()];else if(Array.isArray(Y))return Ta(Y.map((Q)=>X(Q)));else return["<unknown>"]},$=J[0];if(L3(Bb0,Z)&&$!=null)return X($);return Ta(J.map((Y)=>X(Y)))}catch{return}}function Ca(Z,J,X){if(!p2(Z))return!1;for(let $ of J)if(Lb0($,X))return!0;return!1}function Na(Z){let J=(X)=>{try{if(Buffer.isBuffer(X))return X.byteLength;else if(typeof X==="string")return X.length;else if(typeof X==="number")return X.toString().length;else if(X===null||X===void 0)return 0;return JSON.stringify(X).length}catch{return}};return Array.isArray(Z)?Z.reduce((X,$)=>{let Y=J($);return typeof Y==="number"?X!==void 0?X+Y:Y:X},0):J(Z)}function Ta(Z){let J=[],X=($)=>{$.forEach((Y)=>{if(Array.isArray(Y))X(Y);else J.push(Y)})};return X(Z),J}var Mz="Redis",D3={},Ea=(Z,J,X,$)=>{Z.setAttribute(X0,"auto.db.otel.redis");let Y=qa(J,X),Q=p2(J);if(!Y||!Q||!D3.cachePrefixes||!Ca(J,Y,D3.cachePrefixes))return;let W=J0(Z).data["net.peer.name"],K=J0(Z).data["net.peer.port"];if(K&&W)Z.setAttributes({"network.peer.address":W,"network.peer.port":K});let z=Na($);if(z)Z.setAttribute(hB,z);if(L3(l2,J)&&z!==void 0)Z.setAttribute(xB,z>0);Z.setAttributes({[K0]:Q,[vB]:Y});let G=Y.join(", ");Z.updateName(D3.maxCacheKeyLength?h9(G,D3.maxCacheKeyLength):G)},Db0=a(`${Mz}.IORedis`,()=>{return new Ra.IORedisInstrumentation({responseHook:Ea})}),_b0=a(`${Mz}.Redis`,()=>{return new Pa.RedisInstrumentation({responseHook:Ea})}),Ia=Object.assign(()=>{Db0(),_b0()},{id:Mz}),Ob0=(Z={})=>{return{name:Mz,setupOnce(){D3=Z,Ia()}}},ya=S(Ob0);var Kr=k(Wr(),1);var zr="Postgres",Gr=a(zr,()=>new Kr.PgInstrumentation({requireParentSpan:!0,requestHook(Z){i0(Z,"auto.db.otel.postgres")}})),Hg0=()=>{return{name:zr,setupOnce(){Gr()}}},Hr=S(Hg0);var hX=k(f(),1),Q9=k(H0(),1),x1=k(p0(),1);var Pz="PostgresJs",Vr=[">=3.0.0 <4"],Vg0=/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i,Rz=Symbol("sentryPostgresConnectionContext"),t2=Symbol.for("sentry.instrumented.postgresjs"),Fr=Symbol.for("sentry.query.from.instrumented.sql"),Br=a(Pz,(Z)=>new Ur({requireParentSpan:Z?.requireParentSpan??!0,requestHook:Z?.requestHook}));class Ur extends Q9.InstrumentationBase{constructor(Z){super("sentry-postgres-js",N0,Z)}init(){let Z=new Q9.InstrumentationNodeModuleDefinition("postgres",Vr,(J)=>{try{return this._patchPostgres(J)}catch(X){return N1&&A.error("Failed to patch postgres module:",X),J}},(J)=>J);return["src","cf/src","cjs/src"].forEach((J)=>{Z.files.push(new Q9.InstrumentationNodeModuleFile(`postgres/${J}/query.js`,Vr,this._patchQueryPrototype.bind(this),this._unpatchQueryPrototype.bind(this)))}),Z}_patchPostgres(Z){let J=typeof Z==="function",X=J?Z:Z.default;if(typeof X!=="function")return N1&&A.warn("postgres module does not export a function. Skipping instrumentation."),Z;let $=this,Y=function(...Q){let W=Reflect.construct(X,Q);if(!W||typeof W!=="function")return N1&&A.warn("postgres() did not return a valid instance"),W;return $._instrumentSqlInstance(W)};Object.setPrototypeOf(Y,X),Object.setPrototypeOf(Y.prototype,X.prototype);for(let Q of Object.getOwnPropertyNames(X))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor(X,Q);if(W)Object.defineProperty(Y,Q,W)}if(J)return Y;else return RY(Z,"default",Y),Z}_wrapQueryMethod(Z,J,X){let $=this;return function(...Y){let Q=Reflect.apply(Z,J,Y);if(Q&&typeof Q==="object"&&"handle"in Q)$._wrapSingleQueryHandle(Q,X);return Q}}_wrapCallbackMethod(Z,J,X){let $=this;return function(...Y){let Q=X[Rz];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 $._instrumentSqlInstance(V,Q)});return H}let K=Y.length===1?Y[0]:Y[1],z=function(H){let V=$._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(x1.ATTR_DB_NAMESPACE,J.ATTR_DB_NAMESPACE);if(J.ATTR_SERVER_ADDRESS)Z.setAttribute(x1.ATTR_SERVER_ADDRESS,J.ATTR_SERVER_ADDRESS);if(J.ATTR_SERVER_PORT!==void 0){let X=parseInt(J.ATTR_SERVER_PORT,10);if(!isNaN(X))Z.setAttribute(x1.ATTR_SERVER_PORT,X)}}_setOperationName(Z,J,X){if(X){Z.setAttribute(x1.ATTR_DB_OPERATION_NAME,X);return}let $=J?.match(Vg0);if($?.[1])Z.setAttribute(x1.ATTR_DB_OPERATION_NAME,$[1].toUpperCase())}_attachConnectionContext(Z,J){let X=Z;if(!X.options||typeof X.options!=="object")return;let $=X.options,Y=$.host?.[0]||"localhost",Q=$.port?.[0]||5432,W={ATTR_DB_NAMESPACE:typeof $.database==="string"&&$.database!==""?$.database:void 0,ATTR_SERVER_ADDRESS:Y,ATTR_SERVER_PORT:String(Q)};J[Rz]=W}_instrumentSqlInstance(Z,J){if(Z[t2])return Z;let X=this,$=new Proxy(Z,{apply(Y,Q,W){let K=Reflect.apply(Y,Q,W);if(K&&typeof K==="object"&&"handle"in K)X._wrapSingleQueryHandle(K,$);return K},get(Y,Q){let W=Y[Q];if(typeof Q!=="string"||typeof W!=="function")return W;if(Q==="unsafe"||Q==="file")return X._wrapQueryMethod(W,Y,$);if(Q==="begin"||Q==="reserve")return X._wrapCallbackMethod(W,Y,$);return W}});if(J)$[Rz]=J;else this._attachConnectionContext(Z,$);return Z[t2]=!0,$[t2]=!0,$}_wrapSingleQueryHandle(Z,J){if(Z.handle?.__sentryWrapped)return;Z[Fr]=!0;let X=Z.handle,$=this,Y=async function(...Q){if(!$._shouldCreateSpans())return X.apply(this,Q);let W=$._reconstructQuery(Z.strings),K=$._sanitizeSqlQuery(W);return z4({name:K||"postgresjs.query",op:"db"},(z)=>{i0(z,"auto.db.postgresjs"),z.setAttributes({[x1.ATTR_DB_SYSTEM_NAME]:"postgres",[x1.ATTR_DB_QUERY_TEXT]:K});let G=J?J[Rz]:void 0;$._setConnectionAttributes(z,G);let H=$.getConfig(),{requestHook:V}=H;if(V)Q9.safeExecuteInTheMiddle(()=>V(z,K,G),(B)=>{if(B)z.setAttribute("sentry.hook.error","requestHook failed"),N1&&A.error(`Error in requestHook for ${Pz} integration:`,B)},!0);let F=this;F.resolve=new Proxy(F.resolve,{apply:(B,U,D)=>{try{$._setOperationName(z,K,D?.[0]?.command),z.end()}catch(_){N1&&A.error("Error ending span in resolve callback:",_)}return Reflect.apply(B,U,D)}}),F.reject=new Proxy(F.reject,{apply:(B,U,D)=>{try{z.setStatus({code:A0,message:D?.[0]?.message||"unknown_error"}),z.setAttribute(x1.ATTR_DB_RESPONSE_STATUS_CODE,D?.[0]?.code||"unknown"),z.setAttribute(x1.ATTR_ERROR_TYPE,D?.[0]?.name||"unknown"),$._setOperationName(z,K),z.end()}catch(_){N1&&A.error("Error ending span in reject callback:",_)}return Reflect.apply(B,U,D)}});try{return X.apply(this,Q)}catch(B){throw z.setStatus({code:A0,message:B instanceof Error?B.message:"unknown_error"}),z.end(),B}})};Y.__sentryWrapped=!0,Z.handle=Y}_shouldCreateSpans(){let Z=this.getConfig();return hX.trace.getSpan(hX.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,$)=>$===0?X:`${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,X=Z.Query.prototype.handle;return Z.Query.prototype.handle=async function(...$){if(this[Fr])return X.apply(this,$);if(!J._shouldCreateSpans())return X.apply(this,$);let Y=J._reconstructQuery(this.strings),Q=J._sanitizeSqlQuery(Y);return z4({name:Q||"postgresjs.query",op:"db"},(W)=>{i0(W,"auto.db.postgresjs"),W.setAttributes({[x1.ATTR_DB_SYSTEM_NAME]:"postgres",[x1.ATTR_DB_QUERY_TEXT]:Q});let K=J.getConfig(),{requestHook:z}=K;if(z)Q9.safeExecuteInTheMiddle(()=>z(W,Q,void 0),(V)=>{if(V)W.setAttribute("sentry.hook.error","requestHook failed"),N1&&A.error(`Error in requestHook for ${Pz} 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){N1&&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:A0,message:B?.[0]?.message||"unknown_error"}),W.setAttribute(x1.ATTR_DB_RESPONSE_STATUS_CODE,B?.[0]?.code||"unknown"),W.setAttribute(x1.ATTR_ERROR_TYPE,B?.[0]?.name||"unknown"),J._setOperationName(W,Q),W.end()}catch(U){N1&&A.error("Error ending span in reject callback:",U)}return Reflect.apply(V,F,B)}});try{return X.apply(this,$)}catch(V){throw W.setStatus({code:A0,message:V instanceof Error?V.message:"unknown_error"}),W.end(),V}})},Z.Query.prototype.handle.__sentry_original__=X,Z}_unpatchQueryPrototype(Z){if(Z.Query.prototype.handle.__sentry_original__)Z.Query.prototype.handle=Z.Query.prototype.handle.__sentry_original__;return Z}}var Fg0=(Z)=>{return{name:Pz,setupOnce(){Br(Z)}}},Lr=S(Fg0);var r6=k(f(),1);var Or=k(f(),1),Ez=k(H0(),1),O7=k(f(),1);var Bg0=process.env.PRISMA_SHOW_ALL_TRACES==="true",Ug0="00-10-10-00";function Lg0(Z){switch(Z){case"client":return O7.SpanKind.CLIENT;case"internal":default:return O7.SpanKind.INTERNAL}}var Dg0=class{tracerProvider;ignoreSpanTypes;constructor({tracerProvider:Z,ignoreSpanTypes:J}){this.tracerProvider=Z,this.ignoreSpanTypes=J}isEnabled(){return!0}getTraceParent(Z){let J=O7.trace.getSpanContext(Z??O7.context.active());if(J)return`00-${J.traceId}-${J.spanId}-0${J.traceFlags}`;return Ug0}dispatchEngineSpans(Z){let J=this.tracerProvider.getTracer("prisma"),X=new Map,$=Z.filter((Y)=>Y.parentId===null);for(let Y of $)wr(J,Y,Z,X,this.ignoreSpanTypes)}getActiveContext(){return O7.context.active()}runInChildSpan(Z,J){if(typeof Z==="string")Z={name:Z};if(Z.internal&&!Bg0)return J();let X=this.tracerProvider.getTracer("prisma"),$=Z.context??this.getActiveContext(),Y=`prisma:client:${Z.name}`;if(jr(Y,this.ignoreSpanTypes))return J();if(Z.active===!1){let Q=X.startSpan(Y,Z,$);return Dr(Q,J(Q,$))}return X.startActiveSpan(Y,Z,(Q)=>Dr(Q,J(Q,$)))}};function wr(Z,J,X,$,Y){if(jr(J.name,Y))return;let Q={attributes:J.attributes,kind:Lg0(J.kind),startTime:J.startTime};Z.startActiveSpan(J.name,Q,(W)=>{if($.set(J.id,W.spanContext().spanId),J.links)W.addLinks(J.links.flatMap((z)=>{let G=$.get(z);if(!G)return[];return{context:{spanId:G,traceId:W.spanContext().traceId,traceFlags:W.spanContext().traceFlags}}}));let K=X.filter((z)=>z.parentId===J.id);for(let z of K)wr(Z,z,X,$,Y);W.end(J.endTime)})}function Dr(Z,J){if(_g0(J))return J.then((X)=>{return Z.end(),X},(X)=>{throw Z.end(),X});return Z.end(),J}function _g0(Z){return Z!=null&&typeof Z.then==="function"}function jr(Z,J){return J.some((X)=>typeof X==="string"?X===Z:X.test(Z))}var Mr={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},ZD=Mr.version,Og0=ZD.split(".")[0],_r="PRISMA_INSTRUMENTATION",e2=`V${Og0}_PRISMA_INSTRUMENTATION`,wg0=Mr.name,jg0="@prisma/client",Ar=class extends Ez.InstrumentationBase{tracerProvider;constructor(Z={}){super(wg0,ZD,Z)}setTracerProvider(Z){this.tracerProvider=Z}init(){return[new Ez.InstrumentationNodeModuleDefinition(jg0,[ZD])]}enable(){let Z=this._config,J={helper:new Dg0({tracerProvider:this.tracerProvider??Or.trace.getTracerProvider(),ignoreSpanTypes:Z.ignoreSpanTypes??[]})};global[_r]=J,global[e2]=J}disable(){delete global[_r],delete global[e2]}isEnabled(){return Boolean(global[e2])}};var Tr="Prisma";function Mg0(Z){return!!Z&&typeof Z==="object"&&"dispatchEngineSpans"in Z}function qr(){let Z=globalThis.PRISMA_INSTRUMENTATION;return Z&&typeof Z==="object"&&"helper"in Z?Z.helper:void 0}class Cr extends Ar{constructor(){super()}enable(){super.enable();let Z=qr();if(Mg0(Z))Z.createEngineSpan=(J)=>{let X=r6.trace.getTracer("prismaV5Compatibility"),$=X._idGenerator;if(!$){y1(()=>{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=Ag0(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:r6.TraceFlags.SAMPLED}}}),H=r6.trace.setSpanContext(r6.context.active(),{traceId:z,spanId:W,traceFlags:r6.TraceFlags.SAMPLED});r6.context.with(H,()=>{let V={generateTraceId:()=>{return z},generateSpanId:()=>{return K}};X._idGenerator=V,X.startSpan(Y.name,{kind:Q,links:G,startTime:Y.start_time,attributes:Y.attributes}).end(Y.end_time),X._idGenerator=$})})}finally{X._idGenerator=$}}}}function Ag0(Z){switch(Z){case"client":return r6.SpanKind.CLIENT;case"internal":default:return r6.SpanKind.INTERNAL}}var Tg0=a(Tr,(Z)=>{return new Cr}),Nr=S((Z)=>{return{name:Tr,setupOnce(){Tg0()},setup(J){if(!qr())return;J.on("spanStart",(X)=>{let $=J0(X);if($.description?.startsWith("prisma:"))X.setAttribute(X0,"auto.db.otel.prisma");if($.description==="prisma:engine:db_query"&&$.data["db.query.text"])X.updateName($.data["db.query.text"]);if($.description==="prisma:engine:db_query"&&!$.data["db.system"])X.setAttribute("db.system","prisma")})}}});var or=k(nr(),1);var ar="Hapi",rr=a(ar,()=>new or.HapiInstrumentation),ng0=()=>{return{name:ar,setupOnce(){rr()}}},sr=S(ng0);var Sz=k(p0(),1);var j7={HONO_TYPE:"hono.type",HONO_NAME:"hono.name"},M3={MIDDLEWARE:"middleware",REQUEST_HANDLER:"request_handler"};var hZ=k(f(),1),yz=k(H0(),1);var og0="@sentry/instrumentation-hono",ag0="0.0.1";class QD extends yz.InstrumentationBase{constructor(Z={}){super(og0,ag0,Z)}init(){return[new yz.InstrumentationNodeModuleDefinition("hono",[">=4.0.0 <5"],(Z)=>this._patch(Z))]}_patch(Z){let J=this;class X extends Z.Hono{constructor(...$){super(...$);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=X}catch{return{...Z,Hono:X}}return Z}_patchHandler(){let Z=this;return function(J){return function(...$){if(typeof $[0]==="string"){let Y=$[0];if($.length===1)return J.apply(this,[Y]);let Q=$.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,$.map((Y)=>Z._wrapHandler(Y)))}}}_patchOnHandler(){let Z=this;return function(J){return function(...$){let Y=$.slice(2);return J.apply(this,[...$.slice(0,2),...Y.map((Q)=>Z._wrapHandler(Q))])}}}_patchMiddlewareHandler(){let Z=this;return function(J){return function(...$){if(typeof $[0]==="string"){let Y=$[0];if($.length===1)return J.apply(this,[Y]);let Q=$.slice(1);return J.apply(this,[Y,...Q.map((W)=>Z._wrapHandler(W))])}return J.apply(this,$.map((Y)=>Z._wrapHandler(Y)))}}}_wrapHandler(Z){let J=this;return function(X,$){if(!J.isEnabled())return Z.apply(this,[X,$]);let Y=X.req.path,Q=J.tracer.startSpan(Y);return hZ.context.with(hZ.trace.setSpan(hZ.context.active(),Q),()=>{return J._safeExecute(()=>{let W=Z.apply(this,[X,$]);if(I4(W))return W.then((K)=>{let z=J._determineHandlerType(K);return Q.setAttributes({[j7.HONO_TYPE]:z,[j7.HONO_NAME]:z===M3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),K});else{let K=J._determineHandlerType(W);return Q.setAttributes({[j7.HONO_TYPE]:K,[j7.HONO_NAME]:K===M3.REQUEST_HANDLER?Y:Z.name||"anonymous"}),J.getConfig().responseHook?.(Q),W}},()=>Q.end(),(W)=>{J._handleError(Q,W),Q.end()})})}}_safeExecute(Z,J,X){try{let $=Z();if(I4($))$.then(()=>J(),(Y)=>X(Y));else J();return $}catch($){throw X($),$}}_determineHandlerType(Z){return Z===void 0?M3.MIDDLEWARE:M3.REQUEST_HANDLER}_handleError(Z,J){if(J instanceof Error)Z.setStatus({code:hZ.SpanStatusCode.ERROR,message:J.message}),Z.recordException(J)}}var tr="Hono";function rg0(Z){let J=J0(Z).data,X=J[j7.HONO_TYPE];if(J[K0]||!X)return;Z.setAttributes({[X0]:"auto.http.otel.hono",[K0]:`${X}.hono`});let $=J[j7.HONO_NAME];if(typeof $==="string")Z.updateName($);if(R0()===B6()){N1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let Y=J[Sz.ATTR_HTTP_ROUTE],Q=J[Sz.ATTR_HTTP_REQUEST_METHOD];if(typeof Y==="string"&&typeof Q==="string")R0().setTransactionName(`${Q} ${Y}`)}var er=a(tr,()=>new QD({responseHook:(Z)=>{rg0(Z)}})),sg0=()=>{return{name:tr,setupOnce(){er()}}},Zs=S(sg0);var Ts=k(As(),1),qs=k(p0(),1);var Cs="Koa",Ns=a(Cs,Ts.KoaInstrumentation,(Z={})=>{return{ignoreLayersType:Z.ignoreLayersType,requestHook(J,X){i0(J,"auto.http.otel.koa");let $=J0(J).data,Y=$["koa.type"];if(Y)J.setAttribute(K0,`${Y}.koa`);let Q=$["koa.name"];if(typeof Q==="string")J.updateName(Q||"< unknown >");if(R0()===B6()){N1&&A.warn("Isolation scope is default isolation scope - skipping setting transactionName");return}let W=$[qs.ATTR_HTTP_ROUTE],K=X.context?.request?.method?.toUpperCase()||"GET";if(W)R0().setTransactionName(`${K} ${W}`)}}}),Gm0=(Z={})=>{return{name:Cs,setupOnce(){Ns(Z)}}},Rs=S(Gm0);var os=k(ns(),1);var as="Connect",rs=a(as,()=>new os.ConnectInstrumentation),Tm0=()=>{return{name:as,setupOnce(){rs()}}},ss=S(Tm0);var Lt=k(Ut(),1);var bm0=new Set(["callProcedure","execSql","execSqlBatch","execBulkLoad","prepare","execute"]),Dt="Tedious",_t=a(Dt,()=>new Lt.TediousInstrumentation({})),gm0=()=>{let Z;return{name:Dt,setupOnce(){let J=_t();Z=EY(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let{description:$,data:Y}=J0(X);if(!$||Y["db.system"]!=="mssql")return;let Q=$.split(" ")[0]||"";if(bm0.has(Q))X.setAttribute(X0,"auto.db.otel.tedious")}))}}},Ot=S(gm0);var Pt=k(Rt(),1);var Et="GenericPool",It=a(Et,()=>new Pt.GenericPoolInstrumentation({})),cm0=()=>{let Z;return{name:Et,setupOnce(){let J=It();Z=EY(J)},setup(J){Z?.(()=>J.on("spanStart",(X)=>{let Y=J0(X).description;if(Y==="generic-pool.aquire"||Y==="generic-pool.acquire")X.setAttribute(X0,"auto.db.otel.generic_pool")}))}}},yt=S(cm0);var Je=k(Ze(),1);var Xe="Amqplib",Td0={consumeEndHook:(Z)=>{i0(Z,"auto.amqplib.otel.consumer")},publishHook:(Z)=>{i0(Z,"auto.amqplib.otel.publisher")}},$e=a(Xe,()=>new Je.AmqplibInstrumentation(Td0)),qd0=()=>{return{name:Xe,setupOnce(){$e()}}},Ye=S(qd0);var N3="VercelAI";var dz=k(H0(),1);var Cd0=[">=3.0.0 <7"],Qe=["generateText","streamText","generateObject","streamObject","embed","embedMany"];function Nd0(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 Rd0(Z){if(typeof Z!=="object"||Z===null||!("content"in Z))return;let J=Z;if(!Array.isArray(J.content))return;for(let X of J.content)if(Nd0(X)){let $=PU(X.toolCallId);if($){let Y=$.spanContext();s4((Q)=>{Q.setContext("trace",{trace_id:Y.traceId,span_id:Y.spanId}),Q.setTag("vercel.ai.tool.name",X.toolName),Q.setTag("vercel.ai.tool.callId",X.toolCallId),Q.setLevel("error"),V0(X.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})}),EU(X.toolCallId)}else s4((Y)=>{Y.setTag("vercel.ai.tool.name",X.toolName),Y.setTag("vercel.ai.tool.callId",X.toolCallId),Y.setLevel("error"),V0(X.error,{mechanism:{type:"auto.vercelai.otel",handled:!1}})})}}function Pd0(Z,J,X,$){let Y=Z?.recordInputs!==void 0?Z.recordInputs:J.recordInputs!==void 0?J.recordInputs:X===!0?!0:$,Q=Z?.recordOutputs!==void 0?Z.recordOutputs:J.recordOutputs!==void 0?J.recordOutputs:X===!0?!0:$;return{recordInputs:Y,recordOutputs:Q}}class R3 extends dz.InstrumentationBase{__init(){this._isPatched=!1}__init2(){this._callbacks=[]}constructor(Z={}){super("@sentry/instrumentation-vercel-ai",N0,Z);R3.prototype.__init.call(this),R3.prototype.__init2.call(this)}init(){return new dz.InstrumentationNodeModuleDefinition("ai",Cd0,this._patch.bind(this))}callWhenPatched(Z){if(this._isPatched)Z();else this._callbacks.push(Z)}_patch(Z){this._isPatched=!0,this._callbacks.forEach((X)=>X()),this._callbacks=[];let J=(X)=>{return new Proxy(X,{apply:($,Y,Q)=>{let W=Q[0].experimental_telemetry||{},K=W.isEnabled,z=u(),G=z?.getIntegrationByName(N3),H=G?.options,V=G?Boolean(z?.getOptions().sendDefaultPii):!1,{recordInputs:F,recordOutputs:B}=Pd0(H,W,K,V);return Q[0].experimental_telemetry={...W,isEnabled:K!==void 0?K:!0,recordInputs:F,recordOutputs:B},D6(()=>Reflect.apply($,Y,Q),(U)=>{if(U&&typeof U==="object")f1(U,"_sentry_active_span",t8())},()=>{},(U)=>{Rd0(U)})}})};if(Object.prototype.toString.call(Z)==="[object Module]"){for(let X of Qe)Z[X]=J(Z[X]);return Z}else{let X=Qe.reduce(($,Y)=>{return $[Y]=J(Z[Y]),$},{});return{...Z,...X}}}}var We=a(N3,()=>new R3({}));function Ed0(Z){return!!Z.getIntegrationByName("Modules")?.getModules?.()?.ai}var Id0=(Z={})=>{let J;return{name:N3,options:Z,setupOnce(){J=We()},afterAllSetup(X){if(Z.force??Ed0(X))GK(X);else J?.callWhenPatched(()=>GK(X))}}},Ke=S(Id0);var uz=k(H0(),1);var yd0=[">=4.0.0 <7"];class qD extends uz.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-openai",N0,Z)}init(){return new uz.InstrumentationNodeModuleDefinition("openai",yd0,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 X=Z[J];if(!X)return Z;let $=this.getConfig(),Y=function(...Q){if(jZ(Y7))return Reflect.construct(X,Q);let W=Reflect.construct(X,Q),K=u(),z=Boolean(K?.getOptions().sendDefaultPii),G=$.recordInputs??z,H=$.recordOutputs??z;return FK(W,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf(Y,X),Object.setPrototypeOf(Y.prototype,X.prototype);for(let Q of Object.getOwnPropertyNames(X))if(!["length","name","prototype"].includes(Q)){let W=Object.getOwnPropertyDescriptor(X,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===X)try{Z.default=Y}catch(Q){Object.defineProperty(Z,"default",{value:Y,writable:!0,configurable:!0,enumerable:!0})}return Z}}var ze=a(Y7,(Z)=>new qD(Z)),Sd0=(Z={})=>{return{name:Y7,setupOnce(){ze(Z)}}},Ge=S(Sd0);var cz=k(H0(),1);var kd0=[">=0.19.2 <1.0.0"];class CD extends cz.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-anthropic-ai",N0,Z)}init(){return new cz.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk",kd0,this._patch.bind(this))}_patch(Z){let J=Z.Anthropic,X=this.getConfig(),$=function(...Y){if(jZ(Q7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=u(),K=Boolean(W?.getOptions().sendDefaultPii),z=X.recordInputs??K,G=X.recordOutputs??K;return SU(Q,{recordInputs:z,recordOutputs:G})};Object.setPrototypeOf($,J),Object.setPrototypeOf($.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($,Y,Q)}try{Z.Anthropic=$}catch(Y){Object.defineProperty(Z,"Anthropic",{value:$,writable:!0,configurable:!0,enumerable:!0})}if(Z.default===J)try{Z.default=$}catch(Y){Object.defineProperty(Z,"default",{value:$,writable:!0,configurable:!0,enumerable:!0})}return Z}}var He=a(Q7,(Z)=>new CD(Z)),xd0=(Z={})=>{return{name:Q7,options:Z,setupOnce(){He(Z)}}},Ve=S(xd0);var dX=k(H0(),1);var Fe=[">=0.10.0 <2"];class ND extends dX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-google-genai",N0,Z)}init(){return new dX.InstrumentationNodeModuleDefinition("@google/genai",Fe,(J)=>this._patch(J),(J)=>J,[new dX.InstrumentationNodeModuleFile("@google/genai/dist/node/index.cjs",Fe,(J)=>this._patch(J),(J)=>J)])}_patch(Z){let J=Z.GoogleGenAI,X=this.getConfig();if(typeof J!=="function")return Z;let $=function(...Y){if(jZ(W7))return Reflect.construct(J,Y);let Q=Reflect.construct(J,Y),W=u(),K=Boolean(W?.getOptions().sendDefaultPii),z=X,G=z?.recordInputs??K,H=z?.recordOutputs??K;return hU(Q,{recordInputs:G,recordOutputs:H})};Object.setPrototypeOf($,J),Object.setPrototypeOf($.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($,Y,Q)}return RY(Z,"GoogleGenAI",$),Z}}var Be=a(W7,(Z)=>new ND(Z)),vd0=(Z={})=>{return{name:W7,setupOnce(){Be(Z)}}},Ue=S(vd0);var T7=k(H0(),1);var lz=[">=0.1.0 <2.0.0"];function hd0(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 fd0(Z,J,X){return new Proxy(Z,{apply($,Y,Q){let K=Q[1];if(!K||typeof K!=="object"||Array.isArray(K))K={},Q[1]=K;let z=K.callbacks,G=hd0(z,J);return K.callbacks=G,Reflect.apply($,Y,Q)}})}class RD extends T7.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langchain",N0,Z)}init(){let Z=[],J=["@langchain/anthropic","@langchain/openai","@langchain/google-genai","@langchain/mistralai","@langchain/google-vertexai","@langchain/groq"];for(let X of J)Z.push(new T7.InstrumentationNodeModuleDefinition(X,lz,this._patch.bind(this),($)=>$,[new T7.InstrumentationNodeModuleFile(`${X}/dist/index.cjs`,lz,this._patch.bind(this),($)=>$)]));return Z.push(new T7.InstrumentationNodeModuleDefinition("langchain",lz,this._patch.bind(this),(X)=>X,[new T7.InstrumentationNodeModuleFile("langchain/dist/chat_models/universal.cjs",lz,this._patch.bind(this),(X)=>X)])),Z}_patch(Z){zU([Y7,Q7,W7]);let J=u(),X=Boolean(J?.getOptions().sendDefaultPii),$=this.getConfig(),Y=$?.recordInputs??X,Q=$?.recordOutputs??X,W=UK({recordInputs:Y,recordOutputs:Q});return this._patchRunnableMethods(Z,W),Z}_patchRunnableMethods(Z,J){let X=["ChatAnthropic","ChatOpenAI","ChatGoogleGenerativeAI","ChatMistralAI","ChatVertexAI","ChatGroq","ConfigurableModel"],$=Z.universal_exports??Z,Y=Object.values($).find((K)=>{return typeof K==="function"&&X.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]=fd0(z,J)}}}var Le=a(BK,(Z)=>new RD(Z)),bd0=(Z={})=>{return{name:BK,setupOnce(){Le(Z)}}},De=S(bd0);var uX=k(H0(),1);var _e=[">=0.0.0 <2.0.0"];class PD extends uX.InstrumentationBase{constructor(Z={}){super("@sentry/instrumentation-langgraph",N0,Z)}init(){return new uX.InstrumentationNodeModuleDefinition("@langchain/langgraph",_e,this._patch.bind(this),(J)=>J,[new uX.InstrumentationNodeModuleFile("@langchain/langgraph/dist/index.cjs",_e,this._patch.bind(this),(J)=>J)])}_patch(Z){let J=u(),X=Boolean(J?.getOptions().sendDefaultPii),$=this.getConfig(),Y=$.recordInputs??X,Q=$.recordOutputs??X,W={recordInputs:Y,recordOutputs:Q};if(Z.StateGraph&&typeof Z.StateGraph==="function"){let K=Z.StateGraph;K.prototype.compile=gU(K.prototype.compile,W)}return Z}}var Oe=a(LK,(Z)=>new PD(Z)),gd0=(Z={})=>{return{name:LK,setupOnce(){Oe(Z)}}},we=S(gd0);var Re=k(H0(),1);var K9=k(f(),1),z9=k(H0(),1),s6=k(p0(),1);import*as Me from"net";function Ae(Z,J,X,$,Y){let W=()=>{},K=Y.firestoreSpanCreationHook;if(typeof K==="function")W=(H)=>{z9.safeExecuteInTheMiddle(()=>K(H),(V)=>{if(!V)return;K9.diag.error(V?.message)},!0)};let z=new z9.InstrumentationNodeModuleDefinition("@firebase/firestore",J,(H)=>je(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 z9.InstrumentationNodeModuleFile(H,J,(V)=>je(V,X,$,Z,W),(V)=>Te(V,$)));return z}function je(Z,J,X,$,Y){return Te(Z,X),J(Z,"addDoc",md0($,Y)),J(Z,"getDocs",ud0($,Y)),J(Z,"setDoc",cd0($,Y)),J(Z,"deleteDoc",dd0($,Y)),Z}function Te(Z,J){for(let X of["addDoc","getDocs","setDoc","deleteDoc"])if(z9.isWrapped(Z[X]))J(Z,X);return Z}function md0(Z,J){return function($){return function(Y,Q){let W=iz(Z,"addDoc",Y);return J(W),pz(W,()=>{return $(Y,Q)})}}}function dd0(Z,J){return function($){return function(Y){let Q=iz(Z,"deleteDoc",Y.parent||Y);return J(Q),pz(Q,()=>{return $(Y)})}}}function ud0(Z,J){return function($){return function(Y){let Q=iz(Z,"getDocs",Y);return J(Q),pz(Q,()=>{return $(Y)})}}}function cd0(Z,J){return function($){return function(Y,Q,W){let K=iz(Z,"setDoc",Y.parent||Y);return J(K),pz(K,()=>{return typeof W<"u"?$(Y,Q,W):$(Y,Q)})}}}function pz(Z,J){return K9.context.with(K9.trace.setSpan(K9.context.active(),Z),()=>{return z9.safeExecuteInTheMiddle(()=>{return J()},(X)=>{if(X)Z.recordException(X);Z.end()},!0)})}function iz(Z,J,X){let $=Z.startSpan(`${J} ${X.path}`,{kind:K9.SpanKind.CLIENT});return pd0($,X),$.setAttribute(s6.ATTR_DB_OPERATION_NAME,J),$}function ld0(Z){let J,X;if(typeof Z.host==="string")if(Z.host.startsWith("[")){if(Z.host.endsWith("]"))J=Z.host.replace(/^\[|\]$/g,"");else if(Z.host.includes("]:")){let $=Z.host.lastIndexOf(":");if($!==-1)J=Z.host.slice(1,$).replace(/^\[|\]$/g,""),X=Z.host.slice($+1)}}else if(Me.isIPv6(Z.host))J=Z.host;else{let $=Z.host.lastIndexOf(":");if($!==-1)J=Z.host.slice(0,$),X=Z.host.slice($+1);else J=Z.host}return{address:J,port:X?parseInt(X,10):void 0}}function pd0(Z,J){let X=J.firestore.app,$=X.options,Q=(J.firestore.toJSON()||{}).settings||{},W={[s6.ATTR_DB_COLLECTION_NAME]:J.path,[s6.ATTR_DB_NAMESPACE]:X.name,[s6.ATTR_DB_SYSTEM_NAME]:"firebase.firestore","firebase.firestore.type":J.type,"firebase.firestore.options.projectId":$.projectId,"firebase.firestore.options.appId":$.appId,"firebase.firestore.options.messagingSenderId":$.messagingSenderId,"firebase.firestore.options.storageBucket":$.storageBucket},{address:K,port:z}=ld0(Q);if(K)W[s6.ATTR_SERVER_ADDRESS]=K;if(z)W[s6.ATTR_SERVER_PORT]=z;Z.setAttributes(W)}var G5=k(f(),1),G9=k(H0(),1);function qe(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)=>{G9.safeExecuteInTheMiddle(()=>G(F,B),(U)=>{if(!U)return;G5.diag.error(U?.message)},!0)};if(typeof z==="function")Q=(F)=>{G9.safeExecuteInTheMiddle(()=>z(F),(B)=>{if(!B)return;G5.diag.error(B?.message)},!0)};let H=new G9.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 G9.InstrumentationNodeModuleFile(F,J,(U)=>id0(U,X,$,Z,{requestHook:Q,responseHook:W,errorHook:K},B),(U)=>Ce(U,$)))}),H}function f4(Z,J,X){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.${X}`,{kind:G5.SpanKind.SERVER}),F={"faas.name":H,"faas.trigger":X,"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),G5.context.with(G5.trace.setSpan(G5.context.active(),V),async()=>{let B,U;try{U=await W.apply(this,G)}catch(D){B=D}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 id0(Z,J,X,$,Y,Q){switch(Ce(Z,X),Q){case"function":J(Z,"onRequest",f4($,Y,"http.request")),J(Z,"onCall",f4($,Y,"http.call"));break;case"firestore":J(Z,"onDocumentCreated",f4($,Y,"firestore.document.created")),J(Z,"onDocumentUpdated",f4($,Y,"firestore.document.updated")),J(Z,"onDocumentDeleted",f4($,Y,"firestore.document.deleted")),J(Z,"onDocumentWritten",f4($,Y,"firestore.document.written")),J(Z,"onDocumentCreatedWithAuthContext",f4($,Y,"firestore.document.created")),J(Z,"onDocumentUpdatedWithAuthContext",f4($,Y,"firestore.document.updated")),J(Z,"onDocumentDeletedWithAuthContext",f4($,Y,"firestore.document.deleted")),J(Z,"onDocumentWrittenWithAuthContext",f4($,Y,"firestore.document.written"));break;case"scheduler":J(Z,"onSchedule",f4($,Y,"scheduler.scheduled"));break;case"storage":J(Z,"onObjectFinalized",f4($,Y,"storage.object.finalized")),J(Z,"onObjectArchived",f4($,Y,"storage.object.archived")),J(Z,"onObjectDeleted",f4($,Y,"storage.object.deleted")),J(Z,"onObjectMetadataUpdated",f4($,Y,"storage.object.metadataUpdated"));break}return Z}function Ce(Z,J){let X=["onSchedule","onRequest","onCall","onObjectFinalized","onObjectArchived","onObjectDeleted","onObjectMetadataUpdated","onDocumentCreated","onDocumentUpdated","onDocumentDeleted","onDocumentWritten","onDocumentCreatedWithAuthContext","onDocumentUpdatedWithAuthContext","onDocumentDeletedWithAuthContext","onDocumentWrittenWithAuthContext"];for(let $ of X)if(G9.isWrapped(Z[$]))J(Z,$);return Z}var Ne={},nd0=[">=3.0.0 <5"],od0=[">=6.0.0 <7"];class ED extends Re.InstrumentationBase{constructor(Z=Ne){super("@sentry/instrumentation-firebase",N0,Z)}setConfig(Z={}){super.setConfig({...Ne,...Z})}init(){let Z=[];return Z.push(Ae(this.tracer,nd0,this._wrap,this._unwrap,this.getConfig())),Z.push(qe(this.tracer,od0,this._wrap,this._unwrap,this.getConfig())),Z}}var Pe="Firebase",ad0={firestoreSpanCreationHook:(Z)=>{i0(Z,"auto.firebase.otel.firestore"),Z.setAttribute(K0,"db.query")},functions:{requestHook:(Z)=>{i0(Z,"auto.firebase.otel.functions"),Z.setAttribute(K0,"http.request")},errorHook:async(Z,J)=>{if(J)V0(J,{mechanism:{type:"auto.firebase.otel.functions",handled:!1}}),await oW(2000)}}},Ee=a(Pe,()=>new ED(ad0)),rd0=()=>{return{name:Pe,setupOnce(){Ee()}}},Ie=S(rd0);function P3(){return[yl(),Op(),Ki(),Zs(),Ln(),bn(),Qo(),Ro(),ya(),Hr(),Nr(),sr(),Rs(),ss(),Ot(),yt(),xi(),Ye(),ai(),De(),we(),Ke(),Ge(),Ve(),Ue(),Lr(),Ie()]}var cX=k(f(),1);var lX=k(p0(),1);var ID=1e6;function ye(Z,J={}){if(Z.getOptions().debug)bL();let[X,$]=sd0(Z,J);Z.traceProvider=X,Z.asyncLocalStorageLookup=$}function sd0(Z,J={}){let X=new hK({sampler:new TL(Z),resource:xY().merge(IK({[lX.ATTR_SERVICE_NAME]:"node",[lX.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[lX.ATTR_SERVICE_VERSION]:N0})),forceFlushTimeoutMillis:500,spanProcessors:[new AL({timeout:td0(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});cX.trace.setGlobalTracerProvider(X),cX.propagation.setGlobalPropagator(new ML);let $=new cK;return cX.context.setGlobalContextManager($),[X,$.getAsyncLocalStorageLookup()]}function td0(Z){if(Z==null)return;if(Z>ID)return N1&&A.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${ID}`),ID;else if(Z<=0||Number.isNaN(Z)){N1&&A.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function Se(){return oK().filter((J)=>J.name!=="Http"&&J.name!=="NodeFetch").concat(oY(),rY())}function ke(Z){return[...Se(),...L1(Z)?P3():[]]}function yD(Z={}){return ed0(Z,ke)}function ed0(Z={},J){n5(Z,"node");let X=nL({...Z,defaultIntegrations:Z.defaultIntegrations??J(Z)});if(X&&!Z.skipOpenTelemetrySetup)ye(X,{spanProcessors:Z.openTelemetrySpanProcessors}),aK();return X}import*as be from"os";var Zu0="BunServer",Ju0=()=>{return{name:Zu0,setupOnce(){Xu0()}}},he=S(Ju0),xe=!1;function Xu0(){if(xe)return;Bun.serve=new Proxy(Bun.serve,{apply(Z,J,X){ve(X[0]);let $=Z.apply(J,X),Y=$.reload.bind($);return $.reload=(Q)=>{return ve(Q),Y(Q)},$}}),xe=!0}function ve(Z){$u0(Z),Yu0(Z)}function $u0(Z){if(typeof Z.fetch!=="function")return;Z.fetch=new Proxy(Z.fetch,{apply(J,X,$){return SD(J,X,$)}})}function Yu0(Z){if(!Z.routes)return;if(typeof Z.routes!=="object")return;Object.keys(Z.routes).forEach((J)=>{let X=Z.routes[J];if(typeof X==="function")Z.routes[J]=new Proxy(X,{apply:($,Y,Q)=>{return SD($,Y,Q,J)}});if(X instanceof Response)return;if(typeof X==="object")Object.entries(X).forEach(([$,Y])=>{if(typeof Y==="function")Z.routes[J][$]=new Proxy(Y,{apply:(Q,W,K)=>{return SD(Q,W,K,J)}})})})}function SD(Z,J,X,$){return GZ((Y)=>{let Q=X[0],W=Q.method.toUpperCase();if(W==="OPTIONS"||W==="HEAD")return Z.apply(J,X);let K=LY(Q.url),z=Qu0(K,Q),G=K?.pathname||"/";if(Q.params){if(Object.keys(Q.params).forEach((H)=>{z[`url.path.parameter.${H}`]=Q.params[H]}),$)z[U1]="route",z["url.template"]=$,G=$}if($?.endsWith("/*"))z[U1]="route",z["url.template"]=$,G=$;return Object.assign(z,oJ(Q.headers.toJSON(),u()?.getOptions().sendDefaultPii??!1)),Y.setSDKProcessingMetadata({normalizedRequest:{url:Q.url,method:Q.method,headers:Q.headers.toJSON(),query_string:K?.search}}),pW({sentryTrace:Q.headers.get("sentry-trace")??"",baggage:Q.headers.get("baggage")},()=>_6({attributes:z,op:"http.server",name:`${Q.method} ${G}`},async(H)=>{try{let V=await Z.apply(J,X);if(V?.status)xW(H,V.status),Y.setContext("response",{headers:V.headers.toJSON(),status_code:V.status});return V}catch(V){throw V0(V,{mechanism:{type:"auto.http.bun.serve",handled:!1}}),V}}))})}function Qu0(Z,J){let X={[X0]:"auto.http.bun.serve",[fB]:J.method||"GET",[U1]:"url"};if(Z){if(Z.search)X["url.query"]=Z.search;if(Z.hash)X["url.fragment"]=Z.hash;if(Z.pathname)X["url.path"]=Z.pathname;if(!HU(Z)){if(X["url.full"]=Z.href,Z.port)X["url.port"]=Z.port;if(Z.protocol)X["url.scheme"]=Z.protocol;if(Z.hostname)X["url.domain"]=Z.hostname}}return X}function fe(Z){function J(X){let $={body:X.body,method:"POST",headers:Z.headers};try{return i9(()=>{return fetch(Z.url,$).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 wZ(Z,J)}function ge(Z){return[rJ(),aJ(),sJ(),tJ(),eJ(),oY(),rY(),TX(),qX(),MX(),jX(),AX(),he(),...L1(Z)?P3():[]]}function kD(Z={}){n5(Z,"bun");let J={...Z,platform:"javascript",runtime:{name:"bun",version:Bun.version},serverName:Z.serverName||global.process.env.SENTRY_NAME||be.hostname()};if(J.transport=J.transport||fe,J.defaultIntegrations===void 0)J.defaultIntegrations=ge(J);return yD(J)}kD({dsn:"https://f0ba950f2a01c32d24ccd8711de778be@o4510345514123264.ingest.us.sentry.io/4510346875043848",tracesSampleRate:1,sendDefaultPii:!1});import{readFileSync as me}from"fs";import{join as de}from"path";function Q6(){return"2.1.1-beta.2"}function xD(Z){let[J,X]=Z.split("-"),$=(J||"0.0.0").split(".").map(Number),Y=null,Q=0;if(X){let W=X.match(/^([a-z]+)\.?(\d+)?$/i);if(W)Y=W[1]||null,Q=parseInt(W[2]||"0",10);else Y=X}return{major:$[0]||0,minor:$[1]||0,patch:$[2]||0,preRelease:Y,preReleaseNum:Q}}function H9(Z){let J=xD(Z);if(!J.preRelease)return"stable";if(J.preRelease.startsWith("alpha"))return"alpha";return"beta"}function E3(Z,J){try{let X=xD(Z),$=xD(J);if(X.major>$.major)return!1;if(X.major<$.major)return!1;if($.preRelease&&!X.preRelease)return!1;if(!$.preRelease&&X.preRelease)return!1;if($.preRelease&&X.preRelease){if(X.minor<$.minor)return!1;if(X.minor>$.minor)return!0;if(X.patch>$.patch)return!0;if(X.patch<$.patch)return!1;return X.preReleaseNum>$.preReleaseNum}if(X.minor>$.minor)return!0;if(X.minor<$.minor)return!1;if(X.patch>$.patch)return!0;return!1}catch(X){return!1}}import{parseArgs as Ku0}from"util";var zu0={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 ue(){let Z=Ku0({options:zu0,allowPositionals:!1,strict:!0});if(Z.values.version)console.log(`ccc v${Q6()}`),process.exit(0);if(Z.values.help)Gu0(),process.exit(0);let J=process.env.CCC_USERNAME||Z.values.username,X=process.env.CCC_PASSWORD||Z.values.password,$=process.env.CCC_NGROK_TOKEN||Z.values["ngrok-token"],Y=process.env.CCC_NGROK_DOMAIN||Z.values["ngrok-domain"];if(!J||!X)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:X,ngrokToken:$,ngrokDomain:Y,autoUpdate:!Z.values["no-auto-update"],autoUpdateCheckInterval:parseInt(Z.values["auto-update-check-interval"],10),terminalAudit:Z.values["terminal-audit"]}}function Gu0(){console.log(`
|
|
54
54
|
Backend v2 - Clean modular architecture
|
|
55
55
|
|
|
56
56
|
Usage:
|
|
@@ -2341,7 +2341,7 @@ Please ensure librust_pty.so is available or use the install script.`)}}return j
|
|
|
2341
2341
|
`);$=W.pop()||"";for(let K of W)if(K.trim())try{let z=JSON.parse(K);this.handleClaudeMessage(J,z)}catch(z){r.error("[ClaudeProcessManager] Failed to parse JSON from Claude:",{tempId:J.tempId,sessionId:J.sessionId,line:K,error:z instanceof Error?z.message:"Unknown error"})}}if($.trim())try{let Y=JSON.parse($);this.handleClaudeMessage(J,Y)}catch(Y){r.error("[ClaudeProcessManager] Failed to parse final JSON from Claude:",{tempId:J.tempId,sessionId:J.sessionId,buffer:$})}}catch(X){r.error("[ClaudeProcessManager] Error reading stdout:",{tempId:J.tempId,sessionId:J.sessionId,error:X instanceof Error?X.message:"Unknown error"})}})()}readStderrLines(Z,J){(async()=>{try{let X=Z.pipeThrough(new TextDecoderStream).getReader(),$="";while(!0){let{done:Y,value:Q}=await X.read();if(Y)break;$+=Q;let W=$.split(`
|
|
2342
2342
|
`);$=W.pop()||"";for(let K of W)if(K.trim())r.warn("[ClaudeProcessManager] Claude stderr:",{tempId:J.tempId,sessionId:J.sessionId,line:K})}if($.trim())r.warn("[ClaudeProcessManager] Claude stderr (final):",{tempId:J.tempId,sessionId:J.sessionId,line:$})}catch(X){r.error("[ClaudeProcessManager] Error reading stderr:",{tempId:J.tempId,sessionId:J.sessionId,error:X instanceof Error?X.message:"Unknown error"})}})()}handleClaudeMessage(Z,J){if(Z.stopped)return;switch(Z.lastActivity=new Date,J.type){case"system":if(J.subtype==="init")this.handleInitMessage(Z,J);break;case"user":this.handleUserMessage(Z,J);break;case"assistant":this.handleAssistantMessage(Z,J);break;case"result":this.handleResultMessage(Z,J);break;case"summary":this.handleSummaryMessage(Z,J);break;case"control_request":this.handlePermissionRequest(Z,J);break;case"error":this.handleSessionError(Z,J.content||"Unknown error");break;default:}}handleInitMessage(Z,J){if(!J.session_id){r.error("[ClaudeProcessManager] Init message missing session_id",{tempId:Z.tempId}),this.handleSessionError(Z,"Init message missing session_id");return}Z.sessionId=J.session_id,Z.model=J.model,Z.status="idle",r.debug("[ClaudeProcessManager] Session initialized",{tempId:Z.tempId,sessionId:Z.sessionId,model:Z.model}),this.tempSessions.delete(Z.tempId),this.sessions.set(Z.sessionId,Z),this.callbacks.onSessionInitialized?.(Z,J)}handleUserMessage(Z,J){let X=J.message;if(!Z.firstUserMessage&&X?.content&&Array.isArray(X.content)){let $=X.content.find((Y)=>Y.type==="text");if($?.text&&$.text.trim())Z.firstUserMessage=$.text.trim()}if(X?.content&&Array.isArray(X.content)){if(X.content.some((Y)=>Y.type==="tool_result"))r.debug("[ClaudeProcessManager] Forwarding tool results from Claude:",{sessionId:Z.sessionId,resultCount:X.content.filter((Y)=>Y.type==="tool_result").length}),this.callbacks.onAssistantMessage?.(Z,J)}}handleAssistantMessage(Z,J){Z.messageCount++;let{message:X,parent_tool_use_id:$}=J,Y=!!$;if(Y)r.debug("[ClaudeProcessManager] Subagent message:",{sessionId:Z.sessionId,parentToolUseId:$});let Q=X?.usage;if(Q&&!Y){let K=this.calculateContextBreakdown(Q,Z.model);Z.contextUsage=K,this.callbacks.onContextUpdate?.(Z,K)}let W="";if(X?.content&&Array.isArray(X.content))W=X.content.filter((z)=>z.type==="text").map((z)=>z.text).filter(Boolean).join(`
|
|
2343
2343
|
`);if(!X?.content||!Array.isArray(X.content)||X.content.length===0)return;J.content=W,this.callbacks.onAssistantMessage?.(Z,J)}calculateContextBreakdown(Z,J){let X=Z.input_tokens||0,$=Z.output_tokens||0,Y=Z.cache_creation_input_tokens||0,Q=Z.cache_read_input_tokens||0,W=X+Y+Q,K=i8.SYSTEM_PROMPT,z=i8.TOOLS_TOTAL,G=0,H=this.getAutoCompactEnabled()?i8.AUTOCOMPACT_BUFFER:0,V=Math.max(0,W-K-z-0),F=W+H,B=this.getContextLimit(J);return{total:F,inputTokens:X,outputTokens:$,cacheCreation:Y,cacheRead:Q,systemPrompt:K,tools:z,mcpServers:0,messages:V,autocompactBuffer:H,contextLimit:B,remaining:Math.max(0,B-F),percentage:Math.round(F/B*100),lastUpdated:Date.now()}}getContextLimit(Z){if(Z?.includes("sonnet-4")||Z?.includes("claude-sonnet-4"))return i8.CONTEXT_LIMIT_STANDARD;return i8.CONTEXT_LIMIT_STANDARD}getEmptyContextBreakdown(){let Z=this.getAutoCompactEnabled()?i8.AUTOCOMPACT_BUFFER:0;return{total:0,inputTokens:0,outputTokens:0,cacheCreation:0,cacheRead:0,systemPrompt:i8.SYSTEM_PROMPT,tools:i8.TOOLS_TOTAL,mcpServers:0,messages:0,autocompactBuffer:Z,contextLimit:i8.CONTEXT_LIMIT_STANDARD,remaining:i8.CONTEXT_LIMIT_STANDARD,percentage:0,lastUpdated:Date.now()}}handleSummaryMessage(Z,J){let X=J.summary;if(X&&typeof X==="string"){let $=X.substring(0,100);Z.title=$,r.debug("[ClaudeProcessManager] Title from summary:",{sessionId:Z.sessionId,title:$}),this.callbacks.onTitleGenerated?.(Z,$)}}handleResultMessage(Z,J){if(r.debug("[ClaudeProcessManager] Result message received:",{sessionId:Z.sessionId,subtype:J.subtype,isError:J.is_error}),J.subtype==="success"&&!J.is_error){if(Z.status="idle",Z.lastActivity=new Date,!Z.title&&Z.firstUserMessage){let X=Z.firstUserMessage.substring(0,50)+(Z.firstUserMessage.length>50?"...":"");Z.title=X,r.debug("[ClaudeProcessManager] Fallback title from first message:",{sessionId:Z.sessionId,title:X}),this.callbacks.onTitleGenerated?.(Z,X)}this.callbacks.onProcessingComplete?.(Z)}else if(J.is_error){let X=J.result||"Unknown error";this.handleSessionError(Z,X)}}handlePermissionRequest(Z,J){Z.status="waiting_permission",r.debug("[ClaudeProcessManager] Permission request:",{sessionId:Z.sessionId,fullRequest:JSON.stringify(J),requestId:J.request_id,action:J.action}),this.callbacks.onPermissionRequest?.(Z,J)}handleSessionError(Z,J){Z.status="error",r.error("[ClaudeProcessManager] Session error:",{tempId:Z.tempId,sessionId:Z.sessionId,error:J}),this.callbacks.onSessionError?.(Z,J);let X=Z.sessionId??Z.tempId;this.stopSession(X)}handleSessionStopped(Z,J){if(Z.respawning){r.debug("[ClaudeProcessManager] Skipping session_stopped - session is respawning:",{tempId:Z.tempId,sessionId:Z.sessionId});return}if(Z.status="stopped",r.debug("[ClaudeProcessManager] Session stopped:",{tempId:Z.tempId,sessionId:Z.sessionId,reason:J}),this.callbacks.onSessionStopped?.(Z,J),Z.sessionId)this.sessions.delete(Z.sessionId);this.tempSessions.delete(Z.tempId)}sendUserMessage(Z,J,X){if(!Z.process)throw r.error("[ClaudeProcessManager] Cannot send message - process not found:",{tempId:Z.tempId,sessionId:Z.sessionId,status:Z.status}),Error("Session process not found or has been terminated");let $=[];if(J&&J.trim())$.push({type:"text",text:J});if(X&&X.length>0)for(let K of X)$.push({type:"image",source:{type:"base64",media_type:K.mimeType,data:K.data}});let Q=JSON.stringify({type:"user",message:{role:"user",content:$}})+`
|
|
2344
|
-
`;Z.process.stdin.write(Q),Z.lastActivity=new Date,Z.messageCount++,Z.status="processing",this.callbacks.onProcessingStarted?.(Z)}sendPermissionResponse(Z,J){let X=this.sessions.get(Z);if(!X){r.warn(`[ClaudeProcessManager] Session not found for permission response: ${Z}`);return}let $;if(J.behavior==="allow")$={behavior:"allow",updatedInput:J.updatedInput||{}};else if($={behavior:"deny",message:J.message||"Permission denied by user"},J.hardDeny===!0)$.continue=!1;let Y={type:"control_response",response:{subtype:"success",request_id:J.request_id,response:$}},Q=JSON.stringify(Y)+`
|
|
2344
|
+
`;if(Z.process.stdin.write(Q),Z.lastActivity=new Date,Z.messageCount++,Z.status!=="processing")Z.status="processing",this.callbacks.onProcessingStarted?.(Z)}sendPermissionResponse(Z,J){let X=this.sessions.get(Z);if(!X){r.warn(`[ClaudeProcessManager] Session not found for permission response: ${Z}`);return}let $;if(J.behavior==="allow")$={behavior:"allow",updatedInput:J.updatedInput||{}};else if($={behavior:"deny",message:J.message||"Permission denied by user"},J.hardDeny===!0)$.continue=!1;let Y={type:"control_response",response:{subtype:"success",request_id:J.request_id,response:$}},Q=JSON.stringify(Y)+`
|
|
2345
2345
|
`;X.process.stdin.write(Q),r.debug("[ClaudeProcessManager] Sent permission response:",{sessionId:Z,request_id:J.request_id,behavior:J.behavior,hardDeny:J.hardDeny,hasMessage:!!J.message,fullResponse:Q.trim()}),X.lastActivity=new Date,X.status="idle"}async respawnWithPermissionMode(Z,J,X="proceed with implementation"){let $=this.sessions.get(Z);if(!$)return r.warn(`[ClaudeProcessManager] Cannot respawn - session not found: ${Z}`),null;let{tempId:Y,userId:Q,projectId:W,directoryPath:K,model:z}=$;r.debug("[ClaudeProcessManager] Respawning session with new permission mode:",{sessionId:Z,newPermissionMode:J,continuationMessage:X}),$.respawning=!0;let G=$.process;if(G&&!G.killed)G.kill();this.sessions.delete(Z);try{let H=await this.spawnSession(Y,Q,W,K,X,Z,J,z);return r.debug("[ClaudeProcessManager] Session respawned successfully:",{sessionId:Z,newPermissionMode:J,newTempId:H.tempId}),H}catch(H){return r.error("[ClaudeProcessManager] Failed to respawn session:",{sessionId:Z,newPermissionMode:J,error:H instanceof Error?H.message:"Unknown error"}),null}}stopSession(Z){let J=this.sessions.get(Z)||this.tempSessions.get(Z);if(!J){r.warn(`[ClaudeProcessManager] Session not found: ${Z}`);return}r.debug("[ClaudeProcessManager] Stopping session:",{tempId:J.tempId,sessionId:J.sessionId}),J.stopped=!0;let X=J.process;if(X&&!X.killed){try{X.stdin?.end?.()}catch{}X.kill("SIGKILL")}this.sessions.delete(J.sessionId),this.tempSessions.delete(J.tempId)}stopAll(){r.debug(`[ClaudeProcessManager] Stopping all sessions (${this.sessions.size+this.tempSessions.size} total)`);for(let[Z]of this.sessions)this.stopSession(Z);for(let[Z]of this.tempSessions)this.stopSession(Z)}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}async executeFileRewind(Z,J,X){let $=this.config.claudeCodePath||await this.resolveClaudePath(),Y=["--resume",Z,"--rewind-files",J];r.debug("[ClaudeProcessManager] Executing file rewind:",{sessionId:Z,checkpointUuid:J,cwd:X});try{let Q=Bun.spawn([$,...Y],{cwd:X,stdout:"pipe",stderr:"pipe",env:{...process.env,HOME:process.env.HOME||process.env.USERPROFILE,USER:process.env.USER||process.env.USERNAME,TERM:process.env.TERM||"xterm-256color",LANG:process.env.LANG||"en_US.UTF-8",CI:"1",CLAUDE_HEADLESS:"1",CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING:"1"}}),W=await Q.exited,K=await new Response(Q.stderr).text();if(W===0)return r.info("[ClaudeProcessManager] File rewind successful:",{sessionId:Z,checkpointUuid:J}),{success:!0};else return r.error("[ClaudeProcessManager] File rewind failed:",{sessionId:Z,checkpointUuid:J,exitCode:W,stderr:K}),{success:!1,error:K||`Exit code: ${W}`}}catch(Q){return r.error("[ClaudeProcessManager] File rewind error:",{sessionId:Z,checkpointUuid:J,error:Q}),{success:!1,error:Q instanceof Error?Q.message:"Unknown error"}}}async executeConversationFork(Z,J,X){return this.forkAndTruncateSession(Z,J,X)}async forkAndTruncateSession(Z,J,X){let $=await this.executeConversationForkWithPrompt(Z,J,"ok");if(!$.success||!$.newSessionId)return $;let Y=$.newSessionId;if(!X)return $;let Q=await this.findParentUuidOfCheckpoint(Y,X,J);if(!Q)return r.warn("[ClaudeProcessManager] Could not find parent UUID for checkpoint, returning full fork"),$;let W=await this.truncateSessionFile(Y,Q,J);if(!W.success)return r.error("[ClaudeProcessManager] Failed to truncate session file:",W.error),$;return r.info("[ClaudeProcessManager] Fork with truncation successful:",{originalSessionId:Z,newSessionId:Y,truncatedToUuid:Q}),{success:!0,newSessionId:Y}}async findParentUuidOfCheckpoint(Z,J,X){try{let $=await this.getSessionFilePath(Z,X),Y=Bun.file($);if(!await Y.exists())return r.warn("[ClaudeProcessManager] Session file not found:",$),null;let W=(await Y.text()).trim().split(`
|
|
2346
2346
|
`);for(let K of W){if(!K.trim())continue;try{let z=JSON.parse(K);if(z.uuid===J&&z.parentUuid)return r.debug("[ClaudeProcessManager] Found parent UUID for checkpoint:",{checkpointUuid:J,parentUuid:z.parentUuid}),z.parentUuid}catch{}}return r.warn("[ClaudeProcessManager] No parent UUID found for checkpoint:",J),null}catch($){return r.error("[ClaudeProcessManager] Error finding parent UUID:",$),null}}async getSessionFilePath(Z,J){return`${process.env.CLAUDE_CONFIG_DIR||`${z30.homedir()}/.claude`}/projects/${x5(J)}/${Z}.jsonl`}async truncateSessionFile(Z,J,X){try{let $=await this.getSessionFilePath(Z,X),Y=Bun.file($);if(!await Y.exists())return{success:!1,error:"Session file not found"};let W=(await Y.text()).trim().split(`
|
|
2347
2347
|
`),K=new Set,z=[],G=!1;for(let V of W){if(!V.trim())continue;try{let F=JSON.parse(V);if(F.type==="summary"||F.type==="file-history-snapshot"){z.push(V);continue}if(G)continue;if(z.push(V),F.uuid)K.add(F.uuid);if(F.uuid===J)G=!0,r.debug("[ClaudeProcessManager] Found truncate point:",{uuid:J,linesKept:z.length})}catch{z.push(V)}}if(!G)return r.warn("[ClaudeProcessManager] Truncate UUID not found in session:",J),{success:!1,error:"Truncate UUID not found"};let H=z.join(`
|
|
@@ -2367,7 +2367,7 @@ Please ensure librust_pty.so is available or use the install script.`)}}return j
|
|
|
2367
2367
|
`+`\u2022 Set up a ~/.netrc file with your GitHub credentials
|
|
2368
2368
|
`+"\u2022 Use Git credential manager";return`${J} failed: ${Z}`}async function k30(Z){try{let J=await DJ(Z);if(!J)return{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:"Not on a branch"};let X,$=!1;try{X=(await g`git -C ${Z} rev-parse --abbrev-ref @{upstream}`.text()).trim()}catch{if(L0.info("[GitExecutor] No upstream set, checking if remote branch exists",{path:Z,branch:J}),(await g`git -C ${Z} ls-remote --heads origin ${J}`.quiet()).stdout.toString().trim().length>0)try{await g`git -C ${Z} branch --set-upstream-to=origin/${J} ${J}`.quiet(),X=`origin/${J}`}catch{return{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:`Failed to set up tracking for origin/${J}`}}else L0.info("[GitExecutor] Remote branch does not exist, will push to create it",{path:Z,branch:J}),$=!0,X=`origin/${J}`}if($){L0.info("[GitExecutor] Pushing to create remote branch",{path:Z,branch:J});let z=await g`git -C ${Z} push -u origin ${J}`.quiet();if(z.exitCode!==0){let H=z.stderr.toString();return{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:$j(H,"Push")}}let G=0;try{let H=await g`git -C ${Z} rev-list --count HEAD`.text();G=parseInt(H.trim(),10)||0}catch{G=1}return{success:!0,action:"synced",commitsPulled:0,commitsPushed:G}}let{ahead:Y}=await j$(Z),Q=await g`git -C ${Z} fetch origin`.quiet();if(Q.exitCode!==0){let z=Q.stderr.toString();return{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:$j(z,"Fetch")}}let W=0;try{let z=await g`git -C ${Z} rev-list --count HEAD..@{upstream}`.text();W=parseInt(z.trim(),10)||0}catch{}if(W===0&&Y===0)return{success:!0,action:"up-to-date",commitsPulled:0,commitsPushed:0};if(W>0){if((await g`git -C ${Z} rebase @{upstream}`.quiet()).exitCode!==0){let H=(await g`git -C ${Z} diff --name-only --diff-filter=U`.text()).trim().split(`
|
|
2369
2369
|
`).filter((V)=>V.trim());return await g`git -C ${Z} rebase --abort`.quiet(),{success:!1,action:"conflict",commitsPulled:0,commitsPushed:0,conflictedFiles:H,error:`Rebase failed due to conflicts in ${H.length} file(s). Please resolve conflicts on desktop.`}}}let{ahead:K}=await j$(Z);if(K>0){let z=await g`git -C ${Z} push origin ${J}`.quiet();if(z.exitCode!==0){let G=z.stderr.toString();if(G.includes("rejected")||G.includes("non-fast-forward"))return{success:!1,action:"diverged",commitsPulled:W,commitsPushed:0,error:"Push rejected. Remote has new changes. Please sync again."};let H=$j(G,"Push");return{success:!1,action:"error",commitsPulled:W,commitsPushed:0,error:H}}}return{success:!0,action:"synced",commitsPulled:W,commitsPushed:K}}catch(J){return L0.error("[GitExecutor] Sync failed",{error:J,path:Z}),{success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:J instanceof Error?J.message:"Sync failed"}}}async function x30(Z,J,X){try{let $,Y=!1;try{$=await g`git -C ${Z} diff ${J}^..${J} -- ${X}`.text()}catch{$=await g`git -C ${Z} diff ${"4b825dc642cb6eb9a060e54bf8d69288fbee4904"}..${J} -- ${X}`.text()}if($.includes("Binary files")||$.includes("GIT binary patch"))Y=!0;return{diff:$,isBinary:Y}}catch($){throw L0.error("[GitExecutor] Failed to get commit file diff",{error:$,path:Z,commitHash:J,filePath:X}),Error(`Failed to get file diff: ${$ instanceof Error?$.message:"Unknown error"}`)}}async function v30(Z,J,X,$,Y=!1){try{let Q=await DJ(Z);if(!Q)return{success:!1,error:"Not on a branch"};let{ahead:W}=await j$(Z);if(W>0){let F=await g`git -C ${Z} push -u origin ${Q}`.quiet();if(F.exitCode!==0)return{success:!1,error:`Failed to push branch: ${F.stderr.toString()}`}}let K;if(X&&X.trim().length>0)if(Y&&$)K=await g`gh pr create --title ${J} --body ${X} --base ${$} --draft`.cwd(Z).text();else if(Y)K=await g`gh pr create --title ${J} --body ${X} --draft`.cwd(Z).text();else if($)K=await g`gh pr create --title ${J} --body ${X} --base ${$}`.cwd(Z).text();else K=await g`gh pr create --title ${J} --body ${X}`.cwd(Z).text();else if(Y&&$)K=await g`gh pr create --title ${J} --fill --base ${$} --draft`.cwd(Z).text();else if(Y)K=await g`gh pr create --title ${J} --fill --draft`.cwd(Z).text();else if($)K=await g`gh pr create --title ${J} --fill --base ${$}`.cwd(Z).text();else K=await g`gh pr create --title ${J} --fill`.cwd(Z).text();let G=K.trim(),H=G.match(/\/pull\/(\d+)$/);return{success:!0,prNumber:H&&H[1]?parseInt(H[1],10):void 0,prUrl:G}}catch(Q){L0.error("[GitExecutor] Failed to create pull request",{error:Q,path:Z});let W=Q instanceof Error?Q.message:"Unknown error";if(W.includes("already exists")||W.includes("A pull request for branch"))return{success:!1,error:"A pull request for this branch already exists"};return{success:!1,error:`Failed to create pull request: ${W}`}}}async function h30(Z){try{if(!await DJ(Z))return{exists:!1,error:"Not on a branch"};let X=await g`gh pr view --json number,url,title,state,isDraft`.cwd(Z).quiet();if(X.exitCode!==0){let Y=X.stderr.toString();if(Y.includes("no pull requests found")||Y.includes("Could not resolve"))return{exists:!1};return{exists:!1,error:Y}}let $=JSON.parse(X.stdout.toString());return{exists:!0,prNumber:$.number,prUrl:$.url,title:$.title,state:$.state.toLowerCase(),draft:$.isDraft}}catch(J){L0.error("[GitExecutor] Failed to check for existing PR",{error:J,path:Z});let X=J instanceof Error?J.message:String(J);if(X.includes("no pull requests found")||X.includes("Could not resolve"))return{exists:!1};return{exists:!1,error:`Failed to check for existing PR: ${X}`}}}async function zj(Z){try{let X=(await g`gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name'`.cwd(Z).text()).trim();if(X)return X;let $=await g`git -C ${Z} branch -r`.text();if($.includes("origin/main"))return"main";if($.includes("origin/master"))return"master";return null}catch(J){return L0.error("[GitExecutor] Failed to get default branch",{error:J,path:Z}),null}}async function f30(Z){try{await g`git -C ${Z} fetch --prune`.quiet();let X=(await g`git -C ${Z} branch -r`.text()).split(`
|
|
2370
|
-
`).map((Y)=>Y.trim()).filter((Y)=>Y&&!Y.includes("HEAD")&&!Y.includes("->")).map((Y)=>Y.replace(/^origin\//,"")),$=await zj(Z);return{branches:X,defaultBranch:$}}catch(J){return L0.error("[GitExecutor] Failed to get remote branches",{error:J,path:Z}),{branches:[],defaultBranch:null}}}import*as R4 from"path";import*as T1 from"fs";import*as Hj from"os";var r0=x();function A$(Z){return R4.normalize(Z).toLowerCase()}var GZ1="worktrees",HZ1="sessions";function Gj(){return R4.join(Hj.homedir(),".ccc",HZ1)}function VZ1(){let Z=new Date,J=Z.getFullYear(),X=String(Z.getMonth()+1).padStart(2,"0"),$=String(Z.getDate()).padStart(2,"0"),Y=String(Z.getHours()).padStart(2,"0"),Q=String(Z.getMinutes()).padStart(2,"0");return`${J}${X}${$}-${Y}${Q}`}class T${worktreeCache=new Map;saveSessionMapping(Z,J){try{let X=Gj();if(!T1.existsSync(X))T1.mkdirSync(X,{recursive:!0});let $=R4.join(X,Z);T1.writeFileSync($,J,"utf-8"),r0.debug("[WorktreeManager] Saved session mapping",{sessionId:Z,worktreePath:J})}catch(X){r0.error("[WorktreeManager] Failed to save session mapping",{error:X,sessionId:Z,worktreePath:J})}}loadSessionMapping(Z){try{let J=R4.join(Gj(),Z);if(T1.existsSync(J)){let X=T1.readFileSync(J,"utf-8").trim();if(T1.existsSync(X))return X;else T1.unlinkSync(J),r0.debug("[WorktreeManager] Removed stale session mapping",{sessionId:Z,worktreePath:X})}}catch(J){r0.error("[WorktreeManager] Failed to load session mapping",{error:J,sessionId:Z})}return null}deleteSessionMapping(Z){try{let J=R4.join(Gj(),Z);if(T1.existsSync(J))T1.unlinkSync(J),r0.debug("[WorktreeManager] Deleted session mapping",{sessionId:Z})}catch(J){r0.error("[WorktreeManager] Failed to delete session mapping",{error:J,sessionId:Z})}}getWorktreesBasePath(Z){let J=R4.basename(Z),X=R4.join(Hj.homedir(),".ccc");return R4.join(X,`${J}-${GZ1}`)}getWorktreePath(Z,J){let X=this.getWorktreesBasePath(Z),$=J.replace(/[^a-zA-Z0-9_-]/g,"_");return R4.join(X,$)}generateBranchName(Z){return`session/${Z.replace(/[^a-zA-Z0-9_-]/g,"_")}`}async getOrCreateForSession(Z,J){r0.debug("[WorktreeManager] getOrCreateForSession",{sessionId:Z,repoPath:J});let X=this.worktreeCache.get(Z);if(X)if(T1.existsSync(X.path))return r0.debug("[WorktreeManager] Returning cached worktree",{sessionId:Z,path:X.path}),{worktree:X,isNew:!1};else this.worktreeCache.delete(Z);let $=this.loadSessionMapping(Z);if($&&T1.existsSync($)){let U=await h5(J);if(U){let D=await fQ(U),_=A$($),O=D.find((w)=>A$(w.path)===_);if(O)return O.sessionId=Z,this.worktreeCache.set(Z,O),r0.debug("[WorktreeManager] Found worktree from session mapping",{sessionId:Z,path:$}),{worktree:O,isNew:!1};else r0.warn("[WorktreeManager] Worktree path exists on disk but not found in git worktree list",{mappedWorktreePath:$})}}if(!await M$(J))throw Error(`Not a git repository: ${J}`);let Q=await h5(J);if(!Q)throw Error(`Could not determine repository root for: ${J}`);let W=await gH(Q,Z);if(W)return W.sessionId=Z,this.worktreeCache.set(Z,W),this.saveSessionMapping(Z,W.path),r0.debug("[WorktreeManager] Found existing worktree (legacy)",{sessionId:Z,path:W.path}),{worktree:W,isNew:!1};let K=this.getWorktreePath(Q,Z);if(T1.existsSync(K)){r0.warn("[WorktreeManager] Worktree path exists but not in git worktree list",{expectedPath:K});let U=await fQ(Q),D=A$(K),_=U.find((O)=>A$(O.path)===D);if(_)return _.sessionId=Z,this.worktreeCache.set(Z,_),{worktree:_,isNew:!1}}let z=VZ1(),G=this.getWorktreesBasePath(Q),H=R4.join(G,z),V=`session/${z}`,F=0;while(T1.existsSync(H)){F++;let U=`${z}-${F}`;H=R4.join(G,U),V=`session/${U}`}if(!T1.existsSync(G))T1.mkdirSync(G,{recursive:!0}),r0.debug("[WorktreeManager] Created worktrees base directory",{basePath:G});let B=await w30(Q,H,V);return B.sessionId=Z,this.saveSessionMapping(Z,H),this.worktreeCache.set(Z,B),r0.debug("[WorktreeManager] Created new worktree",{sessionId:Z,worktreeName:R4.basename(H),path:B.path,branch:B.branch}),{worktree:B,isNew:!0}}async getWorktreeForSession(Z,J){r0.debug("[WorktreeManager] getWorktreeForSession",{sessionId:Z,repoPath:J});let X=this.worktreeCache.get(Z);if(X)if(T1.existsSync(X.path))return X;else this.worktreeCache.delete(Z);let $=await h5(J);if(!$)return null;let Y=await gH($,Z);if(Y)Y.sessionId=Z,this.worktreeCache.set(Z,Y);return Y}async listWorktreesForRepo(Z){r0.debug("[WorktreeManager] listWorktreesForRepo",{repoPath:Z});let J=await h5(Z);if(!J)throw Error(`Could not determine repository root for: ${Z}`);let X=await fQ(J);for(let $ of X)if(!$.isMain)if($.branch?.startsWith("session/"))$.sessionId=$.branch.substring(8);else{let Y=this.getWorktreesBasePath(J);if(A$($.path).startsWith(A$(Y))){let Q=R4.basename($.path);$.sessionId=Q}}for(let $ of X)if($.sessionId)this.worktreeCache.set($.sessionId,$);return X}getActiveWorktreeCount(){return this.worktreeCache.size}clearCache(){this.worktreeCache.clear()}removeFromCache(Z){this.worktreeCache.delete(Z)}updateSessionId(Z,J,X){try{this.deleteSessionMapping(J),this.saveSessionMapping(X,Z);let $=this.worktreeCache.get(J);if($)this.worktreeCache.delete(J),$.sessionId=X,this.worktreeCache.set(X,$);r0.debug("[WorktreeManager] Updated session ID mapping",{worktreePath:Z,oldSessionId:J,newSessionId:X})}catch($){r0.error("[WorktreeManager] Failed to update session ID",{error:$,worktreePath:Z,oldSessionId:J,newSessionId:X})}}async renameWorktreeForSession(Z,J,X){r0.debug("[WorktreeManager] Renaming worktree for session",{oldSessionId:Z,newSessionId:J,repoPath:X});try{let $=await h5(X);if(!$)return r0.error("[WorktreeManager] Could not determine repo root for rename"),null;let Y=this.worktreeCache.get(Z);if(!Y){if(r0.warn("[WorktreeManager] No cached worktree found for old session ID",{oldSessionId:Z}),!await gH($,Z))return r0.error("[WorktreeManager] Could not find worktree for old session ID"),null}let Q=this.getWorktreePath($,Z),W=this.getWorktreePath($,J),K=this.generateBranchName(Z),z=this.generateBranchName(J);if(!T1.existsSync(Q))return r0.warn("[WorktreeManager] Old worktree path does not exist",{oldPath:Q}),null;if(T1.existsSync(W)){r0.warn("[WorktreeManager] New worktree path already exists",{newPath:W});let H={path:W,branch:z,head:Y?.head||"",sessionId:J,isMain:!1};return this.worktreeCache.delete(Z),this.worktreeCache.set(J,H),H}await P30($,Q,W),r0.debug("[WorktreeManager] Moved worktree",{from:Q,to:W}),await R30(W,K,z),r0.debug("[WorktreeManager] Renamed branch",{from:K,to:z}),this.worktreeCache.delete(Z);let G={path:W,branch:z,head:Y?.head||"",sessionId:J,isMain:!1,createdAt:Y?.createdAt};return this.worktreeCache.set(J,G),r0.debug("[WorktreeManager] Successfully renamed worktree",{oldSessionId:Z,newSessionId:J,oldPath:Q,newPath:W,oldBranch:K,newBranch:z}),G}catch($){return r0.error("[WorktreeManager] Failed to rename worktree",{error:$,oldSessionId:Z,newSessionId:J}),null}}}import*as Vj from"path";import*as m30 from"os";var V8=x(),mH=Vj.join(m30.homedir(),".ccc"),g30=Vj.join(mH,"pending-permissions.json");class d30{cache=null;async ensureDirectory(){try{let Z=await import("fs");if(!Z.existsSync(mH))Z.mkdirSync(mH,{recursive:!0}),V8.debug("[PendingPermissions] Created .ccc directory:",mH)}catch(Z){throw V8.error("[PendingPermissions] Error ensuring directory:",Z),Z}}async load(){if(this.cache)return this.cache;try{let Z=Bun.file(g30);if(await Z.exists()){let J=await Z.text();return this.cache=JSON.parse(J),V8.debug("[PendingPermissions] Loaded permissions:",{count:this.cache?.permissions?.length||0}),this.cache}}catch(Z){V8.warn("[PendingPermissions] Error loading, starting fresh:",Z)}return this.cache={permissions:[],lastUpdated:new Date().toISOString()},this.cache}async save(Z){try{await this.ensureDirectory(),Z.lastUpdated=new Date().toISOString(),await Bun.write(g30,JSON.stringify(Z,null,2)),this.cache=Z,V8.debug("[PendingPermissions] Saved permissions:",{count:Z.permissions.length})}catch(J){throw V8.error("[PendingPermissions] Error saving:",J),J}}async addPermission(Z){let J=await this.load(),X=J.permissions.findIndex(($)=>$.requestId===Z.requestId);if(X>=0)J.permissions[X]=Z,V8.debug("[PendingPermissions] Updated existing permission:",{requestId:Z.requestId,sessionId:Z.sessionId});else J.permissions.push(Z),V8.debug("[PendingPermissions] Added new pending permission:",{requestId:Z.requestId,sessionId:Z.sessionId,action:Z.action});await this.save(J)}async removePermission(Z){let J=await this.load(),X=J.permissions.length;if(J.permissions=J.permissions.filter(($)=>$.requestId!==Z),J.permissions.length<X)return await this.save(J),V8.debug("[PendingPermissions] Removed permission:",{requestId:Z}),!0;return!1}async removePermissionsForSession(Z){let J=await this.load(),X=J.permissions.length;J.permissions=J.permissions.filter((Y)=>Y.sessionId!==Z);let $=X-J.permissions.length;if($>0)await this.save(J),V8.debug("[PendingPermissions] Removed permissions for session:",{sessionId:Z,removedCount:$});return $}async getPermissionsForSession(Z){return(await this.load()).permissions.filter((X)=>X.sessionId===Z)}async getPermissionsForProject(Z){return(await this.load()).permissions.filter((X)=>X.projectPath===Z)}async getAllPermissions(){return(await this.load()).permissions}async getPermission(Z){return(await this.load()).permissions.find((X)=>X.requestId===Z)}async clearAll(){this.cache={permissions:[],lastUpdated:new Date().toISOString()},await this.save(this.cache),V8.debug("[PendingPermissions] Cleared all pending permissions")}clearCache(){this.cache=null,V8.debug("[PendingPermissions] Cleared cache")}}var d7=new d30;var m=x();class uH{name="Claude Agent Service";running=!1;startedAt;mqttClient=null;sessionsService=null;processManager;worktreeManager;config;totalSessionsCreated=0;totalMessagesProcessed=0;pendingPermissions=new Map;cleanupInterval;constructor(Z){this.config=Z,this.worktreeManager=new T$,this.processManager=new hH(Z,{onSessionInitialized:this.handleSessionInitialized.bind(this),onTitleGenerated:this.handleTitleGenerated.bind(this),onAssistantMessage:this.handleAssistantMessage.bind(this),onPermissionRequest: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(!$)return m.debug("[ClaudeAgent] Git worktrees disabled, using project path",{projectId:Z,directoryPath:J}),{path:J,isWorktree:!1};if(!await M$(J))return m.debug("[ClaudeAgent] Not a git repo, using project path",{projectId:Z,directoryPath:J}),{path:J,isWorktree:!1};let Q=await h5(J);if(!Q)return m.warn("[ClaudeAgent] Could not determine repo root, using project path",{directoryPath:J}),{path:J,isWorktree:!1};m.debug("[ClaudeAgent] Git repo detected, creating worktree",{projectId:Z,sessionId:X,repoRoot:Q});let{worktree:W,isNew:K}=await this.worktreeManager.getOrCreateForSession(X,Q);return m.debug("[ClaudeAgent] Worktree ready",{sessionId:X,worktreePath:W.path,branch:W.branch,isNew:K}),{path:W.path,isWorktree:!0,branch:W.branch}}catch(Y){return m.error("[ClaudeAgent] Worktree creation failed, falling back to project path",{projectId:Z,sessionId:X,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,m.info("[ClaudeAgent] Service started"),this.mqttClient)this.registerMQTTHandlers();else m.warn("[ClaudeAgent] MQTT client not set - handlers will not be registered");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions()},300000),m.info("[ClaudeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions,sessionTimeoutMs:this.config.sessionTimeoutMs})}catch(Z){throw m.error("[ClaudeAgent] Failed to start",Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval);this.processManager.stopAll(),m.info("[ClaudeAgent] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("claude/+/session/start",(Z,J)=>{let X=this.extractUserIdFromTopic(Z);this.handleSessionStart(X,Z,J)}),this.mqttClient.subscribe("claude/+/input/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromInputTopic(Z);this.handleUserInput(X,$,Z,J)}),this.mqttClient.subscribe("claude/+/permission/response/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromPermissionTopic(Z);this.handlePermissionResponse(X,$,Z,J)}),this.mqttClient.subscribe("claude/+/session/stop/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromStopTopic(Z);this.handleSessionStop(X,$)}),this.mqttClient.subscribe("permissions/pending/request",(Z,J)=>{this.handlePendingPermissionsRequest(Z,J)}),this.mqttClient.subscribe("settings/claude/request",(Z,J)=>{this.handleClaudeSettingsRequest(Z,J)}),this.mqttClient.subscribe("settings/claude/update",(Z,J)=>{this.handleClaudeSettingsUpdate(Z,J)}),this.mqttClient.subscribe("claude/+/checkpoints/list/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromStopTopic(Z);this.handleCheckpointListRequest(X,$,J)}),this.mqttClient.subscribe("claude/+/session/rewind/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromStopTopic(Z);this.handleRewindRequest(X,$,J)}),m.info("[ClaudeAgent] MQTT handlers registered")}async handleSessionStart(Z,J,X){try{let $=JSON.parse(X.toString());m.info("[ClaudeAgent] Session start request:",{userId:Z,tempId:$.tempId,projectId:$.projectId,directoryPath:$.directoryPath,permissionMode:$.permissionMode,selectedModel:$.selectedModel,hasAttachments:!!$.attachments,attachmentCount:$.attachments?.length||0,gitWorktreesEnabled:$.gitWorktreesEnabled});let{path:Y,isWorktree:Q,branch:W}=await this.determineWorkingDirectory($.projectId,$.directoryPath,$.tempId,$.gitWorktreesEnabled??!1),K=await this.processManager.spawnSession($.tempId,Z,$.projectId,Y,$.initialMessage||"",void 0,$.permissionMode,$.selectedModel,$.attachments);if(Q)K.directoryPath=$.directoryPath,K.worktreePath=Y,K.worktreeBranch=W;this.totalSessionsCreated++,m.info("[ClaudeAgent] Session spawned successfully:",{userId:Z,tempId:$.tempId,projectId:$.projectId,workingPath:Y,isWorktree:Q})}catch($){m.error("[ClaudeAgent] Error starting session:",{userId:Z,error:$ instanceof Error?$.message:"Unknown error"}),this.publishStatus(Z,"temp_error",{type:"error",error:$ instanceof Error?$.message:"Failed to start session",timestamp:Date.now()})}}async handleUserInput(Z,J,X,$){try{let Y=JSON.parse($.toString());if(!Y.message&&(!Y.attachments||Y.attachments.length===0)){m.warn("[ClaudeAgent] Received request without message or attachments:",{userId:Z,sessionId:Y.sessionId,hasAttachments:!!Y.attachments});return}m.debug("[ClaudeAgent] User input:",{userId:Z,sessionId:Y.sessionId,messageLength:Y.message?.length||0,permissionMode:Y.permissionMode,selectedModel:Y.selectedModel,hasAttachments:!!Y.attachments,attachmentCount:Y.attachments?.length||0,allSessions:this.processManager.getAllSessions().map((z)=>({tempId:z.tempId,sessionId:z.sessionId,status:z.status}))});let Q=this.processManager.getSession(Y.sessionId);if(!Q){m.warn("[ClaudeAgent] Session not found, creating new session:",{userId:Z,requestedSessionId:Y.sessionId,projectId:Y.projectId,availableSessions:this.processManager.getAllSessions().map((G)=>G.sessionId||G.tempId)});let z=Y.sessionId&&!Y.sessionId.startsWith("temp_")&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(Y.sessionId);try{let{path:G,isWorktree:H,branch:V}=await this.determineWorkingDirectory(Y.projectId,Y.directoryPath,Y.sessionId,Y.gitWorktreesEnabled??!1);if(Q=await this.processManager.spawnSession(Y.sessionId,Z,Y.projectId,G,Y.message||"",z?Y.sessionId:void 0,Y.permissionMode,Y.selectedModel,Y.attachments),H)Q.directoryPath=Y.directoryPath,Q.worktreePath=G,Q.worktreeBranch=V;this.totalSessionsCreated++,m.info(`[ClaudeAgent] Session ${z?"resumed":"created"} successfully:`,{userId:Z,sessionId:Y.sessionId,isResume:z,workingPath:G,isWorktree:H}),this.totalMessagesProcessed++;return}catch(G){m.error("[ClaudeAgent] Failed to create session:",{userId:Z,sessionId:Y.sessionId,error:G instanceof Error?G.message:"Unknown error"}),this.publishStatus(Z,Y.sessionId,{type:"error",error:"Failed to create session",timestamp:Date.now()});return}}let W=Q.permissionMode||"default",K=Y.permissionMode||"default";if(K!==W&&Q.sessionId)if(m.info("[ClaudeAgent] Permission mode changed, respawning session:",{userId:Z,sessionId:Q.sessionId,currentMode:W,requestedMode:K}),await this.processManager.respawnWithPermissionMode(Q.sessionId,K,Y.message||"proceed with implementation")){this.publishStatus(Z,Q.sessionId,{type:"session_restarted",permissionMode:K,timestamp:Date.now()}),this.totalMessagesProcessed++;return}else m.error("[ClaudeAgent] Failed to respawn session with new permission mode");this.processManager.sendUserMessage(Q,Y.message||"",Y.attachments),this.totalMessagesProcessed++}catch(Y){m.error("[ClaudeAgent] Error handling user input:",{userId:Z,sessionId:J,error:Y instanceof Error?Y.message:"Unknown error"})}}async handlePermissionResponse(Z,J,X,$){try{let Y=JSON.parse($.toString());m.debug("[ClaudeAgent] Permission response:",{userId:Z,sessionId:J,requestId:Y.requestId,approved:Y.approved,hasAnswers:!!Y.answers,addToAllowedTools:Y.addToAllowedTools,toolPattern:Y.toolPattern,permissionMode:Y.permissionMode,hardDeny:Y.hardDeny,hasDenyMessage:!!Y.denyMessage});let Q=this.pendingPermissions.get(Y.requestId);if(!Q)m.warn(`[ClaudeAgent] No pending permission found for request_id: ${Y.requestId}`);if(Y.approved&&Y.addToAllowedTools){let K=this.processManager.getSession(J);if(K){let z=Y.toolPattern||(Q?this.generateToolPattern(Q.action,Q.params):null);if(z)await this.addToAllowedTools(K.directoryPath,z),m.debug("[ClaudeAgent] Added tool pattern to settings.local.json:",{toolPattern:z,projectPath:K.directoryPath})}}let W=this.processManager.getSession(J);if(Y.permissionMode&&W?.sessionId){if(m.debug("[ClaudeAgent] Permission mode change requested, will respawn session:",{sessionId:W.sessionId,newPermissionMode:Y.permissionMode}),this.processManager.sendPermissionResponse(J,{request_id:Y.requestId,behavior:"allow",updatedInput:Q?.params,message:"Permission mode is changing. Stopping current execution for session respawn."}),await new Promise((z)=>setTimeout(z,200)),await this.processManager.respawnWithPermissionMode(W.sessionId,Y.permissionMode,"proceed with implementation"))this.publishStatus(W.userId,W.sessionId,{type:"session_restarted",permissionMode:Y.permissionMode,timestamp:Date.now()});else this.publishStatus(W.userId,W.sessionId,{type:"error",error:"Failed to respawn session with new permission mode",timestamp:Date.now()});if(Q)this.pendingPermissions.delete(Y.requestId);d7.removePermission(Y.requestId).catch((z)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",z)});return}if(Y.approved&&Y.answers&&Object.keys(Y.answers).length>0){let K={...Q?.params,answers:Y.answers};m.info("[ClaudeAgent] Sending AskUserQuestion response:",{requestId:Y.requestId,answerCount:Object.keys(Y.answers).length}),this.processManager.sendPermissionResponse(J,{request_id:Y.requestId,behavior:"allow",updatedInput:K})}else if(Y.approved)this.processManager.sendPermissionResponse(J,{request_id:Y.requestId,behavior:"allow",updatedInput:Q?Q.params:void 0});else{let K=Y.denyMessage||"Permission denied by user",z=Y.hardDeny!==!1;if(m.info("[ClaudeAgent] Sending deny response:",{requestId:Y.requestId,hardDeny:z,hasDenyMessage:!!Y.denyMessage}),this.processManager.sendPermissionResponse(J,{request_id:Y.requestId,behavior:"deny",message:K,hardDeny:z}),z)m.info("[ClaudeAgent] Hard deny - stopping session:",{sessionId:J}),setTimeout(()=>{this.processManager.stopSession(J),this.publishStatus(Z,J,{type:"session_stopped",reason:"permission_denied",message:K,timestamp:Date.now()})},100)}if(Q)this.pendingPermissions.delete(Y.requestId);d7.removePermission(Y.requestId).catch((K)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",K)})}catch(Y){m.error("[ClaudeAgent] Error handling permission response:",{userId:Z,sessionId:J,error:Y instanceof Error?Y.message:"Unknown error"})}}handleSessionStop(Z,J){m.info("[ClaudeAgent] Session stop request:",{userId:Z,sessionId:J}),this.processManager.stopSession(J)}async handlePendingPermissionsRequest(Z,J){try{let X=JSON.parse(J.toString()),{clientId:$,sessionId:Y,projectPath:Q}=X;if(!$){m.warn("[ClaudeAgent] Pending permissions request missing clientId");return}m.debug("[ClaudeAgent] Pending permissions request:",{clientId:$,sessionId:Y,projectPath:Q});let W;if(Y)W=await d7.getPermissionsForSession(Y);else if(Q)W=await d7.getPermissionsForProject(Q);else W=await d7.getAllPermissions();let K=this.processManager.getAllSessions(),z=new Set(K.filter((F)=>F.status==="waiting_permission"&&F.sessionId).map((F)=>F.sessionId)),G=W.filter((F)=>z.has(F.sessionId)),H=`permissions/pending/${$}/response`,V={permissions:G,timestamp:Date.now()};await this.mqttClient?.publish(H,JSON.stringify(V)),m.debug("[ClaudeAgent] Sent pending permissions response:",{clientId:$,count:G.length,totalStored:W.length})}catch(X){m.error("[ClaudeAgent] Error handling pending permissions request:",X)}}async handleClaudeSettingsRequest(Z,J){try{let X=JSON.parse(J.toString()),{clientId:$}=X;if(!$){m.warn("[ClaudeAgent] Claude settings request missing clientId");return}m.debug("[ClaudeAgent] Claude settings request:",{clientId:$});let Y=bQ.join(i30.homedir(),".claude","settings.json"),Q={};try{let z=Bun.file(Y);if(await z.exists())Q=JSON.parse(await z.text())}catch(z){m.warn("[ClaudeAgent] Could not read Claude settings file:",z)}let W=`settings/claude/${$}/response`,K={success:!0,settings:Q,timestamp:Date.now()};await this.mqttClient?.publish(W,JSON.stringify(K)),m.debug("[ClaudeAgent] Sent Claude settings response:",{clientId:$})}catch(X){m.error("[ClaudeAgent] Error handling Claude settings request:",X)}}async handleClaudeSettingsUpdate(Z,J){try{let X=JSON.parse(J.toString()),{clientId:$,key:Y,value:Q}=X;if(!$||!Y){m.warn("[ClaudeAgent] Claude settings update missing clientId or key");return}m.debug("[ClaudeAgent] Claude settings update:",{clientId:$,key:Y,value:Q});let W=bQ.join(i30.homedir(),".claude"),K=bQ.join(W,"settings.json");try{if(!dH.existsSync(W))dH.mkdirSync(W,{recursive:!0})}catch(V){}let z={};try{let V=Bun.file(K);if(await V.exists())z=JSON.parse(await V.text())}catch(V){m.warn("[ClaudeAgent] Could not read existing Claude settings, starting fresh")}z[Y]=Q,await Bun.write(K,JSON.stringify(z,null,2));let G=`settings/claude/${$}/response`,H={success:!0,timestamp:Date.now()};await this.mqttClient?.publish(G,JSON.stringify(H)),m.debug("[ClaudeAgent] Updated Claude setting:",{clientId:$,key:Y,value:Q})}catch(X){m.error("[ClaudeAgent] Error handling Claude settings update:",X);try{let Y=`settings/claude/${JSON.parse(J.toString()).clientId}/response`,Q={success:!1,error:X instanceof Error?X.message:"Unknown error",timestamp:Date.now()};await this.mqttClient?.publish(Y,JSON.stringify(Q))}catch{}}}async handleCheckpointListRequest(Z,J,X){try{let $=JSON.parse(X.toString()),Y=$.limit||5;m.debug("[ClaudeAgent] Checkpoint list request:",{userId:Z,sessionId:J,limit:Y});let Q=$?.directoryPath,{parseSessionCheckpoints:W}=await Promise.resolve().then(() => (p30(),l30)),K=await W(J,Q,Y),z=K.some((H)=>H.hasFileChanges),G=`claude/${Z}/checkpoints/response/${J}`;await this.mqttClient?.publish(G,JSON.stringify({sessionId:J,checkpoints:K,hasAnyFileChanges:z})),m.debug("[ClaudeAgent] Checkpoint list response:",{sessionId:J,checkpointCount:K.length,hasAnyFileChanges:z})}catch($){m.error("[ClaudeAgent] Checkpoint list error:",$);let Y=`claude/${Z}/checkpoints/response/${J}`;await this.mqttClient?.publish(Y,JSON.stringify({sessionId:J,checkpoints:[],hasAnyFileChanges:!1,error:$ instanceof Error?$.message:"Unknown error"}))}}async handleRewindRequest(Z,J,X){try{let $=JSON.parse(X.toString()),{checkpointUuid:Y,mode:Q,directoryPath:W}=$;m.info("[ClaudeAgent] Rewind request:",{userId:Z,sessionId:J,checkpointUuid:Y,mode:Q,directoryPath:W});let K=this.processManager.getSession(J),z=W||K?.worktreePath||K?.directoryPath||process.cwd();if(K)this.processManager.stopSession(J),await new Promise((B)=>setTimeout(B,300));let G=!0,H,V;switch(Q){case"code_only":{let B=await this.processManager.executeFileRewind(J,Y,z);G=B.success,H=B.error;break}case"conversation_only":{let B=await this.processManager.executeConversationFork(J,z,Y);G=B.success,H=B.error,V=B.newSessionId;break}case"both":{let B=await this.processManager.executeFullRewind(J,Y,z);G=B.success,H=B.error,V=B.newSessionId;break}}let F=`claude/${Z}/rewind/response/${J}`;if(G)await this.mqttClient?.publish(F,JSON.stringify({type:"rewind_complete",sessionId:J,checkpointUuid:Y,mode:Q,newSessionId:V})),m.info("[ClaudeAgent] Rewind complete:",{sessionId:J,checkpointUuid:Y,mode:Q,newSessionId:V});else await this.mqttClient?.publish(F,JSON.stringify({type:"rewind_failed",sessionId:J,checkpointUuid:Y,error:H||"Unknown error"})),m.error("[ClaudeAgent] Rewind failed:",{sessionId:J,checkpointUuid:Y,error:H})}catch($){m.error("[ClaudeAgent] Rewind error:",$);let Y=`claude/${Z}/rewind/response/${J}`;await this.mqttClient?.publish(Y,JSON.stringify({type:"rewind_failed",sessionId:J,checkpointUuid:"",error:$ instanceof Error?$.message:"Unknown error"}))}}handleSessionInitialized(Z,J){if(m.debug("[ClaudeAgent] Session initialized callback:",{tempId:Z.tempId,sessionId:Z.sessionId,model:Z.model}),Z.worktreePath&&Z.tempId&&Z.sessionId)this.worktreeManager.updateSessionId(Z.worktreePath,Z.tempId,Z.sessionId);let X=J.slash_commands||[],$=J.agents||[],Y=J.skills||[];if(m.debug("[ClaudeAgent] Available commands from init:",{slashCommands:X.length,agents:$.length,skills:Y.length}),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:X,agents:$,skills:Y,timestamp:Date.now()}),this.sessionsService){let Q=Z.worktreePath||Z.directoryPath;this.sessionsService.notifySessionCreated(Z.directoryPath,Q).catch((W)=>{m.warn("[ClaudeAgent] Failed to notify sessions service about new session",{error:W})})}}handleTitleGenerated(Z,J){m.debug("[ClaudeAgent] Title generated callback:",{sessionId:Z.sessionId,title:J}),this.publishStatus(Z.userId,Z.sessionId,{type:"title_generated",title:J,timestamp:Date.now()})}handleAssistantMessage(Z,J){if(this.totalMessagesProcessed++,Z.sessionId)this.publishOutput(Z.userId,Z.sessionId,J)}handlePermissionRequest(Z,J){if(m.debug("[ClaudeAgent] Permission request callback:",{sessionId:Z.sessionId,requestId:J.request_id,action:J.action}),Z.sessionId)this.publishPermissionRequest(Z,J)}handleSessionError(Z,J){m.error("[ClaudeAgent] Session error callback:",{sessionId:Z.sessionId,tempId:Z.tempId,error:J}),this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"error",error:J,timestamp:Date.now()})}handleSessionStopped(Z,J){if(m.debug("[ClaudeAgent] Session stopped callback:",{sessionId:Z.sessionId,tempId:Z.tempId,reason:J}),this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"session_stopped",reason:J,timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifySessionStopped()}handleProcessingStarted(Z){if(m.debug("[ClaudeAgent] Processing started:",{sessionId:Z.sessionId,tempId:Z.tempId}),Z.sessionId)this.publishStatus(Z.userId,Z.sessionId,{type:"session_processing",sessionId:Z.sessionId,timestamp:Date.now()})}handleProcessingComplete(Z){if(m.debug("[ClaudeAgent] Processing complete:",{sessionId:Z.sessionId,tempId:Z.tempId}),Z.sessionId)this.publishStatus(Z.userId,Z.sessionId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()})}handleContextUpdate(Z,J){if(m.debug(`[ClaudeAgent] Context update for session ${Z.sessionId}:`,{total:J.total,percentage:J.percentage,inputTokens:J.inputTokens,cacheCreation:J.cacheCreation,cacheRead:J.cacheRead,breakdown:{systemPrompt:J.systemPrompt,tools:J.tools,messages:J.messages,remaining:J.remaining}}),Z.sessionId)this.publishContextUpdate(Z.userId,Z.sessionId,J);else m.warn("[ClaudeAgent] Cannot publish context update - no sessionId yet")}publishStatus(Z,J,X){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish status - MQTT client not available");return}let $=`claude/${Z}/status/${J}`,Y=JSON.stringify(X);this.mqttClient.publish($,Y).catch((Q)=>{m.error(`[ClaudeAgent] Failed to publish status to ${$}`,{error:Q.message})})}publishOutput(Z,J,X){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish output - MQTT client not available");return}let $=`claude/${Z}/output/${J}`,Y=JSON.stringify(X);this.mqttClient.publish($,Y).catch((Q)=>{m.error(`[ClaudeAgent] Failed to publish output to ${$}`,{error:Q.message})})}publishContextUpdate(Z,J,X){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish context update - MQTT client not available");return}let $=`claude/${Z}/context/${J}`,Y=JSON.stringify(X);this.mqttClient.publish($,Y).catch((Q)=>{m.error(`[ClaudeAgent] Failed to publish context to ${$}`,{error:Q.message})})}publishPermissionRequest(Z,J){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish permission request - MQTT client not available");return}let{userId:X,sessionId:$}=Z;m.debug("[ClaudeAgent] Raw permission request structure:",{fullRequest:JSON.stringify(J)});let Y=J,Q=Y.request||{},W=Q.tool_name||Y.tool_name||Y.action||"unknown_tool",K=Q.input||Y.tool_input||Y.params||{},z=Q.permission_suggestions||[],G=Q.decision_reason||"",H=Q.blocked_path||"";this.pendingPermissions.set(Y.request_id,{requestId:Y.request_id,action:W,params:K}),d7.addPermission({requestId:Y.request_id,sessionId:$,projectPath:Z.directoryPath,action:W,params:K,permissionSuggestions:z.length>0?z:void 0,decisionReason:G||void 0,blockedPath:H||void 0,createdAt:new Date().toISOString()}).catch((U)=>{m.error("[ClaudeAgent] Failed to persist pending permission:",U)});let V={request_id:Y.request_id,action:W,params:K,permission_suggestions:z,decision_reason:G,blocked_path:H},F=`claude/${X}/permission/request/${$}`,B=JSON.stringify(V);m.debug("[ClaudeAgent] Publishing transformed permission request:",{topic:F,request_id:V.request_id,action:V.action}),this.mqttClient.publish(F,B).catch((U)=>{m.error(`[ClaudeAgent] Failed to publish permission request to ${F}`,{error:U.message})})}extractUserIdFromTopic(Z){return Z.split("/")[1]||""}extractIdsFromInputTopic(Z){let J=Z.split("/");return{userId:J[1]||"",sessionId:J[3]||""}}extractIdsFromPermissionTopic(Z){let J=Z.split("/");return{userId:J[1]||"",sessionId:J[4]||""}}extractIdsFromStopTopic(Z){let J=Z.split("/");return{userId:J[1]||"",sessionId:J[4]||""}}generateToolPattern(Z,J){switch(Z){case"Bash":case"bash":case"execute_command":return`Bash(${J.command})`;case"Read":case"read":case"read_file":return`Read(${J.file_path})`;case"Write":case"write":case"write_file":return`Write(${J.file_path})`;case"Edit":case"edit":return`Edit(${J.file_path})`;default:return Z}}async addToAllowedTools(Z,J){try{let X=bQ.join(Z,".claude"),$=bQ.join(X,"settings.local.json");if(!dH.existsSync(X))dH.mkdirSync(X,{recursive:!0});let Y={},Q=Bun.file($);if(await Q.exists())try{let W=await Q.text();Y=JSON.parse(W)}catch{Y={}}if(Y.permissions=Y.permissions||{},Y.permissions.allow=Y.permissions.allow||[],!Y.permissions.allow.includes(J))Y.permissions.allow.push(J);await Bun.write($,JSON.stringify(Y,null,2)),m.debug("[ClaudeAgent] Updated settings.local.json with allowed tool:",{settingsPath:$,toolPattern:J,totalAllowed:Y.permissions.allow.length})}catch(X){m.error("[ClaudeAgent] Failed to update settings.local.json:",{projectPath:Z,toolPattern:J,error:X instanceof Error?X.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.processManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessions(){return this.processManager.getAllSessions().filter((Z)=>Z.sessionId).map((Z)=>({sessionId:Z.sessionId,projectPath:Z.directoryPath,status:Z.status,worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch}))}}import*as K1 from"fs/promises";import*as Fj from"fs";import*as u1 from"path";import*as u7 from"fs/promises";var q$=x(),n30=10485760;async function W1(Z,J={}){let{maxSize:X=n30,encoding:$="utf-8",logWarnings:Y=!0}=J;try{let Q=await u7.stat(Z);if(!Q.isFile()){if(Y)q$.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Q.size>X){if(Y)q$.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Q.size,maxSize:X});return null}return await u7.readFile(Z,$)}catch(Q){if(Q.code!=="ENOENT"&&Y)q$.debug("[SafeFS] Error reading file",{filePath:Z,error:Q});return null}}async function o30(Z,J={}){let{maxSize:X=n30,logWarnings:$=!0}=J;try{let Y=await u7.stat(Z);if(!Y.isFile()){if($)q$.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Y.size>X){if($)q$.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Y.size,maxSize:X});return null}return await u7.readFile(Z)}catch(Y){if(Y.code!=="ENOENT"&&$)q$.debug("[SafeFS] Error reading file",{filePath:Z,error:Y});return null}}async function c4(Z){try{return(await u7.stat(Z)).isDirectory()}catch{return!1}}async function E9(Z){try{return await u7.stat(Z)}catch{return null}}var I9=x();class cH{validatePath(Z,J){try{let X=u1.resolve(Z),$=u1.resolve(X,J);if(!($===X||$.startsWith(X+u1.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};try{let Q=Fj.realpathSync($),W=Fj.realpathSync(X);if(!(Q===W||Q.startsWith(W+u1.sep)))return{valid:!1,fullPath:"",error:"Symlink escape detected: symlink points outside project directory"}}catch{}return{valid:!0,fullPath:$}}catch(X){return{valid:!1,fullPath:"",error:`Path validation error: ${X instanceof Error?X.message:"Unknown error"}`}}}async listDirectory(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{entries:[],error:X.error};try{if(!(await K1.stat(X.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let Y=await K1.readdir(X.fullPath,{withFileTypes:!0}),Q=await Promise.all(Y.map(async(W)=>{let K=u1.join(X.fullPath,W.name);try{let z=await K1.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($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] listDirectory error",{error:Y,path:X.fullPath}),{entries:[],error:`Failed to list directory: ${Y}`}}}async readFile(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{content:"",size:0,error:X.error};try{let $=await E9(X.fullPath);if(!$||!$.isFile())return{content:"",size:0,error:"Path is not a file"};let Y=await W1(X.fullPath);if(Y===null)return{content:"",size:0,error:"Failed to read file"};return{content:Y,size:Number($.size)}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] readFile error",{error:Y,path:X.fullPath}),{content:"",size:0,error:`Failed to read file: ${Y}`}}}async writeFile(Z,J,X){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{let Y=u1.dirname($.fullPath);return await K1.mkdir(Y,{recursive:!0}),await K1.writeFile($.fullPath,X,"utf-8"),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return I9.error("[FileManager] writeFile error",{error:Q,path:$.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}async createFile(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{try{return await K1.access(X.fullPath),{success:!1,error:"File already exists"}}catch{}let $=u1.basename(J);if(!this.isValidFilename($))return{success:!1,error:"Invalid filename"};let Y=u1.dirname(X.fullPath);return await K1.mkdir(Y,{recursive:!0}),await K1.writeFile(X.fullPath,"","utf-8"),{success:!0}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] createFile error",{error:Y,path:X.fullPath}),{success:!1,error:`Failed to create file: ${Y}`}}}async createDirectory(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{let $=u1.basename(J);if(!this.isValidFilename($))return{success:!1,error:"Invalid directory name"};try{if((await K1.stat(X.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await K1.mkdir(X.fullPath,{recursive:!0}),{success:!0}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] createDirectory error",{error:Y,path:X.fullPath}),{success:!1,error:`Failed to create directory: ${Y}`}}}async deleteFile(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{if(!(await K1.stat(X.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await K1.unlink(X.fullPath),{success:!0}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] deleteFile error",{error:Y,path:X.fullPath}),{success:!1,error:`Failed to delete file: ${Y}`}}}async deleteDirectory(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};if(X.fullPath===u1.resolve(Z))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await K1.stat(X.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await K1.rm(X.fullPath,{recursive:!0,force:!0}),{success:!0}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] deleteDirectory error",{error:Y,path:X.fullPath}),{success:!1,error:`Failed to delete directory: ${Y}`}}}async pathExists(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return!1;try{return await K1.access(X.fullPath),!0}catch{return!1}}async getStats(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return null;try{let $=await K1.stat(X.fullPath);return{isFile:$.isFile(),isDirectory:$.isDirectory(),size:$.size,modified:$.mtime.toISOString()}}catch{return null}}async readFileBinary(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{content:Buffer.alloc(0),size:0,mimeType:"",error:X.error};try{let $=await E9(X.fullPath);if(!$||!$.isFile())return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Path is not a file"};let Y=52428800;if($.size>Y)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"File exceeds maximum size of 50MB"};let Q=await o30(X.fullPath,{maxSize:Y});if(Q===null)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Failed to read file"};let W=this.getMimeType(u1.basename(J));return{content:Q,size:Number($.size),mimeType:W}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] readFileBinary error",{error:Y,path:X.fullPath}),{content:Buffer.alloc(0),size:0,mimeType:"",error:`Failed to read file: ${Y}`}}}async writeFileBinary(Z,J,X){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{let Y=u1.basename(J);if(!this.isValidFilename(Y))return{success:!1,error:"Invalid filename"};let Q=u1.dirname($.fullPath);return await K1.mkdir(Q,{recursive:!0}),await K1.writeFile($.fullPath,X),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return I9.error("[FileManager] writeFileBinary error",{error:Q,path:$.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}getMimeType(Z){let J=u1.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"],X=(Z.split(".")[0]||"").toUpperCase();if(J.includes(X))return!1;if(/[<>:"|?*\x00-\x1f]/.test(Z))return!1;if(Z==="."||Z==="..")return!1;return!0}}import*as Bj from"path";var l4=x(),C$=51200,a30=50;class lH{name="File Browser Service";running=!1;startedAt;mqttClient=null;fileManager;requestsHandled=0;messageHandlers=new Map;fileSaveOperations=new Map;binaryUploadOperations=new Map;constructor(){this.fileManager=new cH}setMQTTClient(Z){this.mqttClient=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,l4.info("[FileBrowser] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(Z){throw l4.error("[FileBrowser] Failed to start",Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.mqttClient){for(let[Z,J]of this.messageHandlers)this.mqttClient.unsubscribe(Z,J);this.messageHandlers.clear()}this.fileSaveOperations.clear(),this.binaryUploadOperations.clear(),l4.info("[FileBrowser] Service stopped")}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)}),l4.info("[FileBrowser] MQTT handlers registered")}registerHandler(Z,J){if(!this.mqttClient)return;this.messageHandlers.set(Z,J),this.mqttClient.subscribe(Z,J)}async handleDirectoryListRequest(Z){try{let J=JSON.parse(Z.toString()),X=await this.fileManager.listDirectory(J.projectPath,J.relativePath),$={path:J.relativePath,entries:X.entries,timestamp:Date.now(),error:X.error};await this.publishResponse(`files/list/${J.clientId}/response`,$),this.requestsHandled++}catch(J){l4.error("[FileBrowser] Error handling directory list request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileContentRequest(Z){try{let J=JSON.parse(Z.toString()),X=await this.fileManager.readFile(J.projectPath,J.relativePath),$=`files/content/${J.clientId}/response`;if(X.error){let Q={path:J.relativePath,chunk:{chunkIndex:0,totalChunks:1,content:""},totalSize:0,timestamp:Date.now(),error:X.error};await this.publishResponse($,Q);return}let Y=Math.max(1,Math.ceil(X.content.length/C$));for(let Q=0;Q<Y;Q++){let W=Q*C$,K=Math.min(W+C$,X.content.length),z=X.content.slice(W,K),G={path:J.relativePath,chunk:{chunkIndex:Q,totalChunks:Y,content:z},totalSize:X.size,timestamp:Date.now()};if(await this.publishResponse($,G),Q<Y-1)await this.delay(a30)}this.requestsHandled++}catch(J){l4.error("[FileBrowser] Error handling file content request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileSaveRequest(Z){try{let J=JSON.parse(Z.toString()),X=`${J.clientId}:${J.relativePath}`;if(J.chunk.chunkIndex===0)this.fileSaveOperations.set(X,{chunks:new Map,totalChunks:J.chunk.totalChunks,totalSize:J.totalSize});let $=this.fileSaveOperations.get(X);if(!$){await this.sendSaveResponse(J,!1,"Save operation not initialized");return}if($.chunks.set(J.chunk.chunkIndex,J.chunk.content),await this.sendSaveResponse(J,!0),$.chunks.size===$.totalChunks){let Y=[];for(let K=0;K<$.totalChunks;K++){let z=$.chunks.get(K);if(z!==void 0)Y.push(z)}let Q=Y.join(""),W=await this.fileManager.writeFile(J.projectPath,J.relativePath,Q);if(this.fileSaveOperations.delete(X),!W.error)this.requestsHandled++}}catch(J){l4.error("[FileBrowser] Error handling file save request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileCreateRequest(Z){try{let J=JSON.parse(Z.toString()),X;if(J.type==="directory")X=await this.fileManager.createDirectory(J.projectPath,J.relativePath);else X=await this.fileManager.createFile(J.projectPath,J.relativePath);let $={path:J.relativePath,success:X.success,type:J.type,timestamp:Date.now(),error:X.error};if(await this.publishResponse(`files/create/${J.clientId}/response`,$),X.success)this.requestsHandled++}catch(J){l4.error("[FileBrowser] Error handling file create request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileDeleteRequest(Z){try{let J=JSON.parse(Z.toString()),X=await this.fileManager.getStats(J.projectPath,J.relativePath),$;if(!X)$={success:!1,error:"Path does not exist"};else if(X.isDirectory)$=await this.fileManager.deleteDirectory(J.projectPath,J.relativePath);else $=await this.fileManager.deleteFile(J.projectPath,J.relativePath);let Y={path:J.relativePath,success:$.success,timestamp:Date.now(),error:$.error};if(await this.publishResponse(`files/delete/${J.clientId}/response`,Y),$.success)this.requestsHandled++}catch(J){l4.error("[FileBrowser] Error handling file delete request",{error:J instanceof Error?J.message:"Unknown error"})}}async sendSaveResponse(Z,J,X){let $={path:Z.relativePath,success:J,chunkIndex:Z.chunk.chunkIndex,totalChunks:Z.chunk.totalChunks,timestamp:Date.now(),error:X};await this.publishResponse(`files/save/${Z.clientId}/response`,$)}async publishResponse(Z,J){if(!this.mqttClient){l4.error("[FileBrowser] MQTT client not available");return}await this.mqttClient.publish(Z,JSON.stringify(J),{qos:1})}delay(Z){return new Promise((J)=>setTimeout(J,Z))}async handleBinaryUploadRequest(Z){try{let J=JSON.parse(Z.toString()),X=`${J.clientId}:${J.relativePath}`;if(J.chunk.chunkIndex===0){if(J.totalSize>52428800){await this.sendBinaryUploadResponse(J,!1,"File exceeds 50MB limit",0);return}this.binaryUploadOperations.set(X,{chunks:new Map,totalChunks:J.chunk.totalChunks,totalSize:J.totalSize,filename:J.filename,mimeType:J.mimeType,receivedBytes:0})}let $=this.binaryUploadOperations.get(X);if(!$){await this.sendBinaryUploadResponse(J,!1,"Upload operation not initialized",0);return}let Y=Buffer.from(J.chunk.data,"base64");if($.chunks.set(J.chunk.chunkIndex,Y),$.receivedBytes+=Y.length,await this.sendBinaryUploadResponse(J,!0,void 0,$.receivedBytes),$.chunks.size===$.totalChunks){let Q=[];for(let z=0;z<$.totalChunks;z++){let G=$.chunks.get(z);if(G)Q.push(G)}let W=Buffer.concat(Q),K=await this.fileManager.writeFileBinary(J.projectPath,J.relativePath,W);if(this.binaryUploadOperations.delete(X),K.error)l4.error("[FileBrowser] Binary upload write failed",{error:K.error});else this.requestsHandled++,l4.info("[FileBrowser] Binary upload completed",{path:J.relativePath,size:W.length})}}catch(J){l4.error("[FileBrowser] Error handling binary upload",{error:J instanceof Error?J.message:"Unknown error"})}}async sendBinaryUploadResponse(Z,J,X,$){let Y={path:Z.relativePath,success:J,chunkIndex:Z.chunk.chunkIndex,totalChunks:Z.chunk.totalChunks,bytesReceived:$||0,timestamp:Date.now(),error:X};await this.publishResponse(`files/upload/${Z.clientId}/response`,Y)}async handleBinaryDownloadRequest(Z){try{let J=JSON.parse(Z.toString()),X=`files/download/${J.clientId}/response`,$=await this.fileManager.readFileBinary(J.projectPath,J.relativePath);if($.error){let K={path:J.relativePath,filename:Bj.basename(J.relativePath),mimeType:"",chunk:{chunkIndex:0,totalChunks:1,data:""},totalSize:0,timestamp:Date.now(),error:$.error};await this.publishResponse(X,K);return}let Y=$.content.toString("base64"),Q=Math.max(1,Math.ceil(Y.length/C$)),W=Bj.basename(J.relativePath);for(let K=0;K<Q;K++){let z=K*C$,G=Math.min(z+C$,Y.length),H=Y.slice(z,G),V={path:J.relativePath,filename:W,mimeType:$.mimeType,chunk:{chunkIndex:K,totalChunks:Q,data:H},totalSize:$.size,timestamp:Date.now()};if(await this.publishResponse(X,V),K<Q-1)await this.delay(a30)}this.requestsHandled++,l4.info("[FileBrowser] Binary download completed",{path:J.relativePath,size:$.size,chunks:Q})}catch(J){l4.error("[FileBrowser] Error handling binary download",{error:J instanceof Error?J.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,pendingSaveOperations:this.fileSaveOperations.size}}}var o=x();class pH{name="Git Service";running=!1;startedAt;mqttClient=null;worktreeManager;requestsHandled=0;messageHandlers=new Map;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){this.worktreeManager=new T$}setMQTTClient(Z){this.mqttClient=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,this.ghAuthResult=await F30(),!this.ghAuthResult.authenticated)o.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else{o.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username,gitProtocol:this.ghAuthResult.gitProtocol});let Z=await U30();if(!Z.success)o.warn("[GitService] Could not sync gh config git_protocol",{error:Z.error});let J=await L30();if(!J.success)o.warn("[GitService] Could not setup git credential helper",{error:J.error})}if(this.mqttClient)this.registerMQTTHandlers();o.info("[GitService] Service started")}catch(Z){throw o.error("[GitService] Failed to start",Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.mqttClient){for(let[Z,J]of this.messageHandlers)this.mqttClient.unsubscribe(Z,J),o.debug(`[GitService] Unsubscribed from ${Z}`);this.messageHandlers.clear()}this.worktreeManager.clearCache(),o.info("[GitService] Service stopped")}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)}),o.info("[GitService] MQTT handlers registered")}registerHandler(Z,J){if(!this.mqttClient)return;this.messageHandlers.set(Z,J),this.mqttClient.subscribe(Z,J),o.debug(`[GitService] Subscribed to ${Z}`)}async publishResponse(Z,J){if(!this.mqttClient){o.error("[GitService] MQTT client not available");return}await this.mqttClient.publish(Z,JSON.stringify(J),{qos:1})}async handleOrgsRequest(Z){try{let J=JSON.parse(Z.toString());if(o.debug("[GitService] Orgs request",{clientId:J.clientId}),!this.ghAuthResult.authenticated){let Y={orgs:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/orgs/${J.clientId}/response`,Y);return}let $={orgs:await Wj(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling orgs request",{error:J})}}async handleReposRequest(Z){try{let J=JSON.parse(Z.toString()),X=J.requestId||J.clientId;if(o.debug("[GitService] Repos request",{clientId:J.clientId,requestId:J.requestId,org:J.org,limit:J.limit}),!this.ghAuthResult.authenticated){let Q={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/${X}/response`,Q);return}let Y={repos:await bH(J.org,J.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${X}/response`,Y),this.requestsHandled++}catch(J){o.error("[GitService] Error handling repos request",{error:J})}}async handleSearchReposRequest(Z){try{let J=JSON.parse(Z.toString());if(o.debug("[GitService] Search repos request",{clientId:J.clientId,query:J.query,limit:J.limit}),!this.ghAuthResult.authenticated){let X={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/search/${J.clientId}/response`,X);return}await D30(J.query,async(X,$,Y)=>{let Q={repos:X,timestamp:Date.now(),source:$,isComplete:Y};await this.publishResponse(`git/repos/search/${J.clientId}/response`,Q),o.debug("[GitService] Sent search results",{source:$,count:X.length,isComplete:Y})},J.limit||50),this.requestsHandled++}catch(J){o.error("[GitService] Error handling search repos request",{error:J})}}async handleBranchesRequest(Z){try{let J=JSON.parse(Z.toString());if(o.debug("[GitService] Branches request",{clientId:J.clientId,owner:J.owner,repo:J.repo}),!this.ghAuthResult.authenticated){let Y={branches:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/branches/${J.clientId}/response`,Y);return}let X=await _30(J.owner,J.repo),$={branches:X.branches,defaultBranch:X.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/branches/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling branches request",{error:J})}}async handleCloneRequest(Z){try{let J=JSON.parse(Z.toString());if(o.info("[GitService] Clone request",{clientId:J.clientId,repoUrl:J.repoUrl,targetPath:J.targetPath,branch:J.branch}),!this.ghAuthResult.authenticated){let Y={success:!1,error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/clone/${J.clientId}/response`,Y);return}let X=await O30(J.repoUrl,J.targetPath,J.branch),$=X.success?{success:!0,path:X.path,defaultBranch:X.defaultBranch,timestamp:Date.now()}:{success:!1,error:X.error||"Clone failed",timestamp:Date.now()};await this.publishResponse(`git/clone/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling clone request",{error:J})}}async handleIsRepoRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Is-repo request",{clientId:J.clientId,path:J.path});let X=await M$(J.path),$;if(X){let[Y,Q,W]=await Promise.all([h5(J.path),DJ(J.path),E30(J.path)]);$={isGitRepo:!0,repoRoot:Y||void 0,defaultBranch:Q||void 0,remoteUrl:W||void 0,timestamp:Date.now()}}else $={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling is-repo request",{error:J});let X=JSON.parse(Z.toString()),$={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${X.clientId}/response`,$)}}async handleWorktreeGetOrCreateRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Worktree get-or-create request",{clientId:J.clientId,repoPath:J.repoPath,sessionId:J.sessionId});let{worktree:X,isNew:$}=await this.worktreeManager.getOrCreateForSession(J.sessionId,J.repoPath),Y={success:!0,worktreePath:X.path,branch:X.branch,isNew:$,timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${J.clientId}/response`,Y),this.requestsHandled++}catch(J){o.error("[GitService] Error handling worktree get-or-create request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${X.clientId}/response`,$)}}async handleWorktreeGetRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Worktree get request",{clientId:J.clientId,repoPath:J.repoPath,sessionId:J.sessionId});let X=await this.worktreeManager.getWorktreeForSession(J.sessionId,J.repoPath),$=X?{exists:!0,worktreePath:X.path,branch:X.branch,timestamp:Date.now()}:{exists:!1,timestamp:Date.now()};await this.publishResponse(`git/worktree/get/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling worktree get request",{error:J})}}async handleWorktreeListRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Worktree list request",{clientId:J.clientId,repoPath:J.repoPath});let $={worktrees:await this.worktreeManager.listWorktreesForRepo(J.repoPath),timestamp:Date.now()};await this.publishResponse(`git/worktree/list/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling worktree list request",{error:J})}}async handleStatusRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Status request",{clientId:J.clientId,path:J.path});let $={success:!0,status:await Kj(J.path),timestamp:Date.now()};await this.publishResponse(`git/status/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling status request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/status/${X.clientId}/response`,$)}}async handleDiffRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Diff request",{clientId:J.clientId,path:J.path,file:J.file,staged:J.staged});let X=await j30(J.path,J.file,J.staged),$={success:!0,diff:X.diff,isBinary:X.isBinary,timestamp:Date.now()};await this.publishResponse(`git/diff/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling diff request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/diff/${X.clientId}/response`,$)}}async handleChangesAllRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Changes all request",{clientId:J.clientId,repoPath:J.repoPath});let X=await this.worktreeManager.listWorktreesForRepo(J.repoPath),$={repoPath:J.repoPath,worktrees:[],totalChanges:0};for(let Q of X)try{let W=await Kj(Q.path);$.worktrees.push({worktreePath:Q.path,branch:Q.branch,sessionId:Q.sessionId,changes:W.files,totalCount:W.files.length}),$.totalChanges+=W.files.length}catch(W){o.warn("[GitService] Failed to get status for worktree",{path:Q.path,error:W})}let Y={success:!0,changes:$,timestamp:Date.now()};await this.publishResponse(`git/changes/all/${J.clientId}/response`,Y),this.requestsHandled++}catch(J){o.error("[GitService] Error handling changes all request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/changes/all/${X.clientId}/response`,$)}}async handleStageRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Stage request",{clientId:J.clientId,path:J.path,files:J.files}),await M30(J.path,J.files);let X={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${J.clientId}/response`,X),this.requestsHandled++}catch(J){o.error("[GitService] Error handling stage request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/stage/${X.clientId}/response`,$)}}async handleUnstageRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Unstage request",{clientId:J.clientId,path:J.path,files:J.files}),await A30(J.path,J.files);let X={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${J.clientId}/response`,X),this.requestsHandled++}catch(J){o.error("[GitService] Error handling unstage request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unstage/${X.clientId}/response`,$)}}async handleCommitRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Commit request",{clientId:J.clientId,path:J.path,signoff:J.signoff});let $={success:!0,commit:await T30(J.path,J.message,J.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling commit request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit/${X.clientId}/response`,$)}}async handleUnpushedCommitsRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Unpushed commits request",{clientId:J.clientId,path:J.path});let X=await j$(J.path),$={success:!0,commits:X.commits,upstream:X.upstream,ahead:X.ahead,timestamp:Date.now()};await this.publishResponse(`git/unpushed/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling unpushed commits request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unpushed/${X.clientId}/response`,$)}}async handlePushRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Push request",{clientId:J.clientId,path:J.path,force:J.force});let X=await I30(J.path,J.force),$={success:!0,commitsPushed:X.commitsPushed,remote:X.remote,branch:X.branch,timestamp:Date.now()};await this.publishResponse(`git/push/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling push request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/push/${X.clientId}/response`,$)}}async handleHistoryRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] History request",{clientId:J.clientId,path:J.path,limit:J.limit});let X=await y30(J.path,J.limit||50),$={success:!0,commits:X.commits,totalCount:X.totalCount,timestamp:Date.now()};await this.publishResponse(`git/history/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling history request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/history/${X.clientId}/response`,$)}}async handleCommitDetailsRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Commit details request",{clientId:J.clientId,path:J.path,commitHash:J.commitHash});let $={success:!0,commit:await S30(J.path,J.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling commit details request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-details/${X.clientId}/response`,$)}}async handleCommitFileDiffRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Commit file diff request",{clientId:J.clientId,path:J.path,commitHash:J.commitHash,filePath:J.filePath});let X=await x30(J.path,J.commitHash,J.filePath),$={success:!0,diff:X.diff,isBinary:X.isBinary,timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling commit file diff request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${X.clientId}/response`,$)}}async handleSyncRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Sync request",{clientId:J.clientId,path:J.path});let X=await k30(J.path),$=X.success?{success:!0,action:X.action,commitsPulled:X.commitsPulled,commitsPushed:X.commitsPushed,timestamp:Date.now()}:{success:!1,action:X.action,commitsPulled:X.commitsPulled,commitsPushed:X.commitsPushed,error:X.error||"Sync failed",conflictedFiles:X.conflictedFiles,timestamp:Date.now()};await this.publishResponse(`git/sync/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling sync request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/sync/${X.clientId}/response`,$)}}async handleCreatePRRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Create PR request",{clientId:J.clientId,path:J.path,title:J.title,baseBranch:J.baseBranch,draft:J.draft});let X=await v30(J.path,J.title,J.body,J.baseBranch,J.draft),$=X.success?{success:!0,prNumber:X.prNumber,prUrl:X.prUrl,timestamp:Date.now()}:{success:!1,error:X.error||"Failed to create pull request",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling create PR request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${X.clientId}/response`,$)}}async handleDefaultBranchRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Default branch request",{clientId:J.clientId,path:J.path});let X=await zj(J.path),$=X?{success:!0,defaultBranch:X,timestamp:Date.now()}:{success:!1,error:"Could not determine default branch",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling default branch request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${X.clientId}/response`,$)}}async handleExistingPRRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Existing PR request",{clientId:J.clientId,path:J.path});let X=await h30(J.path),$={exists:X.exists,prNumber:X.prNumber,prUrl:X.prUrl,title:X.title,state:X.state,draft:X.draft,error:X.error,timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling existing PR request",{error:J});let X=JSON.parse(Z.toString()),$={exists:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${X.clientId}/response`,$)}}async handleRemoteBranchesRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Remote branches request",{clientId:J.clientId,path:J.path});let X=await f30(J.path),$={success:!0,branches:X.branches,defaultBranch:X.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling remote branches request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${X.clientId}/response`,$)}}async handleCreateBranchRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Create branch request",{clientId:J.clientId,path:J.path,branchName:J.branchName,checkout:J.checkout});let X=await q30(J.path,J.branchName,J.checkout!==!1),$=X.success?{success:!0,branchName:J.branchName,timestamp:Date.now()}:{success:!1,error:X.error||"Failed to create branch",timestamp:Date.now()};await this.publishResponse(`git/create-branch/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling create branch request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-branch/${X.clientId}/response`,$)}}async handleLocalBranchesRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Local branches request",{clientId:J.clientId,path:J.path});let X=await N30(J.path),$={success:!0,branches:X.branches,currentBranch:X.currentBranch,timestamp:Date.now()};await this.publishResponse(`git/local-branches/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling local branches request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/local-branches/${X.clientId}/response`,$)}}async handleCheckoutBranchRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Checkout branch request",{clientId:J.clientId,path:J.path,branchName:J.branchName});let X=await C30(J.path,J.branchName),$=X.success?{success:!0,branchName:J.branchName,timestamp:Date.now()}:{success:!1,error:X.error||"Failed to checkout branch",timestamp:Date.now()};await this.publishResponse(`git/checkout-branch/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling checkout branch request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/checkout-branch/${X.clientId}/response`,$)}}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 ZQ0 from"path";import*as iH from"path";import*as r30 from"os";import*as nH from"fs";var z1=x(),dQ=iH.join(r30.homedir(),".ccc"),gQ=iH.join(dQ,"device-tokens.json"),mQ=iH.join(dQ,"notification-preferences.json");class s30{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if(!nH.existsSync(dQ))nH.mkdirSync(dQ,{recursive:!0}),z1.debug("[NotificationStorage] Created .ccc directory:",dQ)}catch(Z){throw z1.error("[NotificationStorage] Error ensuring directory:",Z),Z}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let Z=Bun.file(gQ);if(await Z.exists()){let J=await Z.text(),X=JSON.parse(J);if(X&&typeof X==="object"&&Array.isArray(X.tokens)){let $=X;return this.tokensCache=$,z1.debug("[NotificationStorage] Loaded tokens:",{count:$.tokens.length}),$}else if(X&&typeof X==="object")return z1.warn("[NotificationStorage] Invalid tokens file format, attempting to recover data"),this.tokensCache={tokens:Array.isArray(X.tokens)?X.tokens:[]},await this.saveTokens(this.tokensCache),this.tokensCache;else{z1.error("[NotificationStorage] Completely invalid tokens file format, creating backup");let $=`${gQ}.backup.${Date.now()}`;await Bun.write($,J),z1.error("[NotificationStorage] Backup saved to:",$)}}}catch(Z){z1.error("[NotificationStorage] Error loading tokens:",Z);try{let J=Bun.file(gQ);if(await J.exists()){let X=await J.text(),$=`${gQ}.backup.${Date.now()}`;await Bun.write($,X),z1.error("[NotificationStorage] Corrupted file backed up to:",$)}}catch{}}return this.tokensCache={tokens:[]},this.tokensCache}async saveTokens(Z){try{await this.ensureDirectory(),await Bun.write(gQ,JSON.stringify(Z,null,2)),this.tokensCache=Z,z1.debug("[NotificationStorage] Saved tokens:",{count:Z.tokens.length})}catch(J){throw z1.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:X,platform:$,deviceInfo:Y,createdAt:z?.createdAt??W,lastUsed:W};if(K>=0)Q.tokens[K]=G,z1.info("[NotificationStorage] Updated device token:",{deviceId:Z,platform:$,hasExpoPushToken:!!X});else Q.tokens.push(G),z1.info("[NotificationStorage] Registered new device token:",{deviceId:Z,platform:$,hasExpoPushToken:!!X});return await this.saveTokens(Q),G}async unregisterToken(Z){let J=await this.loadTokens(),X=J.tokens.length;if(J.tokens=J.tokens.filter(($)=>$.deviceId!==Z),J.tokens.length<X)return await this.saveTokens(J),z1.info("[NotificationStorage] Unregistered device token:",{deviceId:Z}),!0;return!1}async getToken(Z){return(await this.loadTokens()).tokens.find((X)=>X.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(),X=J.tokens.find(($)=>$.deviceId===Z);if(X)X.lastUsed=new Date().toISOString(),await this.saveTokens(J)}async cleanupOldTokens(Z=90){let J=await this.loadTokens(),X=new Date;X.setDate(X.getDate()-Z);let $=X.toISOString(),Y=J.tokens.length;J.tokens=J.tokens.filter((W)=>W.lastUsed>$);let Q=Y-J.tokens.length;if(Q>0)await this.saveTokens(J),z1.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(mQ);if(await Z.exists()){let J=await Z.text(),X=JSON.parse(J);if(X&&typeof X==="object"&&typeof X.preferences==="object"&&!Array.isArray(X.preferences)){let $=X;return this.preferencesCache=$,z1.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys($.preferences).length}),$}else if(X&&typeof X==="object")return z1.warn("[NotificationStorage] Invalid preferences file format, attempting to recover data"),this.preferencesCache={preferences:X.preferences&&typeof X.preferences==="object"&&!Array.isArray(X.preferences)?X.preferences:{}},await this.savePreferences(this.preferencesCache),this.preferencesCache;else{z1.error("[NotificationStorage] Completely invalid preferences file format, creating backup");let $=`${mQ}.backup.${Date.now()}`;await Bun.write($,J),z1.error("[NotificationStorage] Backup saved to:",$)}}}catch(Z){z1.error("[NotificationStorage] Error loading preferences:",Z);try{let J=Bun.file(mQ);if(await J.exists()){let X=await J.text(),$=`${mQ}.backup.${Date.now()}`;await Bun.write($,X),z1.error("[NotificationStorage] Corrupted file backed up to:",$)}}catch{}}return this.preferencesCache={preferences:{}},this.preferencesCache}async savePreferences(Z){try{await this.ensureDirectory(),await Bun.write(mQ,JSON.stringify(Z,null,2)),this.preferencesCache=Z,z1.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(Z.preferences).length})}catch(J){throw z1.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),z1.info("[NotificationStorage] Created default preferences for device:",{deviceId:Z});return J.preferences[Z]}async updatePreferences(Z,J){let X=await this.loadPreferences(),$=await this.getPreferences(Z);return X.preferences[Z]={...$,...J,deviceId:Z,updatedAt:new Date().toISOString()},await this.savePreferences(X),z1.info("[NotificationStorage] Updated preferences:",{deviceId:Z,updates:J}),X.preferences[Z]}async isNotificationEnabled(Z,J){return(await this.getPreferences(Z))[J]}clearCache(){this.tokensCache=null,this.preferencesCache=null,z1.debug("[NotificationStorage] Cleared cache")}}var F8=new s30;import{Expo as _Z1}from"expo-server-sdk";function OZ1(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 F6=x();class t30{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;getExpo(){if(!this.expo)this.expo=new _Z1;return this.expo}isValidToken(Z){return OZ1(Z)}async sendNotification(Z,J){if(!this.isValidToken(Z))return F6.warn("[ExpoPushClient] Invalid Expo push token:",{token:Z.substring(0,20)+"..."}),null;let X={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([X]))[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 F6.debug("[ExpoPushClient] Sent notification:",{token:Z.substring(0,20)+"...",status:Q?.status}),Q??null}catch($){return F6.error("[ExpoPushClient] Error sending notification:",$),null}}async sendBatchNotifications(Z,J){let X=[];for(let K of Z)if(!this.isValidToken(K))F6.warn("[ExpoPushClient] Skipping invalid token:",{token:K.substring(0,20)+"..."});else X.push(K);if(X.length===0)return F6.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($),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=X[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){F6.error("[ExpoPushClient] Error sending batch chunk:",z)}return F6.info("[ExpoPushClient] Sent batch notifications:",{total:X.length,successful:W.filter((K)=>K.status==="ok").length,failed:W.filter((K)=>K.status==="error").length}),W}async handleTicketError(Z,J){if(F6.warn("[ExpoPushClient] Ticket error:",{message:Z.message,details:Z.details}),Z.details?.error==="DeviceNotRegistered"){F6.info("[ExpoPushClient] Removing invalid token:",{token:J.substring(0,20)+"..."});let $=(await F8.getAllTokens()).find((Y)=>Y.expoPushToken===J);if($)await F8.unregisterToken($.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;F6.debug("[ExpoPushClient] Checking receipts:",{count:J.length});let X=this.getExpo(),$=X.chunkPushNotificationReceiptIds(J);for(let Q of $)try{let W=await X.getPushNotificationReceiptsAsync(Q);for(let[K,z]of Object.entries(W)){let G=this.pendingTickets.get(K),H=z;if(H.status==="ok")F6.debug("[ExpoPushClient] Receipt OK:",{ticketId:K});else if(H.status==="error"){let V=z;if(F6.warn("[ExpoPushClient] Receipt error:",{ticketId:K,message:V.message,details:V.details}),V.details?.error==="DeviceNotRegistered"&&G){let B=(await F8.getAllTokens()).find((U)=>U.expoPushToken===G.token);if(B)F6.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:B.deviceId}),await F8.unregisterToken(B.deviceId)}}this.pendingTickets.delete(K)}}catch(W){F6.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 uQ=new t30;var J1=x(),e30=200,wZ1=900000;class oH{name="Notification Service";running=!1;startedAt;mqttClient=null;claudeAgentService=null;receiptCheckInterval;constructor(){}setMQTTClient(Z){this.mqttClient=Z}setClaudeAgentService(Z){this.claudeAgentService=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,J1.info("[Notification] Service started"),this.mqttClient)this.registerMQTTHandlers();else J1.warn("[Notification] MQTT client not set - handlers will not be registered");this.receiptCheckInterval=setInterval(()=>{uQ.checkReceipts().catch((Z)=>{J1.error("[Notification] Error checking receipts:",Z)})},wZ1),J1.info("[Notification] Ready to send notifications")}catch(Z){throw J1.error("[Notification] Failed to start",Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.receiptCheckInterval)clearInterval(this.receiptCheckInterval);J1.info("[Notification] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("notifications/register/request",this.handleRegisterToken.bind(this)),this.mqttClient.subscribe("notifications/preferences/get/request",this.handleGetPreferences.bind(this)),this.mqttClient.subscribe("notifications/preferences/update/request",this.handleUpdatePreferences.bind(this)),this.mqttClient.subscribe("claude/+/output/+",this.handleClaudeOutput.bind(this)),this.mqttClient.subscribe("claude/+/permission/request/+",this.handlePermissionRequest.bind(this)),J1.info("[Notification] MQTT handlers registered")}async handleRegisterToken(Z,J){try{let X=JSON.parse(J.toString());J1.info("[Notification] Register token request:",{deviceId:X.deviceId,platform:X.platform,hasExpoPushToken:!!X.expoPushToken,hasFcmToken:!!X.fcmToken}),await F8.registerToken(X.deviceId,X.fcmToken,X.expoPushToken,X.platform,X.deviceInfo);let $={requestId:X.requestId,success:!0};await this.mqttClient?.publish("notifications/register/response",JSON.stringify($)),J1.info("[Notification] Token registered successfully:",{deviceId:X.deviceId})}catch(X){J1.error("[Notification] Error registering token:",X);try{let $=J.toString(),Q={requestId:JSON.parse($).requestId,success:!1,error:X instanceof Error?X.message:"Unknown error"};await this.mqttClient?.publish("notifications/register/response",JSON.stringify(Q))}catch{}}}async handleGetPreferences(Z,J){try{let X=JSON.parse(J.toString());J1.debug("[Notification] Get preferences request:",{deviceId:X.deviceId});let $=await F8.getPreferences(X.deviceId),Y={requestId:X.requestId,success:!0,preferences:$};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(Y)),J1.debug("[Notification] Sent preferences:",{deviceId:X.deviceId})}catch(X){J1.error("[Notification] Error getting preferences:",X);try{let Y={requestId:JSON.parse(J.toString()).requestId,success:!1,error:X instanceof Error?X.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(Y))}catch{}}}async handleUpdatePreferences(Z,J){try{let X=JSON.parse(J.toString());J1.info("[Notification] Update preferences request:",{deviceId:X.deviceId,preferences:X.preferences});let $=await F8.updatePreferences(X.deviceId,X.preferences),Y={requestId:X.requestId,success:!0,preferences:$};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(Y)),J1.info("[Notification] Preferences updated:",{deviceId:X.deviceId})}catch(X){J1.error("[Notification] Error updating preferences:",X);try{let Y={requestId:JSON.parse(J.toString()).requestId,success:!1,error:X instanceof Error?X.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(Y))}catch{}}}async handleClaudeOutput(Z,J){try{let X=Z.split("/"),$=X[1],Y=X[3],Q=JSON.parse(J.toString());if(Q.type!=="assistant")return;let W=this.getSessionInfo(Y??"");if(!W){J1.debug("[Notification] Session not found for notification:",{sessionId:Y});return}let K=this.buildNotificationTitle(W),z=this.extractMessageBody(Q);if(!z)return;let G={type:"message",projectId:W.projectPath,sessionId:Y??""};await this.sendToDevicesWithPreference("allMessages",{title:K,body:z,data:G,priority:"high",channelId:"messages"}),J1.debug("[Notification] Sent message notification:",{sessionId:Y,title:K})}catch(X){J1.error("[Notification] Error handling Claude output:",X)}}async handlePermissionRequest(Z,J){try{let X=Z.split("/"),$=X[1],Y=X[4],Q=JSON.parse(J.toString()),W=this.getSessionInfo(Y??"");if(!W){J1.debug("[Notification] Session not found for permission notification:",{sessionId:Y});return}let K=this.buildNotificationTitle(W),z=this.buildPermissionBody(Q),G={type:"permission",projectId:W.projectPath,sessionId:Y??"",requestId:Q.request_id,action:Q.action};await this.sendToDevicesWithPreference("needsAttention",{title:K,body:z,data:G,priority:"high",channelId:"default"}),J1.info("[Notification] Sent permission notification:",{sessionId:Y,action:Q.action})}catch(X){J1.error("[Notification] Error handling permission request:",X)}}getSessionInfo(Z){if(!this.claudeAgentService)return null;let X=this.claudeAgentService.getActiveSessions().find(($)=>$.sessionId===Z);if(!X)return null;return{sessionId:X.sessionId,projectPath:X.projectPath,worktreeBranch:X.worktreeBranch}}buildNotificationTitle(Z){let J=ZQ0.basename(Z.projectPath);if(Z.worktreeBranch){let X=Z.worktreeBranch.replace("session/","");return`${J} (${X})`}return J}extractMessageBody(Z){let J="",X=Z.message;if(X?.content&&Array.isArray(X.content))J=X.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).filter(Boolean).join(`
|
|
2370
|
+
`).map((Y)=>Y.trim()).filter((Y)=>Y&&!Y.includes("HEAD")&&!Y.includes("->")).map((Y)=>Y.replace(/^origin\//,"")),$=await zj(Z);return{branches:X,defaultBranch:$}}catch(J){return L0.error("[GitExecutor] Failed to get remote branches",{error:J,path:Z}),{branches:[],defaultBranch:null}}}import*as R4 from"path";import*as T1 from"fs";import*as Hj from"os";var r0=x();function A$(Z){return R4.normalize(Z).toLowerCase()}var GZ1="worktrees",HZ1="sessions";function Gj(){return R4.join(Hj.homedir(),".ccc",HZ1)}function VZ1(){let Z=new Date,J=Z.getFullYear(),X=String(Z.getMonth()+1).padStart(2,"0"),$=String(Z.getDate()).padStart(2,"0"),Y=String(Z.getHours()).padStart(2,"0"),Q=String(Z.getMinutes()).padStart(2,"0");return`${J}${X}${$}-${Y}${Q}`}class T${worktreeCache=new Map;saveSessionMapping(Z,J){try{let X=Gj();if(!T1.existsSync(X))T1.mkdirSync(X,{recursive:!0});let $=R4.join(X,Z);T1.writeFileSync($,J,"utf-8"),r0.debug("[WorktreeManager] Saved session mapping",{sessionId:Z,worktreePath:J})}catch(X){r0.error("[WorktreeManager] Failed to save session mapping",{error:X,sessionId:Z,worktreePath:J})}}loadSessionMapping(Z){try{let J=R4.join(Gj(),Z);if(T1.existsSync(J)){let X=T1.readFileSync(J,"utf-8").trim();if(T1.existsSync(X))return X;else T1.unlinkSync(J),r0.debug("[WorktreeManager] Removed stale session mapping",{sessionId:Z,worktreePath:X})}}catch(J){r0.error("[WorktreeManager] Failed to load session mapping",{error:J,sessionId:Z})}return null}deleteSessionMapping(Z){try{let J=R4.join(Gj(),Z);if(T1.existsSync(J))T1.unlinkSync(J),r0.debug("[WorktreeManager] Deleted session mapping",{sessionId:Z})}catch(J){r0.error("[WorktreeManager] Failed to delete session mapping",{error:J,sessionId:Z})}}getWorktreesBasePath(Z){let J=R4.basename(Z),X=R4.join(Hj.homedir(),".ccc");return R4.join(X,`${J}-${GZ1}`)}getWorktreePath(Z,J){let X=this.getWorktreesBasePath(Z),$=J.replace(/[^a-zA-Z0-9_-]/g,"_");return R4.join(X,$)}generateBranchName(Z){return`session/${Z.replace(/[^a-zA-Z0-9_-]/g,"_")}`}async getOrCreateForSession(Z,J){r0.debug("[WorktreeManager] getOrCreateForSession",{sessionId:Z,repoPath:J});let X=this.worktreeCache.get(Z);if(X)if(T1.existsSync(X.path))return r0.debug("[WorktreeManager] Returning cached worktree",{sessionId:Z,path:X.path}),{worktree:X,isNew:!1};else this.worktreeCache.delete(Z);let $=this.loadSessionMapping(Z);if($&&T1.existsSync($)){let U=await h5(J);if(U){let D=await fQ(U),_=A$($),O=D.find((w)=>A$(w.path)===_);if(O)return O.sessionId=Z,this.worktreeCache.set(Z,O),r0.debug("[WorktreeManager] Found worktree from session mapping",{sessionId:Z,path:$}),{worktree:O,isNew:!1};else r0.warn("[WorktreeManager] Worktree path exists on disk but not found in git worktree list",{mappedWorktreePath:$})}}if(!await M$(J))throw Error(`Not a git repository: ${J}`);let Q=await h5(J);if(!Q)throw Error(`Could not determine repository root for: ${J}`);let W=await gH(Q,Z);if(W)return W.sessionId=Z,this.worktreeCache.set(Z,W),this.saveSessionMapping(Z,W.path),r0.debug("[WorktreeManager] Found existing worktree (legacy)",{sessionId:Z,path:W.path}),{worktree:W,isNew:!1};let K=this.getWorktreePath(Q,Z);if(T1.existsSync(K)){r0.warn("[WorktreeManager] Worktree path exists but not in git worktree list",{expectedPath:K});let U=await fQ(Q),D=A$(K),_=U.find((O)=>A$(O.path)===D);if(_)return _.sessionId=Z,this.worktreeCache.set(Z,_),{worktree:_,isNew:!1}}let z=VZ1(),G=this.getWorktreesBasePath(Q),H=R4.join(G,z),V=`session/${z}`,F=0;while(T1.existsSync(H)){F++;let U=`${z}-${F}`;H=R4.join(G,U),V=`session/${U}`}if(!T1.existsSync(G))T1.mkdirSync(G,{recursive:!0}),r0.debug("[WorktreeManager] Created worktrees base directory",{basePath:G});let B=await w30(Q,H,V);return B.sessionId=Z,this.saveSessionMapping(Z,H),this.worktreeCache.set(Z,B),r0.debug("[WorktreeManager] Created new worktree",{sessionId:Z,worktreeName:R4.basename(H),path:B.path,branch:B.branch}),{worktree:B,isNew:!0}}async getWorktreeForSession(Z,J){r0.debug("[WorktreeManager] getWorktreeForSession",{sessionId:Z,repoPath:J});let X=this.worktreeCache.get(Z);if(X)if(T1.existsSync(X.path))return X;else this.worktreeCache.delete(Z);let $=await h5(J);if(!$)return null;let Y=await gH($,Z);if(Y)Y.sessionId=Z,this.worktreeCache.set(Z,Y);return Y}async listWorktreesForRepo(Z){r0.debug("[WorktreeManager] listWorktreesForRepo",{repoPath:Z});let J=await h5(Z);if(!J)throw Error(`Could not determine repository root for: ${Z}`);let X=await fQ(J);for(let $ of X)if(!$.isMain)if($.branch?.startsWith("session/"))$.sessionId=$.branch.substring(8);else{let Y=this.getWorktreesBasePath(J);if(A$($.path).startsWith(A$(Y))){let Q=R4.basename($.path);$.sessionId=Q}}for(let $ of X)if($.sessionId)this.worktreeCache.set($.sessionId,$);return X}getActiveWorktreeCount(){return this.worktreeCache.size}clearCache(){this.worktreeCache.clear()}removeFromCache(Z){this.worktreeCache.delete(Z)}updateSessionId(Z,J,X){try{this.deleteSessionMapping(J),this.saveSessionMapping(X,Z);let $=this.worktreeCache.get(J);if($)this.worktreeCache.delete(J),$.sessionId=X,this.worktreeCache.set(X,$);r0.debug("[WorktreeManager] Updated session ID mapping",{worktreePath:Z,oldSessionId:J,newSessionId:X})}catch($){r0.error("[WorktreeManager] Failed to update session ID",{error:$,worktreePath:Z,oldSessionId:J,newSessionId:X})}}async renameWorktreeForSession(Z,J,X){r0.debug("[WorktreeManager] Renaming worktree for session",{oldSessionId:Z,newSessionId:J,repoPath:X});try{let $=await h5(X);if(!$)return r0.error("[WorktreeManager] Could not determine repo root for rename"),null;let Y=this.worktreeCache.get(Z);if(!Y){if(r0.warn("[WorktreeManager] No cached worktree found for old session ID",{oldSessionId:Z}),!await gH($,Z))return r0.error("[WorktreeManager] Could not find worktree for old session ID"),null}let Q=this.getWorktreePath($,Z),W=this.getWorktreePath($,J),K=this.generateBranchName(Z),z=this.generateBranchName(J);if(!T1.existsSync(Q))return r0.warn("[WorktreeManager] Old worktree path does not exist",{oldPath:Q}),null;if(T1.existsSync(W)){r0.warn("[WorktreeManager] New worktree path already exists",{newPath:W});let H={path:W,branch:z,head:Y?.head||"",sessionId:J,isMain:!1};return this.worktreeCache.delete(Z),this.worktreeCache.set(J,H),H}await P30($,Q,W),r0.debug("[WorktreeManager] Moved worktree",{from:Q,to:W}),await R30(W,K,z),r0.debug("[WorktreeManager] Renamed branch",{from:K,to:z}),this.worktreeCache.delete(Z);let G={path:W,branch:z,head:Y?.head||"",sessionId:J,isMain:!1,createdAt:Y?.createdAt};return this.worktreeCache.set(J,G),r0.debug("[WorktreeManager] Successfully renamed worktree",{oldSessionId:Z,newSessionId:J,oldPath:Q,newPath:W,oldBranch:K,newBranch:z}),G}catch($){return r0.error("[WorktreeManager] Failed to rename worktree",{error:$,oldSessionId:Z,newSessionId:J}),null}}}import*as Vj from"path";import*as m30 from"os";var V8=x(),mH=Vj.join(m30.homedir(),".ccc"),g30=Vj.join(mH,"pending-permissions.json");class d30{cache=null;async ensureDirectory(){try{let Z=await import("fs");if(!Z.existsSync(mH))Z.mkdirSync(mH,{recursive:!0}),V8.debug("[PendingPermissions] Created .ccc directory:",mH)}catch(Z){throw V8.error("[PendingPermissions] Error ensuring directory:",Z),Z}}async load(){if(this.cache)return this.cache;try{let Z=Bun.file(g30);if(await Z.exists()){let J=await Z.text();return this.cache=JSON.parse(J),V8.debug("[PendingPermissions] Loaded permissions:",{count:this.cache?.permissions?.length||0}),this.cache}}catch(Z){V8.warn("[PendingPermissions] Error loading, starting fresh:",Z)}return this.cache={permissions:[],lastUpdated:new Date().toISOString()},this.cache}async save(Z){try{await this.ensureDirectory(),Z.lastUpdated=new Date().toISOString(),await Bun.write(g30,JSON.stringify(Z,null,2)),this.cache=Z,V8.debug("[PendingPermissions] Saved permissions:",{count:Z.permissions.length})}catch(J){throw V8.error("[PendingPermissions] Error saving:",J),J}}async addPermission(Z){let J=await this.load(),X=J.permissions.findIndex(($)=>$.requestId===Z.requestId);if(X>=0)J.permissions[X]=Z,V8.debug("[PendingPermissions] Updated existing permission:",{requestId:Z.requestId,sessionId:Z.sessionId});else J.permissions.push(Z),V8.debug("[PendingPermissions] Added new pending permission:",{requestId:Z.requestId,sessionId:Z.sessionId,action:Z.action});await this.save(J)}async removePermission(Z){let J=await this.load(),X=J.permissions.length;if(J.permissions=J.permissions.filter(($)=>$.requestId!==Z),J.permissions.length<X)return await this.save(J),V8.debug("[PendingPermissions] Removed permission:",{requestId:Z}),!0;return!1}async removePermissionsForSession(Z){let J=await this.load(),X=J.permissions.length;J.permissions=J.permissions.filter((Y)=>Y.sessionId!==Z);let $=X-J.permissions.length;if($>0)await this.save(J),V8.debug("[PendingPermissions] Removed permissions for session:",{sessionId:Z,removedCount:$});return $}async getPermissionsForSession(Z){return(await this.load()).permissions.filter((X)=>X.sessionId===Z)}async getPermissionsForProject(Z){return(await this.load()).permissions.filter((X)=>X.projectPath===Z)}async getAllPermissions(){return(await this.load()).permissions}async getPermission(Z){return(await this.load()).permissions.find((X)=>X.requestId===Z)}async clearAll(){this.cache={permissions:[],lastUpdated:new Date().toISOString()},await this.save(this.cache),V8.debug("[PendingPermissions] Cleared all pending permissions")}clearCache(){this.cache=null,V8.debug("[PendingPermissions] Cleared cache")}}var d7=new d30;var m=x();class uH{name="Claude Agent Service";running=!1;startedAt;mqttClient=null;sessionsService=null;processManager;worktreeManager;config;totalSessionsCreated=0;totalMessagesProcessed=0;pendingPermissions=new Map;cleanupInterval;constructor(Z){this.config=Z,this.worktreeManager=new T$,this.processManager=new hH(Z,{onSessionInitialized:this.handleSessionInitialized.bind(this),onTitleGenerated:this.handleTitleGenerated.bind(this),onAssistantMessage:this.handleAssistantMessage.bind(this),onPermissionRequest: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(!$)return m.debug("[ClaudeAgent] Git worktrees disabled, using project path",{projectId:Z,directoryPath:J}),{path:J,isWorktree:!1};if(!await M$(J))return m.debug("[ClaudeAgent] Not a git repo, using project path",{projectId:Z,directoryPath:J}),{path:J,isWorktree:!1};let Q=await h5(J);if(!Q)return m.warn("[ClaudeAgent] Could not determine repo root, using project path",{directoryPath:J}),{path:J,isWorktree:!1};m.debug("[ClaudeAgent] Git repo detected, creating worktree",{projectId:Z,sessionId:X,repoRoot:Q});let{worktree:W,isNew:K}=await this.worktreeManager.getOrCreateForSession(X,Q);return m.debug("[ClaudeAgent] Worktree ready",{sessionId:X,worktreePath:W.path,branch:W.branch,isNew:K}),{path:W.path,isWorktree:!0,branch:W.branch}}catch(Y){return m.error("[ClaudeAgent] Worktree creation failed, falling back to project path",{projectId:Z,sessionId:X,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,m.info("[ClaudeAgent] Service started"),this.mqttClient)this.registerMQTTHandlers();else m.warn("[ClaudeAgent] MQTT client not set - handlers will not be registered");this.cleanupInterval=setInterval(()=>{this.processManager.cleanupInactiveSessions()},300000),m.info("[ClaudeAgent] Ready to handle sessions",{maxConcurrentSessions:this.config.maxConcurrentSessions,sessionTimeoutMs:this.config.sessionTimeoutMs})}catch(Z){throw m.error("[ClaudeAgent] Failed to start",Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.cleanupInterval)clearInterval(this.cleanupInterval);this.processManager.stopAll(),m.info("[ClaudeAgent] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("claude/+/session/start",(Z,J)=>{let X=this.extractUserIdFromTopic(Z);this.handleSessionStart(X,Z,J)}),this.mqttClient.subscribe("claude/+/input/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromInputTopic(Z);this.handleUserInput(X,$,Z,J)}),this.mqttClient.subscribe("claude/+/permission/response/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromPermissionTopic(Z);this.handlePermissionResponse(X,$,Z,J)}),this.mqttClient.subscribe("claude/+/session/stop/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromStopTopic(Z);this.handleSessionStop(X,$)}),this.mqttClient.subscribe("permissions/pending/request",(Z,J)=>{this.handlePendingPermissionsRequest(Z,J)}),this.mqttClient.subscribe("settings/claude/request",(Z,J)=>{this.handleClaudeSettingsRequest(Z,J)}),this.mqttClient.subscribe("settings/claude/update",(Z,J)=>{this.handleClaudeSettingsUpdate(Z,J)}),this.mqttClient.subscribe("claude/+/checkpoints/list/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromStopTopic(Z);this.handleCheckpointListRequest(X,$,J)}),this.mqttClient.subscribe("claude/+/session/rewind/+",(Z,J)=>{let{userId:X,sessionId:$}=this.extractIdsFromStopTopic(Z);this.handleRewindRequest(X,$,J)}),m.info("[ClaudeAgent] MQTT handlers registered")}async handleSessionStart(Z,J,X){try{let $=JSON.parse(X.toString());m.info("[ClaudeAgent] Session start request:",{userId:Z,tempId:$.tempId,projectId:$.projectId,directoryPath:$.directoryPath,permissionMode:$.permissionMode,selectedModel:$.selectedModel,hasAttachments:!!$.attachments,attachmentCount:$.attachments?.length||0,gitWorktreesEnabled:$.gitWorktreesEnabled});let{path:Y,isWorktree:Q,branch:W}=await this.determineWorkingDirectory($.projectId,$.directoryPath,$.tempId,$.gitWorktreesEnabled??!1),K=await this.processManager.spawnSession($.tempId,Z,$.projectId,Y,$.initialMessage||"",void 0,$.permissionMode,$.selectedModel,$.attachments);if(Q)K.directoryPath=$.directoryPath,K.worktreePath=Y,K.worktreeBranch=W;this.totalSessionsCreated++,m.info("[ClaudeAgent] Session spawned successfully:",{userId:Z,tempId:$.tempId,projectId:$.projectId,workingPath:Y,isWorktree:Q})}catch($){m.error("[ClaudeAgent] Error starting session:",{userId:Z,error:$ instanceof Error?$.message:"Unknown error"}),this.publishStatus(Z,"temp_error",{type:"error",error:$ instanceof Error?$.message:"Failed to start session",timestamp:Date.now()})}}async handleUserInput(Z,J,X,$){try{let Y=JSON.parse($.toString());if(!Y.message&&(!Y.attachments||Y.attachments.length===0)){m.warn("[ClaudeAgent] Received request without message or attachments:",{userId:Z,sessionId:Y.sessionId,hasAttachments:!!Y.attachments});return}m.debug("[ClaudeAgent] User input:",{userId:Z,sessionId:Y.sessionId,messageLength:Y.message?.length||0,permissionMode:Y.permissionMode,selectedModel:Y.selectedModel,hasAttachments:!!Y.attachments,attachmentCount:Y.attachments?.length||0,allSessions:this.processManager.getAllSessions().map((z)=>({tempId:z.tempId,sessionId:z.sessionId,status:z.status}))});let Q=this.processManager.getSession(Y.sessionId);if(!Q){m.warn("[ClaudeAgent] Session not found, creating new session:",{userId:Z,requestedSessionId:Y.sessionId,projectId:Y.projectId,availableSessions:this.processManager.getAllSessions().map((G)=>G.sessionId||G.tempId)});let z=Y.sessionId&&!Y.sessionId.startsWith("temp_")&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(Y.sessionId);try{let{path:G,isWorktree:H,branch:V}=await this.determineWorkingDirectory(Y.projectId,Y.directoryPath,Y.sessionId,Y.gitWorktreesEnabled??!1);if(Q=await this.processManager.spawnSession(Y.sessionId,Z,Y.projectId,G,Y.message||"",z?Y.sessionId:void 0,Y.permissionMode,Y.selectedModel,Y.attachments),H)Q.directoryPath=Y.directoryPath,Q.worktreePath=G,Q.worktreeBranch=V;this.totalSessionsCreated++,m.info(`[ClaudeAgent] Session ${z?"resumed":"created"} successfully:`,{userId:Z,sessionId:Y.sessionId,isResume:z,workingPath:G,isWorktree:H}),this.totalMessagesProcessed++;return}catch(G){m.error("[ClaudeAgent] Failed to create session:",{userId:Z,sessionId:Y.sessionId,error:G instanceof Error?G.message:"Unknown error"}),this.publishStatus(Z,Y.sessionId,{type:"error",error:"Failed to create session",timestamp:Date.now()});return}}let W=Q.permissionMode||"default",K=Y.permissionMode||"default";if(K!==W&&Q.sessionId)if(m.info("[ClaudeAgent] Permission mode changed, respawning session:",{userId:Z,sessionId:Q.sessionId,currentMode:W,requestedMode:K}),await this.processManager.respawnWithPermissionMode(Q.sessionId,K,Y.message||"proceed with implementation")){this.publishStatus(Z,Q.sessionId,{type:"session_restarted",permissionMode:K,timestamp:Date.now()}),this.totalMessagesProcessed++;return}else m.error("[ClaudeAgent] Failed to respawn session with new permission mode");this.processManager.sendUserMessage(Q,Y.message||"",Y.attachments),this.totalMessagesProcessed++}catch(Y){m.error("[ClaudeAgent] Error handling user input:",{userId:Z,sessionId:J,error:Y instanceof Error?Y.message:"Unknown error"})}}async handlePermissionResponse(Z,J,X,$){try{let Y=JSON.parse($.toString());m.debug("[ClaudeAgent] Permission response:",{userId:Z,sessionId:J,requestId:Y.requestId,approved:Y.approved,hasAnswers:!!Y.answers,addToAllowedTools:Y.addToAllowedTools,toolPattern:Y.toolPattern,permissionMode:Y.permissionMode,hardDeny:Y.hardDeny,hasDenyMessage:!!Y.denyMessage});let Q=this.pendingPermissions.get(Y.requestId);if(!Q)m.warn(`[ClaudeAgent] No pending permission found for request_id: ${Y.requestId}`);if(Y.approved&&Y.addToAllowedTools){let K=this.processManager.getSession(J);if(K){let z=Y.toolPattern||(Q?this.generateToolPattern(Q.action,Q.params):null);if(z)await this.addToAllowedTools(K.directoryPath,z),m.debug("[ClaudeAgent] Added tool pattern to settings.local.json:",{toolPattern:z,projectPath:K.directoryPath})}}let W=this.processManager.getSession(J);if(Y.permissionMode&&W?.sessionId){if(m.debug("[ClaudeAgent] Permission mode change requested, will respawn session:",{sessionId:W.sessionId,newPermissionMode:Y.permissionMode}),this.processManager.sendPermissionResponse(J,{request_id:Y.requestId,behavior:"allow",updatedInput:Q?.params,message:"Permission mode is changing. Stopping current execution for session respawn."}),await new Promise((z)=>setTimeout(z,200)),await this.processManager.respawnWithPermissionMode(W.sessionId,Y.permissionMode,"proceed with implementation"))this.publishStatus(W.userId,W.sessionId,{type:"session_restarted",permissionMode:Y.permissionMode,timestamp:Date.now()});else this.publishStatus(W.userId,W.sessionId,{type:"error",error:"Failed to respawn session with new permission mode",timestamp:Date.now()});if(Q)this.pendingPermissions.delete(Y.requestId);d7.removePermission(Y.requestId).catch((z)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",z)});return}if(Y.approved&&Y.answers&&Object.keys(Y.answers).length>0){let K={...Q?.params,answers:Y.answers};m.info("[ClaudeAgent] Sending AskUserQuestion response:",{requestId:Y.requestId,answerCount:Object.keys(Y.answers).length}),this.processManager.sendPermissionResponse(J,{request_id:Y.requestId,behavior:"allow",updatedInput:K})}else if(Y.approved)this.processManager.sendPermissionResponse(J,{request_id:Y.requestId,behavior:"allow",updatedInput:Q?Q.params:void 0});else{let K=Y.denyMessage||"Permission denied by user",z=Y.hardDeny!==!1;if(m.info("[ClaudeAgent] Sending deny response:",{requestId:Y.requestId,hardDeny:z,hasDenyMessage:!!Y.denyMessage}),this.processManager.sendPermissionResponse(J,{request_id:Y.requestId,behavior:"deny",message:K,hardDeny:z}),z)m.info("[ClaudeAgent] Hard deny - stopping session:",{sessionId:J}),setTimeout(()=>{this.processManager.stopSession(J),this.publishStatus(Z,J,{type:"session_stopped",reason:"permission_denied",message:K,timestamp:Date.now()})},100)}if(Q)this.pendingPermissions.delete(Y.requestId);d7.removePermission(Y.requestId).catch((K)=>{m.error("[ClaudeAgent] Failed to remove pending permission from storage:",K)})}catch(Y){m.error("[ClaudeAgent] Error handling permission response:",{userId:Z,sessionId:J,error:Y instanceof Error?Y.message:"Unknown error"})}}handleSessionStop(Z,J){m.info("[ClaudeAgent] Session stop request:",{userId:Z,sessionId:J}),this.processManager.stopSession(J)}async handlePendingPermissionsRequest(Z,J){try{let X=JSON.parse(J.toString()),{clientId:$,sessionId:Y,projectPath:Q}=X;if(!$){m.warn("[ClaudeAgent] Pending permissions request missing clientId");return}m.debug("[ClaudeAgent] Pending permissions request:",{clientId:$,sessionId:Y,projectPath:Q});let W;if(Y)W=await d7.getPermissionsForSession(Y);else if(Q)W=await d7.getPermissionsForProject(Q);else W=await d7.getAllPermissions();let K=this.processManager.getAllSessions(),z=new Set(K.filter((F)=>F.status==="waiting_permission"&&F.sessionId).map((F)=>F.sessionId)),G=W.filter((F)=>z.has(F.sessionId)),H=`permissions/pending/${$}/response`,V={permissions:G,timestamp:Date.now()};await this.mqttClient?.publish(H,JSON.stringify(V)),m.debug("[ClaudeAgent] Sent pending permissions response:",{clientId:$,count:G.length,totalStored:W.length})}catch(X){m.error("[ClaudeAgent] Error handling pending permissions request:",X)}}async handleClaudeSettingsRequest(Z,J){try{let X=JSON.parse(J.toString()),{clientId:$}=X;if(!$){m.warn("[ClaudeAgent] Claude settings request missing clientId");return}m.debug("[ClaudeAgent] Claude settings request:",{clientId:$});let Y=bQ.join(i30.homedir(),".claude","settings.json"),Q={};try{let z=Bun.file(Y);if(await z.exists())Q=JSON.parse(await z.text())}catch(z){m.warn("[ClaudeAgent] Could not read Claude settings file:",z)}let W=`settings/claude/${$}/response`,K={success:!0,settings:Q,timestamp:Date.now()};await this.mqttClient?.publish(W,JSON.stringify(K)),m.debug("[ClaudeAgent] Sent Claude settings response:",{clientId:$})}catch(X){m.error("[ClaudeAgent] Error handling Claude settings request:",X)}}async handleClaudeSettingsUpdate(Z,J){try{let X=JSON.parse(J.toString()),{clientId:$,settings:Y}=X;if(!$||!Y||typeof Y!=="object"){m.warn("[ClaudeAgent] Claude settings update missing clientId or settings");return}m.debug("[ClaudeAgent] Claude settings update:",{clientId:$,updates:Y});let Q=bQ.join(i30.homedir(),".claude"),W=bQ.join(Q,"settings.json");try{if(!dH.existsSync(Q))dH.mkdirSync(Q,{recursive:!0})}catch(H){}let K={};try{let H=Bun.file(W);if(await H.exists())K=JSON.parse(await H.text())}catch(H){m.warn("[ClaudeAgent] Could not read existing Claude settings, starting fresh")}for(let[H,V]of Object.entries(Y))K[H]=V;await Bun.write(W,JSON.stringify(K,null,2));let z=`settings/claude/${$}/response`,G={success:!0,timestamp:Date.now()};await this.mqttClient?.publish(z,JSON.stringify(G)),m.debug("[ClaudeAgent] Updated Claude settings:",{clientId:$,updates:Y})}catch(X){m.error("[ClaudeAgent] Error handling Claude settings update:",X);try{let Y=`settings/claude/${JSON.parse(J.toString()).clientId}/response`,Q={success:!1,error:X instanceof Error?X.message:"Unknown error",timestamp:Date.now()};await this.mqttClient?.publish(Y,JSON.stringify(Q))}catch{}}}async handleCheckpointListRequest(Z,J,X){try{let $=JSON.parse(X.toString()),Y=$.limit||5;m.debug("[ClaudeAgent] Checkpoint list request:",{userId:Z,sessionId:J,limit:Y});let Q=$?.directoryPath,{parseSessionCheckpoints:W}=await Promise.resolve().then(() => (p30(),l30)),K=await W(J,Q,Y),z=K.some((H)=>H.hasFileChanges),G=`claude/${Z}/checkpoints/response/${J}`;await this.mqttClient?.publish(G,JSON.stringify({sessionId:J,checkpoints:K,hasAnyFileChanges:z})),m.debug("[ClaudeAgent] Checkpoint list response:",{sessionId:J,checkpointCount:K.length,hasAnyFileChanges:z})}catch($){m.error("[ClaudeAgent] Checkpoint list error:",$);let Y=`claude/${Z}/checkpoints/response/${J}`;await this.mqttClient?.publish(Y,JSON.stringify({sessionId:J,checkpoints:[],hasAnyFileChanges:!1,error:$ instanceof Error?$.message:"Unknown error"}))}}async handleRewindRequest(Z,J,X){try{let $=JSON.parse(X.toString()),{checkpointUuid:Y,mode:Q,directoryPath:W}=$;m.info("[ClaudeAgent] Rewind request:",{userId:Z,sessionId:J,checkpointUuid:Y,mode:Q,directoryPath:W});let K=this.processManager.getSession(J),z=W||K?.worktreePath||K?.directoryPath||process.cwd();if(K)this.processManager.stopSession(J),await new Promise((B)=>setTimeout(B,300));let G=!0,H,V;switch(Q){case"code_only":{let B=await this.processManager.executeFileRewind(J,Y,z);G=B.success,H=B.error;break}case"conversation_only":{let B=await this.processManager.executeConversationFork(J,z,Y);G=B.success,H=B.error,V=B.newSessionId;break}case"both":{let B=await this.processManager.executeFullRewind(J,Y,z);G=B.success,H=B.error,V=B.newSessionId;break}}let F=`claude/${Z}/rewind/response/${J}`;if(G)await this.mqttClient?.publish(F,JSON.stringify({type:"rewind_complete",sessionId:J,checkpointUuid:Y,mode:Q,newSessionId:V})),m.info("[ClaudeAgent] Rewind complete:",{sessionId:J,checkpointUuid:Y,mode:Q,newSessionId:V});else await this.mqttClient?.publish(F,JSON.stringify({type:"rewind_failed",sessionId:J,checkpointUuid:Y,error:H||"Unknown error"})),m.error("[ClaudeAgent] Rewind failed:",{sessionId:J,checkpointUuid:Y,error:H})}catch($){m.error("[ClaudeAgent] Rewind error:",$);let Y=`claude/${Z}/rewind/response/${J}`;await this.mqttClient?.publish(Y,JSON.stringify({type:"rewind_failed",sessionId:J,checkpointUuid:"",error:$ instanceof Error?$.message:"Unknown error"}))}}handleSessionInitialized(Z,J){if(m.debug("[ClaudeAgent] Session initialized callback:",{tempId:Z.tempId,sessionId:Z.sessionId,model:Z.model}),Z.worktreePath&&Z.tempId&&Z.sessionId)this.worktreeManager.updateSessionId(Z.worktreePath,Z.tempId,Z.sessionId);let X=J.slash_commands||[],$=J.agents||[],Y=J.skills||[];if(m.debug("[ClaudeAgent] Available commands from init:",{slashCommands:X.length,agents:$.length,skills:Y.length}),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:X,agents:$,skills:Y,timestamp:Date.now()}),this.sessionsService){let Q=Z.worktreePath||Z.directoryPath;this.sessionsService.notifySessionCreated(Z.directoryPath,Q).catch((W)=>{m.warn("[ClaudeAgent] Failed to notify sessions service about new session",{error:W})})}}handleTitleGenerated(Z,J){m.debug("[ClaudeAgent] Title generated callback:",{sessionId:Z.sessionId,title:J}),this.publishStatus(Z.userId,Z.sessionId,{type:"title_generated",title:J,timestamp:Date.now()})}handleAssistantMessage(Z,J){if(this.totalMessagesProcessed++,Z.sessionId)this.publishOutput(Z.userId,Z.sessionId,J)}handlePermissionRequest(Z,J){if(m.debug("[ClaudeAgent] Permission request callback:",{sessionId:Z.sessionId,requestId:J.request_id,action:J.action}),Z.sessionId)this.publishPermissionRequest(Z,J)}handleSessionError(Z,J){m.error("[ClaudeAgent] Session error callback:",{sessionId:Z.sessionId,tempId:Z.tempId,error:J}),this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"error",error:J,timestamp:Date.now()})}handleSessionStopped(Z,J){if(m.debug("[ClaudeAgent] Session stopped callback:",{sessionId:Z.sessionId,tempId:Z.tempId,reason:J}),this.publishStatus(Z.userId,Z.sessionId||Z.tempId,{type:"session_stopped",reason:J,timestamp:Date.now()}),this.sessionsService)this.sessionsService.notifySessionStopped()}handleProcessingStarted(Z){if(m.debug("[ClaudeAgent] Processing started:",{sessionId:Z.sessionId,tempId:Z.tempId}),Z.sessionId)this.publishStatus(Z.userId,Z.sessionId,{type:"session_processing",sessionId:Z.sessionId,timestamp:Date.now()})}handleProcessingComplete(Z){if(m.debug("[ClaudeAgent] Processing complete:",{sessionId:Z.sessionId,tempId:Z.tempId}),Z.sessionId)this.publishStatus(Z.userId,Z.sessionId,{type:"session_idle",sessionId:Z.sessionId,timestamp:Date.now()})}handleContextUpdate(Z,J){if(m.debug(`[ClaudeAgent] Context update for session ${Z.sessionId}:`,{total:J.total,percentage:J.percentage,inputTokens:J.inputTokens,cacheCreation:J.cacheCreation,cacheRead:J.cacheRead,breakdown:{systemPrompt:J.systemPrompt,tools:J.tools,messages:J.messages,remaining:J.remaining}}),Z.sessionId)this.publishContextUpdate(Z.userId,Z.sessionId,J);else m.warn("[ClaudeAgent] Cannot publish context update - no sessionId yet")}publishStatus(Z,J,X){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish status - MQTT client not available");return}let $=`claude/${Z}/status/${J}`,Y=JSON.stringify(X);this.mqttClient.publish($,Y).catch((Q)=>{m.error(`[ClaudeAgent] Failed to publish status to ${$}`,{error:Q.message})})}publishOutput(Z,J,X){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish output - MQTT client not available");return}let $=`claude/${Z}/output/${J}`,Y=JSON.stringify(X);this.mqttClient.publish($,Y).catch((Q)=>{m.error(`[ClaudeAgent] Failed to publish output to ${$}`,{error:Q.message})})}publishContextUpdate(Z,J,X){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish context update - MQTT client not available");return}let $=`claude/${Z}/context/${J}`,Y=JSON.stringify(X);this.mqttClient.publish($,Y).catch((Q)=>{m.error(`[ClaudeAgent] Failed to publish context to ${$}`,{error:Q.message})})}publishPermissionRequest(Z,J){if(!this.mqttClient){m.warn("[ClaudeAgent] Cannot publish permission request - MQTT client not available");return}let{userId:X,sessionId:$}=Z;m.debug("[ClaudeAgent] Raw permission request structure:",{fullRequest:JSON.stringify(J)});let Y=J,Q=Y.request||{},W=Q.tool_name||Y.tool_name||Y.action||"unknown_tool",K=Q.input||Y.tool_input||Y.params||{},z=Q.permission_suggestions||[],G=Q.decision_reason||"",H=Q.blocked_path||"";this.pendingPermissions.set(Y.request_id,{requestId:Y.request_id,action:W,params:K}),d7.addPermission({requestId:Y.request_id,sessionId:$,projectPath:Z.directoryPath,action:W,params:K,permissionSuggestions:z.length>0?z:void 0,decisionReason:G||void 0,blockedPath:H||void 0,createdAt:new Date().toISOString()}).catch((U)=>{m.error("[ClaudeAgent] Failed to persist pending permission:",U)});let V={request_id:Y.request_id,action:W,params:K,permission_suggestions:z,decision_reason:G,blocked_path:H},F=`claude/${X}/permission/request/${$}`,B=JSON.stringify(V);m.debug("[ClaudeAgent] Publishing transformed permission request:",{topic:F,request_id:V.request_id,action:V.action}),this.mqttClient.publish(F,B).catch((U)=>{m.error(`[ClaudeAgent] Failed to publish permission request to ${F}`,{error:U.message})})}extractUserIdFromTopic(Z){return Z.split("/")[1]||""}extractIdsFromInputTopic(Z){let J=Z.split("/");return{userId:J[1]||"",sessionId:J[3]||""}}extractIdsFromPermissionTopic(Z){let J=Z.split("/");return{userId:J[1]||"",sessionId:J[4]||""}}extractIdsFromStopTopic(Z){let J=Z.split("/");return{userId:J[1]||"",sessionId:J[4]||""}}generateToolPattern(Z,J){switch(Z){case"Bash":case"bash":case"execute_command":return`Bash(${J.command})`;case"Read":case"read":case"read_file":return`Read(${J.file_path})`;case"Write":case"write":case"write_file":return`Write(${J.file_path})`;case"Edit":case"edit":return`Edit(${J.file_path})`;default:return Z}}async addToAllowedTools(Z,J){try{let X=bQ.join(Z,".claude"),$=bQ.join(X,"settings.local.json");if(!dH.existsSync(X))dH.mkdirSync(X,{recursive:!0});let Y={},Q=Bun.file($);if(await Q.exists())try{let W=await Q.text();Y=JSON.parse(W)}catch{Y={}}if(Y.permissions=Y.permissions||{},Y.permissions.allow=Y.permissions.allow||[],!Y.permissions.allow.includes(J))Y.permissions.allow.push(J);await Bun.write($,JSON.stringify(Y,null,2)),m.debug("[ClaudeAgent] Updated settings.local.json with allowed tool:",{settingsPath:$,toolPattern:J,totalAllowed:Y.permissions.allow.length})}catch(X){m.error("[ClaudeAgent] Failed to update settings.local.json:",{projectPath:Z,toolPattern:J,error:X instanceof Error?X.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,activeSessions:this.processManager.getSessionCount(),totalSessionsCreated:this.totalSessionsCreated,totalMessagesProcessed:this.totalMessagesProcessed}}getActiveSessions(){return this.processManager.getAllSessions().filter((Z)=>Z.sessionId).map((Z)=>({sessionId:Z.sessionId,projectPath:Z.directoryPath,status:Z.status,worktreePath:Z.worktreePath,worktreeBranch:Z.worktreeBranch}))}}import*as K1 from"fs/promises";import*as Fj from"fs";import*as u1 from"path";import*as u7 from"fs/promises";var q$=x(),n30=10485760;async function W1(Z,J={}){let{maxSize:X=n30,encoding:$="utf-8",logWarnings:Y=!0}=J;try{let Q=await u7.stat(Z);if(!Q.isFile()){if(Y)q$.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Q.size>X){if(Y)q$.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Q.size,maxSize:X});return null}return await u7.readFile(Z,$)}catch(Q){if(Q.code!=="ENOENT"&&Y)q$.debug("[SafeFS] Error reading file",{filePath:Z,error:Q});return null}}async function o30(Z,J={}){let{maxSize:X=n30,logWarnings:$=!0}=J;try{let Y=await u7.stat(Z);if(!Y.isFile()){if($)q$.debug("[SafeFS] Path is not a file",{filePath:Z});return null}if(Y.size>X){if($)q$.warn("[SafeFS] File too large, skipping",{filePath:Z,size:Y.size,maxSize:X});return null}return await u7.readFile(Z)}catch(Y){if(Y.code!=="ENOENT"&&$)q$.debug("[SafeFS] Error reading file",{filePath:Z,error:Y});return null}}async function c4(Z){try{return(await u7.stat(Z)).isDirectory()}catch{return!1}}async function E9(Z){try{return await u7.stat(Z)}catch{return null}}var I9=x();class cH{validatePath(Z,J){try{let X=u1.resolve(Z),$=u1.resolve(X,J);if(!($===X||$.startsWith(X+u1.sep)))return{valid:!1,fullPath:"",error:"Path traversal detected: path escapes project directory"};try{let Q=Fj.realpathSync($),W=Fj.realpathSync(X);if(!(Q===W||Q.startsWith(W+u1.sep)))return{valid:!1,fullPath:"",error:"Symlink escape detected: symlink points outside project directory"}}catch{}return{valid:!0,fullPath:$}}catch(X){return{valid:!1,fullPath:"",error:`Path validation error: ${X instanceof Error?X.message:"Unknown error"}`}}}async listDirectory(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{entries:[],error:X.error};try{if(!(await K1.stat(X.fullPath)).isDirectory())return{entries:[],error:"Path is not a directory"};let Y=await K1.readdir(X.fullPath,{withFileTypes:!0}),Q=await Promise.all(Y.map(async(W)=>{let K=u1.join(X.fullPath,W.name);try{let z=await K1.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($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] listDirectory error",{error:Y,path:X.fullPath}),{entries:[],error:`Failed to list directory: ${Y}`}}}async readFile(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{content:"",size:0,error:X.error};try{let $=await E9(X.fullPath);if(!$||!$.isFile())return{content:"",size:0,error:"Path is not a file"};let Y=await W1(X.fullPath);if(Y===null)return{content:"",size:0,error:"Failed to read file"};return{content:Y,size:Number($.size)}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] readFile error",{error:Y,path:X.fullPath}),{content:"",size:0,error:`Failed to read file: ${Y}`}}}async writeFile(Z,J,X){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{let Y=u1.dirname($.fullPath);return await K1.mkdir(Y,{recursive:!0}),await K1.writeFile($.fullPath,X,"utf-8"),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return I9.error("[FileManager] writeFile error",{error:Q,path:$.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}async createFile(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{try{return await K1.access(X.fullPath),{success:!1,error:"File already exists"}}catch{}let $=u1.basename(J);if(!this.isValidFilename($))return{success:!1,error:"Invalid filename"};let Y=u1.dirname(X.fullPath);return await K1.mkdir(Y,{recursive:!0}),await K1.writeFile(X.fullPath,"","utf-8"),{success:!0}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] createFile error",{error:Y,path:X.fullPath}),{success:!1,error:`Failed to create file: ${Y}`}}}async createDirectory(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{let $=u1.basename(J);if(!this.isValidFilename($))return{success:!1,error:"Invalid directory name"};try{if((await K1.stat(X.fullPath)).isDirectory())return{success:!1,error:"Directory already exists"};return{success:!1,error:"A file with this name already exists"}}catch{}return await K1.mkdir(X.fullPath,{recursive:!0}),{success:!0}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] createDirectory error",{error:Y,path:X.fullPath}),{success:!1,error:`Failed to create directory: ${Y}`}}}async deleteFile(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};try{if(!(await K1.stat(X.fullPath)).isFile())return{success:!1,error:"Path is not a file"};return await K1.unlink(X.fullPath),{success:!0}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] deleteFile error",{error:Y,path:X.fullPath}),{success:!1,error:`Failed to delete file: ${Y}`}}}async deleteDirectory(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{success:!1,error:X.error};if(X.fullPath===u1.resolve(Z))return{success:!1,error:"Cannot delete project root directory"};try{if(!(await K1.stat(X.fullPath)).isDirectory())return{success:!1,error:"Path is not a directory"};return await K1.rm(X.fullPath,{recursive:!0,force:!0}),{success:!0}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] deleteDirectory error",{error:Y,path:X.fullPath}),{success:!1,error:`Failed to delete directory: ${Y}`}}}async pathExists(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return!1;try{return await K1.access(X.fullPath),!0}catch{return!1}}async getStats(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return null;try{let $=await K1.stat(X.fullPath);return{isFile:$.isFile(),isDirectory:$.isDirectory(),size:$.size,modified:$.mtime.toISOString()}}catch{return null}}async readFileBinary(Z,J){let X=this.validatePath(Z,J);if(!X.valid)return{content:Buffer.alloc(0),size:0,mimeType:"",error:X.error};try{let $=await E9(X.fullPath);if(!$||!$.isFile())return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Path is not a file"};let Y=52428800;if($.size>Y)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"File exceeds maximum size of 50MB"};let Q=await o30(X.fullPath,{maxSize:Y});if(Q===null)return{content:Buffer.alloc(0),size:0,mimeType:"",error:"Failed to read file"};let W=this.getMimeType(u1.basename(J));return{content:Q,size:Number($.size),mimeType:W}}catch($){let Y=$ instanceof Error?$.message:"Unknown error";return I9.error("[FileManager] readFileBinary error",{error:Y,path:X.fullPath}),{content:Buffer.alloc(0),size:0,mimeType:"",error:`Failed to read file: ${Y}`}}}async writeFileBinary(Z,J,X){let $=this.validatePath(Z,J);if(!$.valid)return{success:!1,error:$.error};try{let Y=u1.basename(J);if(!this.isValidFilename(Y))return{success:!1,error:"Invalid filename"};let Q=u1.dirname($.fullPath);return await K1.mkdir(Q,{recursive:!0}),await K1.writeFile($.fullPath,X),{success:!0}}catch(Y){let Q=Y instanceof Error?Y.message:"Unknown error";return I9.error("[FileManager] writeFileBinary error",{error:Q,path:$.fullPath}),{success:!1,error:`Failed to write file: ${Q}`}}}getMimeType(Z){let J=u1.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"],X=(Z.split(".")[0]||"").toUpperCase();if(J.includes(X))return!1;if(/[<>:"|?*\x00-\x1f]/.test(Z))return!1;if(Z==="."||Z==="..")return!1;return!0}}import*as Bj from"path";var l4=x(),C$=51200,a30=50;class lH{name="File Browser Service";running=!1;startedAt;mqttClient=null;fileManager;requestsHandled=0;messageHandlers=new Map;fileSaveOperations=new Map;binaryUploadOperations=new Map;constructor(){this.fileManager=new cH}setMQTTClient(Z){this.mqttClient=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,l4.info("[FileBrowser] Service started"),this.mqttClient)this.registerMQTTHandlers()}catch(Z){throw l4.error("[FileBrowser] Failed to start",Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.mqttClient){for(let[Z,J]of this.messageHandlers)this.mqttClient.unsubscribe(Z,J);this.messageHandlers.clear()}this.fileSaveOperations.clear(),this.binaryUploadOperations.clear(),l4.info("[FileBrowser] Service stopped")}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)}),l4.info("[FileBrowser] MQTT handlers registered")}registerHandler(Z,J){if(!this.mqttClient)return;this.messageHandlers.set(Z,J),this.mqttClient.subscribe(Z,J)}async handleDirectoryListRequest(Z){try{let J=JSON.parse(Z.toString()),X=await this.fileManager.listDirectory(J.projectPath,J.relativePath),$={path:J.relativePath,entries:X.entries,timestamp:Date.now(),error:X.error};await this.publishResponse(`files/list/${J.clientId}/response`,$),this.requestsHandled++}catch(J){l4.error("[FileBrowser] Error handling directory list request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileContentRequest(Z){try{let J=JSON.parse(Z.toString()),X=await this.fileManager.readFile(J.projectPath,J.relativePath),$=`files/content/${J.clientId}/response`;if(X.error){let Q={path:J.relativePath,chunk:{chunkIndex:0,totalChunks:1,content:""},totalSize:0,timestamp:Date.now(),error:X.error};await this.publishResponse($,Q);return}let Y=Math.max(1,Math.ceil(X.content.length/C$));for(let Q=0;Q<Y;Q++){let W=Q*C$,K=Math.min(W+C$,X.content.length),z=X.content.slice(W,K),G={path:J.relativePath,chunk:{chunkIndex:Q,totalChunks:Y,content:z},totalSize:X.size,timestamp:Date.now()};if(await this.publishResponse($,G),Q<Y-1)await this.delay(a30)}this.requestsHandled++}catch(J){l4.error("[FileBrowser] Error handling file content request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileSaveRequest(Z){try{let J=JSON.parse(Z.toString()),X=`${J.clientId}:${J.relativePath}`;if(J.chunk.chunkIndex===0)this.fileSaveOperations.set(X,{chunks:new Map,totalChunks:J.chunk.totalChunks,totalSize:J.totalSize});let $=this.fileSaveOperations.get(X);if(!$){await this.sendSaveResponse(J,!1,"Save operation not initialized");return}if($.chunks.set(J.chunk.chunkIndex,J.chunk.content),await this.sendSaveResponse(J,!0),$.chunks.size===$.totalChunks){let Y=[];for(let K=0;K<$.totalChunks;K++){let z=$.chunks.get(K);if(z!==void 0)Y.push(z)}let Q=Y.join(""),W=await this.fileManager.writeFile(J.projectPath,J.relativePath,Q);if(this.fileSaveOperations.delete(X),!W.error)this.requestsHandled++}}catch(J){l4.error("[FileBrowser] Error handling file save request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileCreateRequest(Z){try{let J=JSON.parse(Z.toString()),X;if(J.type==="directory")X=await this.fileManager.createDirectory(J.projectPath,J.relativePath);else X=await this.fileManager.createFile(J.projectPath,J.relativePath);let $={path:J.relativePath,success:X.success,type:J.type,timestamp:Date.now(),error:X.error};if(await this.publishResponse(`files/create/${J.clientId}/response`,$),X.success)this.requestsHandled++}catch(J){l4.error("[FileBrowser] Error handling file create request",{error:J instanceof Error?J.message:"Unknown error"})}}async handleFileDeleteRequest(Z){try{let J=JSON.parse(Z.toString()),X=await this.fileManager.getStats(J.projectPath,J.relativePath),$;if(!X)$={success:!1,error:"Path does not exist"};else if(X.isDirectory)$=await this.fileManager.deleteDirectory(J.projectPath,J.relativePath);else $=await this.fileManager.deleteFile(J.projectPath,J.relativePath);let Y={path:J.relativePath,success:$.success,timestamp:Date.now(),error:$.error};if(await this.publishResponse(`files/delete/${J.clientId}/response`,Y),$.success)this.requestsHandled++}catch(J){l4.error("[FileBrowser] Error handling file delete request",{error:J instanceof Error?J.message:"Unknown error"})}}async sendSaveResponse(Z,J,X){let $={path:Z.relativePath,success:J,chunkIndex:Z.chunk.chunkIndex,totalChunks:Z.chunk.totalChunks,timestamp:Date.now(),error:X};await this.publishResponse(`files/save/${Z.clientId}/response`,$)}async publishResponse(Z,J){if(!this.mqttClient){l4.error("[FileBrowser] MQTT client not available");return}await this.mqttClient.publish(Z,JSON.stringify(J),{qos:1})}delay(Z){return new Promise((J)=>setTimeout(J,Z))}async handleBinaryUploadRequest(Z){try{let J=JSON.parse(Z.toString()),X=`${J.clientId}:${J.relativePath}`;if(J.chunk.chunkIndex===0){if(J.totalSize>52428800){await this.sendBinaryUploadResponse(J,!1,"File exceeds 50MB limit",0);return}this.binaryUploadOperations.set(X,{chunks:new Map,totalChunks:J.chunk.totalChunks,totalSize:J.totalSize,filename:J.filename,mimeType:J.mimeType,receivedBytes:0})}let $=this.binaryUploadOperations.get(X);if(!$){await this.sendBinaryUploadResponse(J,!1,"Upload operation not initialized",0);return}let Y=Buffer.from(J.chunk.data,"base64");if($.chunks.set(J.chunk.chunkIndex,Y),$.receivedBytes+=Y.length,await this.sendBinaryUploadResponse(J,!0,void 0,$.receivedBytes),$.chunks.size===$.totalChunks){let Q=[];for(let z=0;z<$.totalChunks;z++){let G=$.chunks.get(z);if(G)Q.push(G)}let W=Buffer.concat(Q),K=await this.fileManager.writeFileBinary(J.projectPath,J.relativePath,W);if(this.binaryUploadOperations.delete(X),K.error)l4.error("[FileBrowser] Binary upload write failed",{error:K.error});else this.requestsHandled++,l4.info("[FileBrowser] Binary upload completed",{path:J.relativePath,size:W.length})}}catch(J){l4.error("[FileBrowser] Error handling binary upload",{error:J instanceof Error?J.message:"Unknown error"})}}async sendBinaryUploadResponse(Z,J,X,$){let Y={path:Z.relativePath,success:J,chunkIndex:Z.chunk.chunkIndex,totalChunks:Z.chunk.totalChunks,bytesReceived:$||0,timestamp:Date.now(),error:X};await this.publishResponse(`files/upload/${Z.clientId}/response`,Y)}async handleBinaryDownloadRequest(Z){try{let J=JSON.parse(Z.toString()),X=`files/download/${J.clientId}/response`,$=await this.fileManager.readFileBinary(J.projectPath,J.relativePath);if($.error){let K={path:J.relativePath,filename:Bj.basename(J.relativePath),mimeType:"",chunk:{chunkIndex:0,totalChunks:1,data:""},totalSize:0,timestamp:Date.now(),error:$.error};await this.publishResponse(X,K);return}let Y=$.content.toString("base64"),Q=Math.max(1,Math.ceil(Y.length/C$)),W=Bj.basename(J.relativePath);for(let K=0;K<Q;K++){let z=K*C$,G=Math.min(z+C$,Y.length),H=Y.slice(z,G),V={path:J.relativePath,filename:W,mimeType:$.mimeType,chunk:{chunkIndex:K,totalChunks:Q,data:H},totalSize:$.size,timestamp:Date.now()};if(await this.publishResponse(X,V),K<Q-1)await this.delay(a30)}this.requestsHandled++,l4.info("[FileBrowser] Binary download completed",{path:J.relativePath,size:$.size,chunks:Q})}catch(J){l4.error("[FileBrowser] Error handling binary download",{error:J instanceof Error?J.message:"Unknown error"})}}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled,pendingSaveOperations:this.fileSaveOperations.size}}}var o=x();class pH{name="Git Service";running=!1;startedAt;mqttClient=null;worktreeManager;requestsHandled=0;messageHandlers=new Map;ghAuthResult={authenticated:!1,installed:!1,inPath:!1};constructor(){this.worktreeManager=new T$}setMQTTClient(Z){this.mqttClient=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,this.ghAuthResult=await F30(),!this.ghAuthResult.authenticated)o.warn("[GitService] GitHub CLI issue detected",{installed:this.ghAuthResult.installed,inPath:this.ghAuthResult.inPath,ghPath:this.ghAuthResult.ghPath,error:this.ghAuthResult.error});else{o.info("[GitService] GitHub CLI authenticated",{username:this.ghAuthResult.username,gitProtocol:this.ghAuthResult.gitProtocol});let Z=await U30();if(!Z.success)o.warn("[GitService] Could not sync gh config git_protocol",{error:Z.error});let J=await L30();if(!J.success)o.warn("[GitService] Could not setup git credential helper",{error:J.error})}if(this.mqttClient)this.registerMQTTHandlers();o.info("[GitService] Service started")}catch(Z){throw o.error("[GitService] Failed to start",Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.mqttClient){for(let[Z,J]of this.messageHandlers)this.mqttClient.unsubscribe(Z,J),o.debug(`[GitService] Unsubscribed from ${Z}`);this.messageHandlers.clear()}this.worktreeManager.clearCache(),o.info("[GitService] Service stopped")}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)}),o.info("[GitService] MQTT handlers registered")}registerHandler(Z,J){if(!this.mqttClient)return;this.messageHandlers.set(Z,J),this.mqttClient.subscribe(Z,J),o.debug(`[GitService] Subscribed to ${Z}`)}async publishResponse(Z,J){if(!this.mqttClient){o.error("[GitService] MQTT client not available");return}await this.mqttClient.publish(Z,JSON.stringify(J),{qos:1})}async handleOrgsRequest(Z){try{let J=JSON.parse(Z.toString());if(o.debug("[GitService] Orgs request",{clientId:J.clientId}),!this.ghAuthResult.authenticated){let Y={orgs:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/orgs/${J.clientId}/response`,Y);return}let $={orgs:await Wj(),timestamp:Date.now()};await this.publishResponse(`git/orgs/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling orgs request",{error:J})}}async handleReposRequest(Z){try{let J=JSON.parse(Z.toString()),X=J.requestId||J.clientId;if(o.debug("[GitService] Repos request",{clientId:J.clientId,requestId:J.requestId,org:J.org,limit:J.limit}),!this.ghAuthResult.authenticated){let Q={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/${X}/response`,Q);return}let Y={repos:await bH(J.org,J.limit||20),timestamp:Date.now()};await this.publishResponse(`git/repos/${X}/response`,Y),this.requestsHandled++}catch(J){o.error("[GitService] Error handling repos request",{error:J})}}async handleSearchReposRequest(Z){try{let J=JSON.parse(Z.toString());if(o.debug("[GitService] Search repos request",{clientId:J.clientId,query:J.query,limit:J.limit}),!this.ghAuthResult.authenticated){let X={repos:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/repos/search/${J.clientId}/response`,X);return}await D30(J.query,async(X,$,Y)=>{let Q={repos:X,timestamp:Date.now(),source:$,isComplete:Y};await this.publishResponse(`git/repos/search/${J.clientId}/response`,Q),o.debug("[GitService] Sent search results",{source:$,count:X.length,isComplete:Y})},J.limit||50),this.requestsHandled++}catch(J){o.error("[GitService] Error handling search repos request",{error:J})}}async handleBranchesRequest(Z){try{let J=JSON.parse(Z.toString());if(o.debug("[GitService] Branches request",{clientId:J.clientId,owner:J.owner,repo:J.repo}),!this.ghAuthResult.authenticated){let Y={branches:[],error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/branches/${J.clientId}/response`,Y);return}let X=await _30(J.owner,J.repo),$={branches:X.branches,defaultBranch:X.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/branches/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling branches request",{error:J})}}async handleCloneRequest(Z){try{let J=JSON.parse(Z.toString());if(o.info("[GitService] Clone request",{clientId:J.clientId,repoUrl:J.repoUrl,targetPath:J.targetPath,branch:J.branch}),!this.ghAuthResult.authenticated){let Y={success:!1,error:this.ghAuthResult.error||"GitHub CLI not available.",timestamp:Date.now()};await this.publishResponse(`git/clone/${J.clientId}/response`,Y);return}let X=await O30(J.repoUrl,J.targetPath,J.branch),$=X.success?{success:!0,path:X.path,defaultBranch:X.defaultBranch,timestamp:Date.now()}:{success:!1,error:X.error||"Clone failed",timestamp:Date.now()};await this.publishResponse(`git/clone/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling clone request",{error:J})}}async handleIsRepoRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Is-repo request",{clientId:J.clientId,path:J.path});let X=await M$(J.path),$;if(X){let[Y,Q,W]=await Promise.all([h5(J.path),DJ(J.path),E30(J.path)]);$={isGitRepo:!0,repoRoot:Y||void 0,defaultBranch:Q||void 0,remoteUrl:W||void 0,timestamp:Date.now()}}else $={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling is-repo request",{error:J});let X=JSON.parse(Z.toString()),$={isGitRepo:!1,timestamp:Date.now()};await this.publishResponse(`git/is-repo/${X.clientId}/response`,$)}}async handleWorktreeGetOrCreateRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Worktree get-or-create request",{clientId:J.clientId,repoPath:J.repoPath,sessionId:J.sessionId});let{worktree:X,isNew:$}=await this.worktreeManager.getOrCreateForSession(J.sessionId,J.repoPath),Y={success:!0,worktreePath:X.path,branch:X.branch,isNew:$,timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${J.clientId}/response`,Y),this.requestsHandled++}catch(J){o.error("[GitService] Error handling worktree get-or-create request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/worktree/get-or-create/${X.clientId}/response`,$)}}async handleWorktreeGetRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Worktree get request",{clientId:J.clientId,repoPath:J.repoPath,sessionId:J.sessionId});let X=await this.worktreeManager.getWorktreeForSession(J.sessionId,J.repoPath),$=X?{exists:!0,worktreePath:X.path,branch:X.branch,timestamp:Date.now()}:{exists:!1,timestamp:Date.now()};await this.publishResponse(`git/worktree/get/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling worktree get request",{error:J})}}async handleWorktreeListRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Worktree list request",{clientId:J.clientId,repoPath:J.repoPath});let $={worktrees:await this.worktreeManager.listWorktreesForRepo(J.repoPath),timestamp:Date.now()};await this.publishResponse(`git/worktree/list/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling worktree list request",{error:J})}}async handleStatusRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Status request",{clientId:J.clientId,path:J.path});let $={success:!0,status:await Kj(J.path),timestamp:Date.now()};await this.publishResponse(`git/status/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling status request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/status/${X.clientId}/response`,$)}}async handleDiffRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Diff request",{clientId:J.clientId,path:J.path,file:J.file,staged:J.staged});let X=await j30(J.path,J.file,J.staged),$={success:!0,diff:X.diff,isBinary:X.isBinary,timestamp:Date.now()};await this.publishResponse(`git/diff/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling diff request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/diff/${X.clientId}/response`,$)}}async handleChangesAllRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Changes all request",{clientId:J.clientId,repoPath:J.repoPath});let X=await this.worktreeManager.listWorktreesForRepo(J.repoPath),$={repoPath:J.repoPath,worktrees:[],totalChanges:0};for(let Q of X)try{let W=await Kj(Q.path);$.worktrees.push({worktreePath:Q.path,branch:Q.branch,sessionId:Q.sessionId,changes:W.files,totalCount:W.files.length}),$.totalChanges+=W.files.length}catch(W){o.warn("[GitService] Failed to get status for worktree",{path:Q.path,error:W})}let Y={success:!0,changes:$,timestamp:Date.now()};await this.publishResponse(`git/changes/all/${J.clientId}/response`,Y),this.requestsHandled++}catch(J){o.error("[GitService] Error handling changes all request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/changes/all/${X.clientId}/response`,$)}}async handleStageRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Stage request",{clientId:J.clientId,path:J.path,files:J.files}),await M30(J.path,J.files);let X={success:!0,timestamp:Date.now()};await this.publishResponse(`git/stage/${J.clientId}/response`,X),this.requestsHandled++}catch(J){o.error("[GitService] Error handling stage request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/stage/${X.clientId}/response`,$)}}async handleUnstageRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Unstage request",{clientId:J.clientId,path:J.path,files:J.files}),await A30(J.path,J.files);let X={success:!0,timestamp:Date.now()};await this.publishResponse(`git/unstage/${J.clientId}/response`,X),this.requestsHandled++}catch(J){o.error("[GitService] Error handling unstage request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unstage/${X.clientId}/response`,$)}}async handleCommitRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Commit request",{clientId:J.clientId,path:J.path,signoff:J.signoff});let $={success:!0,commit:await T30(J.path,J.message,J.signoff),timestamp:Date.now()};await this.publishResponse(`git/commit/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling commit request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit/${X.clientId}/response`,$)}}async handleUnpushedCommitsRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Unpushed commits request",{clientId:J.clientId,path:J.path});let X=await j$(J.path),$={success:!0,commits:X.commits,upstream:X.upstream,ahead:X.ahead,timestamp:Date.now()};await this.publishResponse(`git/unpushed/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling unpushed commits request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/unpushed/${X.clientId}/response`,$)}}async handlePushRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Push request",{clientId:J.clientId,path:J.path,force:J.force});let X=await I30(J.path,J.force),$={success:!0,commitsPushed:X.commitsPushed,remote:X.remote,branch:X.branch,timestamp:Date.now()};await this.publishResponse(`git/push/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling push request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/push/${X.clientId}/response`,$)}}async handleHistoryRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] History request",{clientId:J.clientId,path:J.path,limit:J.limit});let X=await y30(J.path,J.limit||50),$={success:!0,commits:X.commits,totalCount:X.totalCount,timestamp:Date.now()};await this.publishResponse(`git/history/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling history request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/history/${X.clientId}/response`,$)}}async handleCommitDetailsRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Commit details request",{clientId:J.clientId,path:J.path,commitHash:J.commitHash});let $={success:!0,commit:await S30(J.path,J.commitHash),timestamp:Date.now()};await this.publishResponse(`git/commit-details/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling commit details request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-details/${X.clientId}/response`,$)}}async handleCommitFileDiffRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Commit file diff request",{clientId:J.clientId,path:J.path,commitHash:J.commitHash,filePath:J.filePath});let X=await x30(J.path,J.commitHash,J.filePath),$={success:!0,diff:X.diff,isBinary:X.isBinary,timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling commit file diff request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/commit-file-diff/${X.clientId}/response`,$)}}async handleSyncRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Sync request",{clientId:J.clientId,path:J.path});let X=await k30(J.path),$=X.success?{success:!0,action:X.action,commitsPulled:X.commitsPulled,commitsPushed:X.commitsPushed,timestamp:Date.now()}:{success:!1,action:X.action,commitsPulled:X.commitsPulled,commitsPushed:X.commitsPushed,error:X.error||"Sync failed",conflictedFiles:X.conflictedFiles,timestamp:Date.now()};await this.publishResponse(`git/sync/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling sync request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,action:"error",commitsPulled:0,commitsPushed:0,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/sync/${X.clientId}/response`,$)}}async handleCreatePRRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Create PR request",{clientId:J.clientId,path:J.path,title:J.title,baseBranch:J.baseBranch,draft:J.draft});let X=await v30(J.path,J.title,J.body,J.baseBranch,J.draft),$=X.success?{success:!0,prNumber:X.prNumber,prUrl:X.prUrl,timestamp:Date.now()}:{success:!1,error:X.error||"Failed to create pull request",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling create PR request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-pr/${X.clientId}/response`,$)}}async handleDefaultBranchRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Default branch request",{clientId:J.clientId,path:J.path});let X=await zj(J.path),$=X?{success:!0,defaultBranch:X,timestamp:Date.now()}:{success:!1,error:"Could not determine default branch",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling default branch request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/default-branch/${X.clientId}/response`,$)}}async handleExistingPRRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Existing PR request",{clientId:J.clientId,path:J.path});let X=await h30(J.path),$={exists:X.exists,prNumber:X.prNumber,prUrl:X.prUrl,title:X.title,state:X.state,draft:X.draft,error:X.error,timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling existing PR request",{error:J});let X=JSON.parse(Z.toString()),$={exists:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/existing-pr/${X.clientId}/response`,$)}}async handleRemoteBranchesRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Remote branches request",{clientId:J.clientId,path:J.path});let X=await f30(J.path),$={success:!0,branches:X.branches,defaultBranch:X.defaultBranch,timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling remote branches request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/remote-branches/${X.clientId}/response`,$)}}async handleCreateBranchRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Create branch request",{clientId:J.clientId,path:J.path,branchName:J.branchName,checkout:J.checkout});let X=await q30(J.path,J.branchName,J.checkout!==!1),$=X.success?{success:!0,branchName:J.branchName,timestamp:Date.now()}:{success:!1,error:X.error||"Failed to create branch",timestamp:Date.now()};await this.publishResponse(`git/create-branch/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling create branch request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/create-branch/${X.clientId}/response`,$)}}async handleLocalBranchesRequest(Z){try{let J=JSON.parse(Z.toString());o.debug("[GitService] Local branches request",{clientId:J.clientId,path:J.path});let X=await N30(J.path),$={success:!0,branches:X.branches,currentBranch:X.currentBranch,timestamp:Date.now()};await this.publishResponse(`git/local-branches/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling local branches request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/local-branches/${X.clientId}/response`,$)}}async handleCheckoutBranchRequest(Z){try{let J=JSON.parse(Z.toString());o.info("[GitService] Checkout branch request",{clientId:J.clientId,path:J.path,branchName:J.branchName});let X=await C30(J.path,J.branchName),$=X.success?{success:!0,branchName:J.branchName,timestamp:Date.now()}:{success:!1,error:X.error||"Failed to checkout branch",timestamp:Date.now()};await this.publishResponse(`git/checkout-branch/${J.clientId}/response`,$),this.requestsHandled++}catch(J){o.error("[GitService] Error handling checkout branch request",{error:J});let X=JSON.parse(Z.toString()),$={success:!1,error:J instanceof Error?J.message:"Unknown error",timestamp:Date.now()};await this.publishResponse(`git/checkout-branch/${X.clientId}/response`,$)}}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 ZQ0 from"path";import*as iH from"path";import*as r30 from"os";import*as nH from"fs";var z1=x(),dQ=iH.join(r30.homedir(),".ccc"),gQ=iH.join(dQ,"device-tokens.json"),mQ=iH.join(dQ,"notification-preferences.json");class s30{tokensCache=null;preferencesCache=null;async ensureDirectory(){try{if(!nH.existsSync(dQ))nH.mkdirSync(dQ,{recursive:!0}),z1.debug("[NotificationStorage] Created .ccc directory:",dQ)}catch(Z){throw z1.error("[NotificationStorage] Error ensuring directory:",Z),Z}}async loadTokens(){if(this.tokensCache)return this.tokensCache;try{let Z=Bun.file(gQ);if(await Z.exists()){let J=await Z.text(),X=JSON.parse(J);if(X&&typeof X==="object"&&Array.isArray(X.tokens)){let $=X;return this.tokensCache=$,z1.debug("[NotificationStorage] Loaded tokens:",{count:$.tokens.length}),$}else if(X&&typeof X==="object")return z1.warn("[NotificationStorage] Invalid tokens file format, attempting to recover data"),this.tokensCache={tokens:Array.isArray(X.tokens)?X.tokens:[]},await this.saveTokens(this.tokensCache),this.tokensCache;else{z1.error("[NotificationStorage] Completely invalid tokens file format, creating backup");let $=`${gQ}.backup.${Date.now()}`;await Bun.write($,J),z1.error("[NotificationStorage] Backup saved to:",$)}}}catch(Z){z1.error("[NotificationStorage] Error loading tokens:",Z);try{let J=Bun.file(gQ);if(await J.exists()){let X=await J.text(),$=`${gQ}.backup.${Date.now()}`;await Bun.write($,X),z1.error("[NotificationStorage] Corrupted file backed up to:",$)}}catch{}}return this.tokensCache={tokens:[]},this.tokensCache}async saveTokens(Z){try{await this.ensureDirectory(),await Bun.write(gQ,JSON.stringify(Z,null,2)),this.tokensCache=Z,z1.debug("[NotificationStorage] Saved tokens:",{count:Z.tokens.length})}catch(J){throw z1.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:X,platform:$,deviceInfo:Y,createdAt:z?.createdAt??W,lastUsed:W};if(K>=0)Q.tokens[K]=G,z1.info("[NotificationStorage] Updated device token:",{deviceId:Z,platform:$,hasExpoPushToken:!!X});else Q.tokens.push(G),z1.info("[NotificationStorage] Registered new device token:",{deviceId:Z,platform:$,hasExpoPushToken:!!X});return await this.saveTokens(Q),G}async unregisterToken(Z){let J=await this.loadTokens(),X=J.tokens.length;if(J.tokens=J.tokens.filter(($)=>$.deviceId!==Z),J.tokens.length<X)return await this.saveTokens(J),z1.info("[NotificationStorage] Unregistered device token:",{deviceId:Z}),!0;return!1}async getToken(Z){return(await this.loadTokens()).tokens.find((X)=>X.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(),X=J.tokens.find(($)=>$.deviceId===Z);if(X)X.lastUsed=new Date().toISOString(),await this.saveTokens(J)}async cleanupOldTokens(Z=90){let J=await this.loadTokens(),X=new Date;X.setDate(X.getDate()-Z);let $=X.toISOString(),Y=J.tokens.length;J.tokens=J.tokens.filter((W)=>W.lastUsed>$);let Q=Y-J.tokens.length;if(Q>0)await this.saveTokens(J),z1.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(mQ);if(await Z.exists()){let J=await Z.text(),X=JSON.parse(J);if(X&&typeof X==="object"&&typeof X.preferences==="object"&&!Array.isArray(X.preferences)){let $=X;return this.preferencesCache=$,z1.debug("[NotificationStorage] Loaded preferences:",{count:Object.keys($.preferences).length}),$}else if(X&&typeof X==="object")return z1.warn("[NotificationStorage] Invalid preferences file format, attempting to recover data"),this.preferencesCache={preferences:X.preferences&&typeof X.preferences==="object"&&!Array.isArray(X.preferences)?X.preferences:{}},await this.savePreferences(this.preferencesCache),this.preferencesCache;else{z1.error("[NotificationStorage] Completely invalid preferences file format, creating backup");let $=`${mQ}.backup.${Date.now()}`;await Bun.write($,J),z1.error("[NotificationStorage] Backup saved to:",$)}}}catch(Z){z1.error("[NotificationStorage] Error loading preferences:",Z);try{let J=Bun.file(mQ);if(await J.exists()){let X=await J.text(),$=`${mQ}.backup.${Date.now()}`;await Bun.write($,X),z1.error("[NotificationStorage] Corrupted file backed up to:",$)}}catch{}}return this.preferencesCache={preferences:{}},this.preferencesCache}async savePreferences(Z){try{await this.ensureDirectory(),await Bun.write(mQ,JSON.stringify(Z,null,2)),this.preferencesCache=Z,z1.debug("[NotificationStorage] Saved preferences:",{count:Object.keys(Z.preferences).length})}catch(J){throw z1.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),z1.info("[NotificationStorage] Created default preferences for device:",{deviceId:Z});return J.preferences[Z]}async updatePreferences(Z,J){let X=await this.loadPreferences(),$=await this.getPreferences(Z);return X.preferences[Z]={...$,...J,deviceId:Z,updatedAt:new Date().toISOString()},await this.savePreferences(X),z1.info("[NotificationStorage] Updated preferences:",{deviceId:Z,updates:J}),X.preferences[Z]}async isNotificationEnabled(Z,J){return(await this.getPreferences(Z))[J]}clearCache(){this.tokensCache=null,this.preferencesCache=null,z1.debug("[NotificationStorage] Cleared cache")}}var F8=new s30;import{Expo as _Z1}from"expo-server-sdk";function OZ1(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 F6=x();class t30{expo=null;notificationsSent=0;lastNotificationAt;pendingTickets=new Map;getExpo(){if(!this.expo)this.expo=new _Z1;return this.expo}isValidToken(Z){return OZ1(Z)}async sendNotification(Z,J){if(!this.isValidToken(Z))return F6.warn("[ExpoPushClient] Invalid Expo push token:",{token:Z.substring(0,20)+"..."}),null;let X={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([X]))[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 F6.debug("[ExpoPushClient] Sent notification:",{token:Z.substring(0,20)+"...",status:Q?.status}),Q??null}catch($){return F6.error("[ExpoPushClient] Error sending notification:",$),null}}async sendBatchNotifications(Z,J){let X=[];for(let K of Z)if(!this.isValidToken(K))F6.warn("[ExpoPushClient] Skipping invalid token:",{token:K.substring(0,20)+"..."});else X.push(K);if(X.length===0)return F6.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($),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=X[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){F6.error("[ExpoPushClient] Error sending batch chunk:",z)}return F6.info("[ExpoPushClient] Sent batch notifications:",{total:X.length,successful:W.filter((K)=>K.status==="ok").length,failed:W.filter((K)=>K.status==="error").length}),W}async handleTicketError(Z,J){if(F6.warn("[ExpoPushClient] Ticket error:",{message:Z.message,details:Z.details}),Z.details?.error==="DeviceNotRegistered"){F6.info("[ExpoPushClient] Removing invalid token:",{token:J.substring(0,20)+"..."});let $=(await F8.getAllTokens()).find((Y)=>Y.expoPushToken===J);if($)await F8.unregisterToken($.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;F6.debug("[ExpoPushClient] Checking receipts:",{count:J.length});let X=this.getExpo(),$=X.chunkPushNotificationReceiptIds(J);for(let Q of $)try{let W=await X.getPushNotificationReceiptsAsync(Q);for(let[K,z]of Object.entries(W)){let G=this.pendingTickets.get(K),H=z;if(H.status==="ok")F6.debug("[ExpoPushClient] Receipt OK:",{ticketId:K});else if(H.status==="error"){let V=z;if(F6.warn("[ExpoPushClient] Receipt error:",{ticketId:K,message:V.message,details:V.details}),V.details?.error==="DeviceNotRegistered"&&G){let B=(await F8.getAllTokens()).find((U)=>U.expoPushToken===G.token);if(B)F6.info("[ExpoPushClient] Removing invalid token from receipt:",{deviceId:B.deviceId}),await F8.unregisterToken(B.deviceId)}}this.pendingTickets.delete(K)}}catch(W){F6.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 uQ=new t30;var J1=x(),e30=200,wZ1=900000;class oH{name="Notification Service";running=!1;startedAt;mqttClient=null;claudeAgentService=null;receiptCheckInterval;constructor(){}setMQTTClient(Z){this.mqttClient=Z}setClaudeAgentService(Z){this.claudeAgentService=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,J1.info("[Notification] Service started"),this.mqttClient)this.registerMQTTHandlers();else J1.warn("[Notification] MQTT client not set - handlers will not be registered");this.receiptCheckInterval=setInterval(()=>{uQ.checkReceipts().catch((Z)=>{J1.error("[Notification] Error checking receipts:",Z)})},wZ1),J1.info("[Notification] Ready to send notifications")}catch(Z){throw J1.error("[Notification] Failed to start",Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.receiptCheckInterval)clearInterval(this.receiptCheckInterval);J1.info("[Notification] Service stopped")}registerMQTTHandlers(){if(!this.mqttClient)return;this.mqttClient.subscribe("notifications/register/request",this.handleRegisterToken.bind(this)),this.mqttClient.subscribe("notifications/preferences/get/request",this.handleGetPreferences.bind(this)),this.mqttClient.subscribe("notifications/preferences/update/request",this.handleUpdatePreferences.bind(this)),this.mqttClient.subscribe("claude/+/output/+",this.handleClaudeOutput.bind(this)),this.mqttClient.subscribe("claude/+/permission/request/+",this.handlePermissionRequest.bind(this)),J1.info("[Notification] MQTT handlers registered")}async handleRegisterToken(Z,J){try{let X=JSON.parse(J.toString());J1.info("[Notification] Register token request:",{deviceId:X.deviceId,platform:X.platform,hasExpoPushToken:!!X.expoPushToken,hasFcmToken:!!X.fcmToken}),await F8.registerToken(X.deviceId,X.fcmToken,X.expoPushToken,X.platform,X.deviceInfo);let $={requestId:X.requestId,success:!0};await this.mqttClient?.publish("notifications/register/response",JSON.stringify($)),J1.info("[Notification] Token registered successfully:",{deviceId:X.deviceId})}catch(X){J1.error("[Notification] Error registering token:",X);try{let $=J.toString(),Q={requestId:JSON.parse($).requestId,success:!1,error:X instanceof Error?X.message:"Unknown error"};await this.mqttClient?.publish("notifications/register/response",JSON.stringify(Q))}catch{}}}async handleGetPreferences(Z,J){try{let X=JSON.parse(J.toString());J1.debug("[Notification] Get preferences request:",{deviceId:X.deviceId});let $=await F8.getPreferences(X.deviceId),Y={requestId:X.requestId,success:!0,preferences:$};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(Y)),J1.debug("[Notification] Sent preferences:",{deviceId:X.deviceId})}catch(X){J1.error("[Notification] Error getting preferences:",X);try{let Y={requestId:JSON.parse(J.toString()).requestId,success:!1,error:X instanceof Error?X.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/get/response",JSON.stringify(Y))}catch{}}}async handleUpdatePreferences(Z,J){try{let X=JSON.parse(J.toString());J1.info("[Notification] Update preferences request:",{deviceId:X.deviceId,preferences:X.preferences});let $=await F8.updatePreferences(X.deviceId,X.preferences),Y={requestId:X.requestId,success:!0,preferences:$};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(Y)),J1.info("[Notification] Preferences updated:",{deviceId:X.deviceId})}catch(X){J1.error("[Notification] Error updating preferences:",X);try{let Y={requestId:JSON.parse(J.toString()).requestId,success:!1,error:X instanceof Error?X.message:"Unknown error"};await this.mqttClient?.publish("notifications/preferences/update/response",JSON.stringify(Y))}catch{}}}async handleClaudeOutput(Z,J){try{let X=Z.split("/"),$=X[1],Y=X[3],Q=JSON.parse(J.toString());if(Q.type!=="assistant")return;let W=this.getSessionInfo(Y??"");if(!W){J1.debug("[Notification] Session not found for notification:",{sessionId:Y});return}let K=this.buildNotificationTitle(W),z=this.extractMessageBody(Q);if(!z)return;let G={type:"message",projectId:W.projectPath,sessionId:Y??""};await this.sendToDevicesWithPreference("allMessages",{title:K,body:z,data:G,priority:"high",channelId:"messages"}),J1.debug("[Notification] Sent message notification:",{sessionId:Y,title:K})}catch(X){J1.error("[Notification] Error handling Claude output:",X)}}async handlePermissionRequest(Z,J){try{let X=Z.split("/"),$=X[1],Y=X[4],Q=JSON.parse(J.toString()),W=this.getSessionInfo(Y??"");if(!W){J1.debug("[Notification] Session not found for permission notification:",{sessionId:Y});return}let K=this.buildNotificationTitle(W),z=this.buildPermissionBody(Q),G={type:"permission",projectId:W.projectPath,sessionId:Y??"",requestId:Q.request_id,action:Q.action};await this.sendToDevicesWithPreference("needsAttention",{title:K,body:z,data:G,priority:"high",channelId:"default"}),J1.info("[Notification] Sent permission notification:",{sessionId:Y,action:Q.action})}catch(X){J1.error("[Notification] Error handling permission request:",X)}}getSessionInfo(Z){if(!this.claudeAgentService)return null;let X=this.claudeAgentService.getActiveSessions().find(($)=>$.sessionId===Z);if(!X)return null;return{sessionId:X.sessionId,projectPath:X.projectPath,worktreeBranch:X.worktreeBranch}}buildNotificationTitle(Z){let J=ZQ0.basename(Z.projectPath);if(Z.worktreeBranch){let X=Z.worktreeBranch.replace("session/","");return`${J} (${X})`}return J}extractMessageBody(Z){let J="",X=Z.message;if(X?.content&&Array.isArray(X.content))J=X.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).filter(Boolean).join(`
|
|
2371
2371
|
`);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(`
|
|
2372
2372
|
`)}if(!J.trim())return null;if(J.length>e30)J=J.substring(0,e30)+"...";return J}buildPermissionBody(Z){let J=Z.action||"Unknown tool",X=Z.params||{},$="";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||X.command||X.path||""}if($.length>100)$=$.substring(0,100)+"...";if($)return`Permission requested: ${J}: ${$}`;return`Permission requested: ${J}`}async sendToDevicesWithPreference(Z,J){try{let X=await F8.getAllTokens();if(X.length===0){J1.debug("[Notification] No registered devices");return}let $=[];for(let Y of X){if(!Y.expoPushToken)continue;if((await F8.getPreferences(Y.deviceId))[Z])$.push(Y.expoPushToken)}if($.length===0){J1.debug("[Notification] No devices with preference enabled:",{preferenceType:Z});return}await uQ.sendBatchNotifications($,J),J1.debug("[Notification] Sent to devices:",{count:$.length,preferenceType:Z})}catch(X){J1.error("[Notification] Error sending to devices:",X)}}getStatus(){let Z=uQ.getStats();return{name:this.name,running:this.running,startedAt:this.startedAt,registeredDevices:0,notificationsSent:Z.notificationsSent,lastNotificationAt:Z.lastNotificationAt}}}import*as l7 from"fs/promises";import*as Y4 from"path";import*as JQ0 from"os";var{YAML:jZ1}=globalThis.Bun;var aH=x();class p4{running=!1;startedAt;mqttClient=null;requestsHandled=0;messageHandlers=new Map;setMQTTClient(Z){this.mqttClient=Z}async start(){try{if(this.running=!0,this.startedAt=new Date,await this.onStart(),aH.info(`${this.logPrefix} Service started`),this.mqttClient)this.registerMQTTHandlers()}catch(Z){throw aH.error(`${this.logPrefix} Failed to start`,Z),this.running=!1,Z}}async stop(){if(this.running=!1,this.mqttClient){for(let[Z,J]of this.messageHandlers)this.mqttClient.unsubscribe(Z,J);this.messageHandlers.clear()}await this.onStop(),aH.info(`${this.logPrefix} Service stopped`)}getStatus(){return{name:this.name,running:this.running,startedAt:this.startedAt,requestsHandled:this.requestsHandled}}async onStart(){}async onStop(){}registerHandler(Z,J){if(!this.mqttClient)return;this.messageHandlers.set(Z,J),this.mqttClient.subscribe(Z,J)}async publishResponse(Z,J){if(!this.mqttClient)return;await this.mqttClient.publish(Z,JSON.stringify(J),{qos:1})}buildResponseTopic(Z,J,X){if(X)return`${Z}/${J}/${X}/response`;return`${Z}/${J}/response`}incrementRequestCount(){this.requestsHandled++}parseMessage(Z){try{return JSON.parse(Z.toString())}catch(J){return aH.warn(`${this.logPrefix} Failed to parse message`,{error:J}),null}}formatError(Z){return Z instanceof Error?Z.message:"Unknown error"}}var c7=x();class rH extends p4{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)}),c7.info("[SlashCommands] MQTT handlers registered")}getCommandsDir(Z,J){if(Z==="global")return Y4.join(JQ0.homedir(),".claude","commands");else{if(!J)throw Error("Project path is required for project-scoped commands");return Y4.join(J,".claude","commands")}}parseHooksManually(Z){let J={},X=(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($){let W=this.parseHookItems($);if(W.length>0)J.PreToolUse=W}let Y=X(Z,"PostToolUse");if(Y){let W=this.parseHookItems(Y);if(W.length>0)J.PostToolUse=W}let Q=X(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=[],X=Z.split(/(?=- matcher:)/);for(let $ of X){if(!$.trim())continue;let Y=$.match(/- matcher:\s*(.+)/);if(!Y||!Y[1])continue;let Q=Y[1].trim(),W=[],K=$.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]*)$/,X=Z.match(J);if(!X)return{body:Z};let $=X[1]||"",Y=X[2]||"";try{let Q;try{Q=jZ1.parse($)}catch(K){c7.debug("[SlashCommands] YAML parse failed, attempting manual extraction",{yamlError:K});let z={},G=$.match(/^description:\s*["'](.+?)["']\s*$/m);if(G)z.description=G[1];let H=$.match(/^argument-hint:\s*(.+?)\s*$/m);if(H&&H[1]){let D=H[1].trim();if(D.startsWith('"')&&D.endsWith('"')||D.startsWith("'")&&D.endsWith("'"))D=D.slice(1,-1);z["argument-hint"]=D}let V=$.match(/^allowed-tools:\s*(.+?)\s*$/m);if(V&&V[1])z["allowed-tools"]=V[1].trim();let F=$.match(/^context:\s*(fork|inline)\s*$/m);if(F)z.context=F[1];let B=$.match(/^agent:\s*(.+?)\s*$/m);if(B&&B[1])z.agent=B[1].trim();let U=$.match(/^model:\s*(.+?)\s*$/m);if(U&&U[1])z.model=U[1].trim();if($.includes("hooks:")){let D=$.match(/^hooks:\s*\n([\s\S]*?)(?=^[a-z]|$(?![\s\S]))/m);if(D&&D[1])z.hooks=this.parseHooksManually(D[1]);else{let _=$.indexOf(`hooks:
|
|
2373
2373
|
`);if(_!==-1){let O=$.slice(_+7);z.hooks=this.parseHooksManually(O)}}}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 c7.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 X=Z["argument-hint"],$=/[<>:{}[\]|&*?#!%@`]/.test(X)||X.startsWith("-")||X.startsWith(" ");J.push(`argument-hint: ${$?`"${X.replace(/"/g,"\\\"")}"`:X}`)}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 X of Z.hooks.PreToolUse)if(J.push(` - matcher: ${X.matcher}`),X.hooks&&X.hooks.length>0){J.push(" hooks:");for(let $ of X.hooks)J.push(` - command: ${$.command}`)}}if(Z.hooks.PostToolUse&&Z.hooks.PostToolUse.length>0){J.push(" PostToolUse:");for(let X of Z.hooks.PostToolUse)if(J.push(` - matcher: ${X.matcher}`),X.hooks&&X.hooks.length>0){J.push(" hooks:");for(let $ of X.hooks)J.push(` - command: ${$.command}`)}}if(Z.hooks.Stop&&Z.hooks.Stop.length>0){J.push(" Stop:");for(let X of Z.hooks.Stop)J.push(` - command: ${X.command}`)}}return J.push("---"),J.join(`
|
|
@@ -61,14 +61,8 @@ const targets = [
|
|
|
61
61
|
ngrokLib: 'ngrok.win32-x64-msvc.node',
|
|
62
62
|
ngrokPkg: '@ngrok/ngrok-win32-x64-msvc',
|
|
63
63
|
},
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
target: 'bun-windows-arm64',
|
|
67
|
-
outfile: 'ccc-windows-arm64.exe',
|
|
68
|
-
ptyLib: 'rust_pty_arm64.dll',
|
|
69
|
-
ngrokLib: 'ngrok.win32-arm64-msvc.node',
|
|
70
|
-
ngrokPkg: '@ngrok/ngrok-win32-arm64-msvc',
|
|
71
|
-
},
|
|
64
|
+
// NOTE: windows-arm64 is not supported by Bun's compile target (no bun-windows-aarch64)
|
|
65
|
+
// Re-enable when Bun adds support: https://github.com/oven-sh/bun/issues/9824
|
|
72
66
|
];
|
|
73
67
|
|
|
74
68
|
// Parse command line arguments
|
package/package.json
CHANGED
|
@@ -1,87 +1,86 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@naarang/ccc",
|
|
3
|
-
"version": "2.1.
|
|
4
|
-
"description": "Code Chat Connect - Control Claude Code from your mobile device",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "dist/index.js",
|
|
7
|
-
"bin": {
|
|
8
|
-
"ccc": "bin/ccc.cjs"
|
|
9
|
-
},
|
|
10
|
-
"scripts": {
|
|
11
|
-
"dev": "bun src/index.ts",
|
|
12
|
-
"build": "bun scripts/build-dist.ts",
|
|
13
|
-
"build:compile": "bun scripts/build-binaries.ts",
|
|
14
|
-
"build:linux-x64": "bun scripts/build-binaries.ts linux-x64",
|
|
15
|
-
"build:linux-arm64": "bun scripts/build-binaries.ts linux-arm64",
|
|
16
|
-
"build:darwin-x64": "bun scripts/build-binaries.ts darwin-x64",
|
|
17
|
-
"build:darwin-arm64": "bun scripts/build-binaries.ts darwin-arm64",
|
|
18
|
-
"build:windows-x64": "bun scripts/build-binaries.ts windows-x64",
|
|
19
|
-
"build:
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
"ccc",
|
|
30
|
-
"
|
|
31
|
-
"claude",
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
"
|
|
49
|
-
"
|
|
50
|
-
"
|
|
51
|
-
"
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
"@
|
|
60
|
-
"@
|
|
61
|
-
"@
|
|
62
|
-
"@types/
|
|
63
|
-
"@types/
|
|
64
|
-
"@
|
|
65
|
-
"@xterm/
|
|
66
|
-
"
|
|
67
|
-
"aedes": "^0.
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
"
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
"@ngrok/ngrok-linux-
|
|
82
|
-
"@ngrok/ngrok-
|
|
83
|
-
"@ngrok/ngrok-darwin-
|
|
84
|
-
"@ngrok/ngrok-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@naarang/ccc",
|
|
3
|
+
"version": "2.1.1-beta.2",
|
|
4
|
+
"description": "Code Chat Connect - Control Claude Code from your mobile device",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"ccc": "bin/ccc.cjs"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"dev": "bun src/index.ts",
|
|
12
|
+
"build": "bun scripts/build-dist.ts",
|
|
13
|
+
"build:compile": "bun scripts/build-binaries.ts",
|
|
14
|
+
"build:linux-x64": "bun scripts/build-binaries.ts linux-x64",
|
|
15
|
+
"build:linux-arm64": "bun scripts/build-binaries.ts linux-arm64",
|
|
16
|
+
"build:darwin-x64": "bun scripts/build-binaries.ts darwin-x64",
|
|
17
|
+
"build:darwin-arm64": "bun scripts/build-binaries.ts darwin-arm64",
|
|
18
|
+
"build:windows-x64": "bun scripts/build-binaries.ts windows-x64",
|
|
19
|
+
"build:all": "bun scripts/build-binaries.ts",
|
|
20
|
+
"clean": "rm -rf dist binaries",
|
|
21
|
+
"type-check": "tsc --noEmit",
|
|
22
|
+
"setup": "bun install",
|
|
23
|
+
"test:tools": "bun run scripts/test-claude-tools.ts",
|
|
24
|
+
"prepublishOnly": "bun run build",
|
|
25
|
+
"postinstall": "node scripts/postinstall.cjs || true"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"ccc",
|
|
29
|
+
"ccc-ui",
|
|
30
|
+
"claude",
|
|
31
|
+
"claude-code",
|
|
32
|
+
"mqtt",
|
|
33
|
+
"chat",
|
|
34
|
+
"mobile",
|
|
35
|
+
"ai",
|
|
36
|
+
"assistant",
|
|
37
|
+
"cli",
|
|
38
|
+
"bun"
|
|
39
|
+
],
|
|
40
|
+
"author": "Vishal",
|
|
41
|
+
"license": "UNLICENSED",
|
|
42
|
+
"private": false,
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public"
|
|
45
|
+
},
|
|
46
|
+
"files": [
|
|
47
|
+
"dist",
|
|
48
|
+
"bin",
|
|
49
|
+
"scripts",
|
|
50
|
+
"README.md",
|
|
51
|
+
"LICENSE"
|
|
52
|
+
],
|
|
53
|
+
"preferGlobal": true,
|
|
54
|
+
"engines": {
|
|
55
|
+
"bun": ">=1.0.0"
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"@ngrok/ngrok": "^1.5.2",
|
|
59
|
+
"@sentry/bun": "^10.34.0",
|
|
60
|
+
"@seriousme/opifex": "^1.11.2",
|
|
61
|
+
"@types/bun": "^1.3.2",
|
|
62
|
+
"@types/qrcode-terminal": "^0.12.2",
|
|
63
|
+
"@types/ws": "^8.18.1",
|
|
64
|
+
"@xterm/addon-fit": "^0.10.0",
|
|
65
|
+
"@xterm/xterm": "^5.5.0",
|
|
66
|
+
"aedes": "^0.51.3",
|
|
67
|
+
"aedes-server-factory": "^0.2.1",
|
|
68
|
+
"bun-pty": "^0.4.2",
|
|
69
|
+
"expo-server-sdk": "^4.0.0",
|
|
70
|
+
"figlet": "^1.9.3",
|
|
71
|
+
"mqtt": "^5.14.1",
|
|
72
|
+
"node-gyp": "11.4.2",
|
|
73
|
+
"qrcode-terminal": "^0.12.0",
|
|
74
|
+
"ws": "^8.18.3"
|
|
75
|
+
},
|
|
76
|
+
"devDependencies": {
|
|
77
|
+
"typescript": "^5"
|
|
78
|
+
},
|
|
79
|
+
"optionalDependencies": {
|
|
80
|
+
"@ngrok/ngrok-linux-x64-gnu": "1.6.0",
|
|
81
|
+
"@ngrok/ngrok-linux-arm64-gnu": "1.6.0",
|
|
82
|
+
"@ngrok/ngrok-darwin-x64": "1.6.0",
|
|
83
|
+
"@ngrok/ngrok-darwin-arm64": "1.6.0",
|
|
84
|
+
"@ngrok/ngrok-win32-x64-msvc": "1.6.0"
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -61,14 +61,8 @@ const targets = [
|
|
|
61
61
|
ngrokLib: 'ngrok.win32-x64-msvc.node',
|
|
62
62
|
ngrokPkg: '@ngrok/ngrok-win32-x64-msvc',
|
|
63
63
|
},
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
target: 'bun-windows-arm64',
|
|
67
|
-
outfile: 'ccc-windows-arm64.exe',
|
|
68
|
-
ptyLib: 'rust_pty_arm64.dll',
|
|
69
|
-
ngrokLib: 'ngrok.win32-arm64-msvc.node',
|
|
70
|
-
ngrokPkg: '@ngrok/ngrok-win32-arm64-msvc',
|
|
71
|
-
},
|
|
64
|
+
// NOTE: windows-arm64 is not supported by Bun's compile target (no bun-windows-aarch64)
|
|
65
|
+
// Re-enable when Bun adds support: https://github.com/oven-sh/bun/issues/9824
|
|
72
66
|
];
|
|
73
67
|
|
|
74
68
|
// Parse command line arguments
|