@cline/core 0.0.85 → 0.0.86-nightly.1790303239

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.
@@ -1,5 +1,5 @@
1
- import{createRequire as n0}from"node:module";var s0=n0(import.meta.url);import{homedir as y2}from"node:os";import{claimHubDaemonProcess as b2}from"@cline/shared";import{setHomeDirIfUnset as h2}from"@cline/shared/storage";import{createSessionId as N2,isHubProtocolCompatible as K2,resolveClineBuildEnv as W2,resolveHubCommandTimeoutMs as G2}from"@cline/shared";import q2 from"ws";var $0="session_not_found";class v extends Error{sessionId;code="session_not_found";constructor(J,Q){super(Q??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as g1}from"node:child_process";import{closeSync as T1,mkdirSync as I1,openSync as P1,readFileSync as w1,unlinkSync as H1}from"node:fs";import{basename as k1,dirname as y1,join as b1}from"node:path";import{fileURLToPath as h1}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as m1,isHubDaemonProcess as v1,resolveClineBuildEnv as R0,withResolvedClineBuildEnv as u1}from"@cline/shared";import{createHash as d0,randomBytes as a0}from"node:crypto";import{mkdir as p,open as X0,readFile as N0,rename as o0,rm as T,writeFile as r0}from"node:fs/promises";import{dirname as K0,join as l}from"node:path";import{isHubProtocolCompatible as e0}from"@cline/shared";import{resolveClineDataDir as _,resolveClineDir as d2}from"@cline/shared/storage";var g={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.85",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var J1="CLINE_HUB_DISCOVERY_PATH",Q1="CLINE_HUB_BUILD_ID",Z1="CLINE_HUB_BUILD_EPOCH_MS",$1=30000,X1=15000,j0=100;function j1(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function z1(J){return d0("sha256").update(J).digest("hex").slice(0,12)}function V1(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function z0(J){return new Promise((Q)=>setTimeout(Q,J))}function Y1(J){return`${J}.lock`}async function N1(J){try{let Q=JSON.parse(await N0(l(J,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function u(J){await T(J,{recursive:!0,force:!0}).catch(()=>{return})}function C(){let J=process.env[Q1]?.trim();if(J)return J;return"sdk-v1-7a06925efdddafd91fa32d8c54bdc4f26c316a2e7a7db1f707c69264416f8117".trim()||`source-${String(g.version)}`}function K1(){let J=Number(process.env[Z1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1790064761572)?1790064761572:void 0}function I(J,Q=C()){let Z=e0(J);if(!Z.compatible)return Z;let $=J.buildId?.trim();if(!$)return{compatible:!1,reason:"missing_build"};if($!==Q)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function V0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function Y0(J){let Q=J?.trim().split(/[-+]/,1)[0];if(!Q)return;let Z=Q.split(".").map(($)=>Number($));if(Z.length===0||Z.some(($)=>!Number.isInteger($)||$<0))return;return Z}function W1(J,Q){for(let Z=0;Z<Math.max(J.length,Q.length);Z++){let $=J[Z]??0,X=Q[Z]??0;if($!==X)return $<X?-1:1}return 0}function W0(J,Q){let Z=J.buildId?.trim(),$=Q.buildId?.trim();if(Z&&$&&Z===$)return 0;let X=V0(J.buildEpochMs),j=V0(Q.buildEpochMs);if(X!==void 0&&j!==void 0&&X!==j)return X<j?-1:1;let V=Y0(J.coreVersion),N=Y0(Q.coreVersion);if(V&&N){let Y=W1(V,N);if(Y!==0)return Y}if(Z&&$&&Z!==$)return Z<$?-1:1;return 0}function G0(){return{buildId:C(),buildEpochMs:K1(),coreVersion:String(g.version)}}function P(J,Q){let Z=Q?.self??G0(),$=I(J,Z.buildId??"");if($.compatible)return!0;if($.reason!=="build_mismatch"&&$.reason!=="missing_build")return!1;return W0(Z,J)<=0}function q0(J=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${z1(J)}`,Z=process.env[J1]?.trim()||l(_(),"locks","hub","owners",`${j1(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}async function O(J){try{let Q=JSON.parse(await N0(J,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function F0(J,Q){await c(J,async()=>{let Z=K0(J);await p(Z,{recursive:!0});let $=`${J}.${process.pid}.${a0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(Q,null,2)}
2
- `,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,await o0($,J);let j;try{j=await X0(Z,"r"),await j.sync()}catch{}finally{await j?.close().catch(()=>{return})}}catch(j){throw await X?.close().catch(()=>{return}),await T($,{force:!0}).catch(()=>{return}),j}})}async function x(J){await c(J,async()=>{await T(J,{force:!0}).catch(()=>{return})})}async function L0(J,Q){return await c(J,async()=>{if((await O(J))?.hubId!==Q)return!1;return await T(J,{force:!0}),!0})}async function B0(J,Q,Z){let $=Y1(J);await p(K0($),{recursive:!0});let X=Date.now()+X1;while(!0){try{await p($,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let N=await N1($);if(!N){if(Date.now()>=X){await u($);continue}await z0(j0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!V1(N.pid)||Y>$1){await u($);continue}if(Date.now()>=X)throw Error(`Timed out waiting for hub ${Q} lock ${$}`);await z0(j0);continue}try{return await r0(l($,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
- `,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?G1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function G1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as q1,CLINE_HUB_PORT as F1,resolveClineBuildEnv as L1}from"@cline/shared";var B1="CLINE_HUB_HOST",O1="CLINE_HUB_PORT",A1="CLINE_HUB_PATHNAME",U1="127.0.0.1",M1=F1,f1="/hub";function M0(J){return L1(J)==="development"?q1:M1}function C1(J={}){return(J.env??process.env)[B1]?.trim()||U1}function x1(J={}){let Z=(J.env??process.env)[O1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function _1(J={}){return(J.env??process.env)[A1]?.trim()||f1}function f0(J={},Q={}){return{host:J.host??C1(Q),port:J.port??x1(Q),pathname:J.pathname??_1(Q)}}import{join as D1}from"node:path";import{processWorkspaceInfo as Q4}from"@cline/shared";import $4 from"simple-git";var R1="shared:cline",S1="CLINE_HUB_DISCOVERY_PATH",E1="hub-production";function D(J=R1){return q0(`${J}@${C()}`)}function H(){return{ownerId:E1,discoveryPath:process.env[S1]?.trim()||D1(_(),"locks","hub","production.json")}}var p1=8000,l1=200,C0=3000,c1=100,i1=[100,250,500,1000,2000],n1="--cline-hub-daemon",s1=3,t1=60000,x0=new Map;function d1(J,Q=Date.now()){let Z=x0.get(J);if(!Z||Q-Z.windowStartedAt>t1)return x0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=s1}function a1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function o1(){try{let J=b1(_(),"logs","hub-daemon.log");return I1(y1(J),{recursive:!0}),{fd:P1(J,"a"),logPath:J}}catch{return}}function r1(){return R0()==="production"?H():D()}function R(J){return P(J)}function e1(J){try{let Q=JSON.parse(w1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{H1(`${J}.superseded`)}catch{}}function _0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function S(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function D0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await S(J))?.url)return!0;await new Promise((X)=>setTimeout(X,c1))}return!1}async function s(J,Q){if(!d1(J.url))return!1;await E(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await D0(J.url,C0);if(!Z&&J.pid&&J2(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await D0(J.url,C0)}if(Z)await x(Q).catch(()=>{return});return Z}function J2(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function Q2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await E(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await Q2(J)){if(Z)await E(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await E(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Z2(J){if(R0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await x(Q.discoveryPath).catch(()=>{return})}function $2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return h1(new URL(`./entry.${J}`,import.meta.url))}function X2(J,Q){let Z=$2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=k1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[n1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...a1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...u1(process.env),CLINE_NO_INTERACTIVE:"1",[m1]:"1"}}}function j2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function z2(J,Q={}){if(v1())return;let Z=X2(J,Q),$=o1();try{g1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)T1($.fd)}}async function V2(J,Q={}){for(let Z=0;;Z++)try{z2(J,Q);return}catch($){let X=i1[Z];if(!j2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function Y2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Z2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:e1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await S(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await x(J.discoveryPath).catch(()=>{return})}}let z=await S(j);if(z?.url){let W=_0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let i0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,i0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await V2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+p1;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await S(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await S(j);if(G?.url&&!R(G)){let L=_0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,l1))}throw Error("Timed out waiting for detached hub startup.")}async function k(J,Q={}){let Z=r1();return await O0(Z.discoveryPath,async()=>Y2(Z,J,Q))}function F2(){return W2()==="production"?H():D()}function L2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function P0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return P0(J.data);return String(J)}function B2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function S0(J){let Q=J,Z=B2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function E0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,O2="cline-hub-auth.",w0=new Map,H0=new Set,A2=3000;var a="Hub connection closed",U2=250,M2=5000,g0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function f2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?w0.get($):void 0}function C2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!C2(J))return;let Q=new URL(k0(J));return Q.search="",Q.hash="",Q.toString()}function T0(J){let Q=J0(J);return!!Q&&H0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(H0.add(Z),Q?.trim())w0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=E0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new q2(J.toString(),{headers:{...X}}):new(L2())(J.toString(),Q?[`${O2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=E0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:S0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(P0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=S0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();$?.beforeDispatch?.();let j=N2("hubreq_"),V=G2(J,$?.timeoutMs),N=new Promise((K,z)=>{let F=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;z(new o(J,"hub_command_timeout",`Hub command ${J} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(B)=>{if(F)clearTimeout(F);K(B)},reject:(B)=>{if(F)clearTimeout(F);z(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:Q}})}catch(K){throw this.pendingReplies.delete(j),K}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let K=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new v(K,Y.error.message)}throw new o(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!T0(this.currentUrl)||!f2(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let J=Math.min(U2*2**this.reconnectAttempt,M2),Q=Math.round(J*(1-g0)+Math.random()*J*g0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!T0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",a);for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Q){let Z=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Q)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Q?{sessionId:Q}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(J,Q){let Z=this.subscriptionKeyForSessionId(J),$=(this.subscriptionCounts.get(Z)??0)+Q;if($<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Z,$),Q>0&&$===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??d}subscriptionSessionIdFromKey(J){return J===d?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Q=J.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve(J.envelope);return}case"event":{let Q=J.envelope.sequence;if(typeof Q==="number"){let Z=J.envelope.sessionId?.trim();for(let $ of[d,Z]){if(!$||!this.subscriptionCounts.has($))continue;let X=this.lastEventSequenceByKey.get($)??0;if(Q>X)this.lastEventSequenceByKey.set($,Q)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==J.envelope.sessionId?.trim())continue;Z.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function k0(J){let Q=new URL(J);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function A(J,Q){let Z=new Q0({url:J,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function r(J,Q){let Z=k0(J),$=await w(Z,{authToken:Q?.authToken});if(!$)return{status:"unreachable",url:Z};if(Q?.requireCurrentBuild){let X=C(),j=I($,X);if(!j.compatible&&!P($))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!K2($).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await A(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function x2(J){let Q=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Z=0,$=new Set;for(let X of Q){if(!X||typeof X!=="object")continue;let j=X.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let N=V&&typeof V==="object"?V.clientId:void 0;if(typeof N==="string"&&N.trim())$.add(N)}}return{activeSessionCount:Z,participantClientCount:$.size}}async function t(J,Q,Z){let $=new Q0({url:J,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let X=await $.command("session.list",{limit:500},void 0,{timeoutMs:A2});return x2(X.payload)}finally{await $.dispose().catch(()=>{return})}}async function _2(J,Q,Z){try{return(await t(J,Q,Z)).activeSessionCount===0}catch{return!1}}async function D2(J,Q){let Z=`${J.discoveryPath}.superseded`,$=await O(Z);if(!$?.url||!$.authToken)return;let X=await r($.url,{authToken:$.authToken});if(X.status!=="compatible")return;if(await _2(X.url,$.authToken,Q))return;return y(X.url,$.authToken)}async function R2(J={}){if(J.endpoint?.trim()){let X=await r(J.endpoint);return X.status==="compatible"?X.url:void 0}let Q=F2(),Z=await O(Q.discoveryPath);if(!Z?.url)return await D2(Q,J);let $=await r(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if($.status==="compatible")return y($.url,Z.authToken);if($.status==="protocol_mismatch")await x(Q.discoveryPath).catch(()=>{return});return}async function I0(J={}){let Q=await R2(J);if(Q&&await A(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Q;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch{return}}async function E(J,Q,Z,$){let X=new URL(J),j=Q?.trim()||e(X);if(X.protocol==="ws:")X.protocol="http:";else if(X.protocol==="wss:")X.protocol="https:";if(X.pathname="/drain",X.hash="",Z)X.searchParams.set("reason",Z);if($?.off)X.searchParams.set("off","1");return(await fetch(X,{method:"POST",headers:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b(J,Q){let Z=new URL(J),$=Q?.trim()||e(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:$?{authorization:`Bearer ${$}`}:void 0})).ok}import{spawn as S2}from"node:child_process";import{userInfo as E2}from"node:os";import{basename as g2,delimiter as m}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",b0="__CLINE_SIDECAR_PATH_END__",h0=5000,T2=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${b0}"'`,y0="CLINE_SIDECAR_SKIP_SHELL_PATH";function m0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function I2(J,Q){try{let Z=E2().shell?.trim();if(Z)return Z}catch{}return Q.SHELL?.trim()||m0(J)}function P2(J,Q){let Z=g2(J);if(Z==="csh"||Z==="tcsh")return{args:["-c",Q],argv0:`-${Z}`};return{args:["-i","-l","-c",Q]}}function w2(J){let Q=J.indexOf(Z0);if(Q===-1)return;let Z=J.indexOf(b0,Q);if(Z===-1)return;let $=J.slice(Q+Z0.length,Z).trim();return $.length>0?$:void 0}function H2(J,Q){let Z=[...J.split(m),...Q.split(m)].map(($)=>$.trim()).filter(($)=>$.length>0);return Array.from(new Set(Z)).join(m)}function k2(J,Q=h0){return new Promise((Z)=>{let $=P2(J,T2),X=S2(J,$.args,{argv0:$.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),j="",V=0,N=()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}},Y=!1,K=(F)=>{if(Y)return;Y=!0,clearTimeout(z),X.stdout?.destroy(),N(),Z(F)},z=setTimeout(()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}K(void 0)},Q);X.stdout?.on("data",(F)=>{if(Y)return;if(V+=F.length,V>65536){K(void 0);return}j+=F.toString("utf8")}),X.on("error",()=>K(void 0)),X.on("close",()=>K(w2(j)))})}async function v0(J){let Q=J?.platform??process.platform,Z=J?.env??process.env;if(Q==="win32")return{status:"skipped",reason:"windows"};if(Z[y0]?.trim())return{status:"skipped",reason:y0};let $=J?.userShell??I2(Q,Z),X=J?.fallbackShell??m0(Q),j=J?.timeoutMs??h0,V=$===X?[[$,j]]:[[$,j],[X,j/2]];for(let[N,Y]of V){let K=await k2(N,Y);if(!K)continue;let z=H2(K,Z.PATH??"");return Z.PATH=z,{status:"applied",pathEntries:z.split(m).length,shell:N}}return{status:"failed",shell:$}}var u0={readHubDiscovery:O,clearHubDiscoveryIfOwned:L0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:b2,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:v0,setHomeDirIfUnset:h2,homeDir:y2,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function p0(J,Q){let Z=J.indexOf(Q);return(Z>=0?J[Z+1]:void 0)?.trim()||void 0}function l0(J,Q){let Z=p0(J,"--discovery-path");if(!Z)throw Error("--discovery-path is required for remote Hub management");return Q.env.CLINE_HUB_DISCOVERY_PATH=Z,Z}async function m2(J=process.argv,Q=u0){Q.setHomeDirIfUnset(Q.homeDir()),await Q.ensureLoginShellPath();let Z=p0(J,"--cwd")??Q.cwd();l0(J,Q);let $=await Q.ensureDetachedHubServer(Z,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});Q.writeOutput(`${JSON.stringify({...$,cwd:Z,platform:process.platform,arch:process.arch})}
4
- `)}async function c0(J=process.argv,Q=u0){if(J.includes("--remote-hub-stop")){let Z=l0(J,Q),$=await Q.readHubDiscovery(Z);if($&&typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)try{Q.probeProcess($.pid)}catch(X){if(X?.code==="ESRCH")return await Q.clearHubDiscoveryIfOwned(Z,$.hubId),!0}if($&&!await Q.requestHubShutdown($.url,$.authToken))throw Error("Remote Hub shutdown failed");return!0}if(J.includes("--remote-hub-ensure"))return await m2(J,Q),!0;if(Q.claimHubDaemonProcess())return await Q.loadHubDaemon(),!0;return!1}(async()=>{if(!await c0())throw Error("A remote helper command is required")})().catch((J)=>{process.stderr.write(`${J instanceof Error?J.message:String(J)}
1
+ import{createRequire as s0}from"node:module";var d0=s0(import.meta.url);import{homedir as y2}from"node:os";import{claimHubDaemonProcess as b2}from"@cline/shared";import{setHomeDirIfUnset as h2}from"@cline/shared/storage";import{createSessionId as N2,isHubProtocolCompatible as K2,resolveClineBuildEnv as W2,resolveHubCommandTimeoutMs as G2}from"@cline/shared";import q2 from"ws";var $0="session_not_found";class v extends Error{sessionId;code="session_not_found";constructor(J,Q){super(Q??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as P1}from"node:child_process";import{closeSync as I1,mkdirSync as T1,openSync as w1,readFileSync as H1,unlinkSync as k1}from"node:fs";import{basename as y1,dirname as b1,join as h1}from"node:path";import{fileURLToPath as m1}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as v1,isHubDaemonProcess as u1,resolveClineBuildEnv as E0,withResolvedClineBuildEnv as p1}from"@cline/shared";import{createHash as a0,randomBytes as o0}from"node:crypto";import{mkdir as p,open as X0,readFile as N0,rename as r0,rm as P,writeFile as e0}from"node:fs/promises";import{dirname as K0,join as l}from"node:path";import{isHubProtocolCompatible as J1}from"@cline/shared";import{resolveClineDataDir as _,resolveClineDir as t2}from"@cline/shared/storage";var g={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.86-nightly.1790303239",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var Q1="CLINE_HUB_DISCOVERY_PATH",Z1="CLINE_HUB_BUILD_ID",$1="CLINE_HUB_BUILD_EPOCH_MS",X1=30000,j1=15000,j0=100;function z1(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function V1(J){return a0("sha256").update(J).digest("hex").slice(0,12)}function Y1(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function z0(J){return new Promise((Q)=>setTimeout(Q,J))}function N1(J){return`${J}.lock`}async function K1(J){try{let Q=JSON.parse(await N0(l(J,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function u(J){await P(J,{recursive:!0,force:!0}).catch(()=>{return})}function x(){let J=process.env[Z1]?.trim();if(J)return J;return"sdk-v1-4729c27f0fc26c26414b80b44ca4c07412b582c17389eb6b8850c1d86602faf2".trim()||`source-${String(g.version)}`}function W1(){let J=Number(process.env[$1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1790303265252)?1790303265252:void 0}function I(J,Q=x()){let Z=J1(J);if(!Z.compatible)return Z;let $=J.buildId?.trim();if(!$)return{compatible:!1,reason:"missing_build"};if($!==Q)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function V0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function Y0(J){let Q=J?.trim().split(/[-+]/,1)[0];if(!Q)return;let Z=Q.split(".").map(($)=>Number($));if(Z.length===0||Z.some(($)=>!Number.isInteger($)||$<0))return;return Z}function G1(J,Q){for(let Z=0;Z<Math.max(J.length,Q.length);Z++){let $=J[Z]??0,X=Q[Z]??0;if($!==X)return $<X?-1:1}return 0}function W0(J,Q){let Z=J.buildId?.trim(),$=Q.buildId?.trim();if(Z&&$&&Z===$)return 0;let X=V0(J.buildEpochMs),j=V0(Q.buildEpochMs);if(X!==void 0&&j!==void 0&&X!==j)return X<j?-1:1;let V=Y0(J.coreVersion),N=Y0(Q.coreVersion);if(V&&N){let Y=G1(V,N);if(Y!==0)return Y}if(Z&&$&&Z!==$)return Z<$?-1:1;return 0}function G0(){return{buildId:x(),buildEpochMs:W1(),coreVersion:String(g.version)}}function T(J,Q){let Z=Q?.self??G0(),$=I(J,Z.buildId??"");if($.compatible)return!0;if($.reason!=="build_mismatch"&&$.reason!=="missing_build")return!1;return W0(Z,J)<=0}function q0(J=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${V1(J)}`,Z=process.env[Q1]?.trim()||l(_(),"locks","hub","owners",`${z1(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}async function O(J){try{let Q=JSON.parse(await N0(J,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function F0(J,Q){await c(J,async()=>{let Z=K0(J);await p(Z,{recursive:!0});let $=`${J}.${process.pid}.${o0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(Q,null,2)}
2
+ `,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,await r0($,J);let j;try{j=await X0(Z,"r"),await j.sync()}catch{}finally{await j?.close().catch(()=>{return})}}catch(j){throw await X?.close().catch(()=>{return}),await P($,{force:!0}).catch(()=>{return}),j}})}async function C(J){await c(J,async()=>{await P(J,{force:!0}).catch(()=>{return})})}async function L0(J,Q){return await c(J,async()=>{if((await O(J))?.hubId!==Q)return!1;return await P(J,{force:!0}),!0})}async function B0(J,Q,Z){let $=N1(J);await p(K0($),{recursive:!0});let X=Date.now()+j1;while(!0){try{await p($,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let N=await K1($);if(!N){if(Date.now()>=X){await u($);continue}await z0(j0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!Y1(N.pid)||Y>X1){await u($);continue}if(Date.now()>=X)throw Error(`Timed out waiting for hub ${Q} lock ${$}`);await z0(j0);continue}try{return await e0(l($,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
+ `,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?q1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function q1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as F1,CLINE_HUB_PORT as L1,resolveClineBuildEnv as B1}from"@cline/shared";var O1="CLINE_HUB_HOST",A1="CLINE_HUB_PORT",U1="CLINE_HUB_PATHNAME",M1="127.0.0.1",f1=L1,x1="/hub";function M0(J){return B1(J)==="development"?F1:f1}function C1(J={}){return(J.env??process.env)[O1]?.trim()||M1}function _1(J={}){let Z=(J.env??process.env)[A1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function D1(J={}){return(J.env??process.env)[U1]?.trim()||x1}function f0(J={},Q={}){return{host:J.host??C1(Q),port:J.port??_1(Q),pathname:J.pathname??D1(Q)}}import{join as R1}from"node:path";import{processWorkspaceInfo as Q6}from"@cline/shared";import $6 from"simple-git";var E1="shared:cline",S1="CLINE_HUB_DISCOVERY_PATH",g1="hub-production";function D(J=E1){return q0(`${J}@${x()}`)}function H(){return{ownerId:g1,discoveryPath:process.env[S1]?.trim()||R1(_(),"locks","hub","production.json")}}var x0=15000,l1=200,C0=3000,c1=100,i1=[100,250,500,1000,2000],n1="--cline-hub-daemon",s1=3,d1=60000,_0=new Map;function t1(J,Q=Date.now()){let Z=_0.get(J);if(!Z||Q-Z.windowStartedAt>d1)return _0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=s1}function a1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function o1(){try{let J=h1(_(),"logs","hub-daemon.log");return T1(b1(J),{recursive:!0}),{fd:w1(J,"a"),logPath:J}}catch{return}}function r1(){return E0()==="production"?H():D()}function R(J){return T(J)}function e1(J){try{let Q=JSON.parse(H1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{k1(`${J}.superseded`)}catch{}}function D0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function E(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function R0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await E(J))?.url)return!0;await new Promise((X)=>setTimeout(X,c1))}return!1}async function s(J,Q){if(!t1(J.url))return!1;await S(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await R0(J.url,C0);if(!Z&&J.pid&&J2(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await R0(J.url,C0)}if(Z)await C(Q).catch(()=>{return});return Z}function J2(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function Q2(J){try{return(await d(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await S(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await Q2(J)){if(Z)await S(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await S(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Z2(J){if(E0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await C(Q.discoveryPath).catch(()=>{return})}function $2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return m1(new URL(`./entry.${J}`,import.meta.url))}function X2(J,Q){let Z=$2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=y1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[n1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...a1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...p1(process.env),CLINE_NO_INTERACTIVE:"1",[v1]:"1"}}}function j2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function z2(J,Q={}){if(u1())return;let Z=X2(J,Q),$=o1();try{P1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)I1($.fd)}}async function V2(J,Q={}){for(let Z=0;;Z++)try{z2(J,Q);return}catch($){let X=i1[Z];if(!j2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function Y2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Z2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:e1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await E(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await C(J.discoveryPath).catch(()=>{return})}}let z=await E(j);if(z?.url){let W=D0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let n0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,n0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await V2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+x0;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await E(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await E(j);if(G?.url&&!R(G)){let L=D0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,l1))}throw Error(`Timed out after ${x0}ms waiting for detached hub startup.`)}async function k(J,Q={}){let Z=r1();return await O0(Z.discoveryPath,async()=>Y2(Z,J,Q))}function F2(){return W2()==="production"?H():D()}function L2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function w0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return w0(J.data);return String(J)}function B2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function S0(J){let Q=J,Z=B2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function g0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var t="*",h=8000,O2="cline-hub-auth.",H0=new Map,k0=new Set,A2=3000;var a="Hub connection closed",U2=250,M2=5000,P0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function f2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?H0.get($):void 0}function x2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!x2(J))return;let Q=new URL(y0(J));return Q.search="",Q.hash="",Q.toString()}function I0(J){let Q=J0(J);return!!Q&&k0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(k0.add(Z),Q?.trim())H0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=g0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new q2(J.toString(),{headers:{...X}}):new(L2())(J.toString(),Q?[`${O2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=g0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:S0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(w0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=S0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();$?.beforeDispatch?.();let j=N2("hubreq_");$?.onDispatch?.(j);let V=G2(J,$?.timeoutMs),N=new Promise((K,z)=>{let F=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;z(new o(J,"hub_command_timeout",`Hub command ${J} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(B)=>{if(F)clearTimeout(F);K(B)},reject:(B)=>{if(F)clearTimeout(F);z(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:Q}})}catch(K){throw this.pendingReplies.delete(j),K}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let K=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new v(K,Y.error.message)}throw new o(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!I0(this.currentUrl)||!f2(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await T0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let J=Math.min(U2*2**this.reconnectAttempt,M2),Q=Math.round(J*(1-P0)+Math.random()*J*P0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!I0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await T0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",a);for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Q){let Z=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Q)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Q?{sessionId:Q}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(J,Q){let Z=this.subscriptionKeyForSessionId(J),$=(this.subscriptionCounts.get(Z)??0)+Q;if($<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Z,$),Q>0&&$===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??t}subscriptionSessionIdFromKey(J){return J===t?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Q=J.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve(J.envelope);return}case"event":{let Q=J.envelope.sequence;if(typeof Q==="number"){let Z=J.envelope.sessionId?.trim();for(let $ of[t,Z]){if(!$||!this.subscriptionCounts.has($))continue;let X=this.lastEventSequenceByKey.get($)??0;if(Q>X)this.lastEventSequenceByKey.set($,Q)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==J.envelope.sessionId?.trim())continue;Z.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function y0(J){let Q=new URL(J);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function A(J,Q){let Z=new Q0({url:J,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function r(J,Q){let Z=y0(J),$=await w(Z,{authToken:Q?.authToken});if(!$)return{status:"unreachable",url:Z};if(Q?.requireCurrentBuild){let X=x(),j=I($,X);if(!j.compatible&&!T($))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!K2($).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await A(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function C2(J){let Q=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Z=0,$=new Set;for(let X of Q){if(!X||typeof X!=="object")continue;let j=X.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let N=V&&typeof V==="object"?V.clientId:void 0;if(typeof N==="string"&&N.trim())$.add(N)}}return{activeSessionCount:Z,participantClientCount:$.size}}async function d(J,Q,Z){let $=new Q0({url:J,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let X=await $.command("session.list",{limit:500},void 0,{timeoutMs:A2});return C2(X.payload)}finally{await $.dispose().catch(()=>{return})}}async function _2(J,Q,Z){try{return(await d(J,Q,Z)).activeSessionCount===0}catch{return!1}}async function D2(J,Q){let Z=`${J.discoveryPath}.superseded`,$=await O(Z);if(!$?.url||!$.authToken)return;let X=await r($.url,{authToken:$.authToken});if(X.status!=="compatible")return;if(await _2(X.url,$.authToken,Q))return;return y(X.url,$.authToken)}async function R2(J={}){if(J.endpoint?.trim()){let X=await r(J.endpoint);return X.status==="compatible"?X.url:void 0}let Q=F2(),Z=await O(Q.discoveryPath);if(!Z?.url)return await D2(Q,J);let $=await r(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if($.status==="compatible")return y($.url,Z.authToken);if($.status==="protocol_mismatch")await C(Q.discoveryPath).catch(()=>{return});return}async function T0(J={}){let Q=await R2(J);if(Q&&await A(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Q;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch(Z){J.onStartupError?.(Z);return}}async function S(J,Q,Z,$){let X=new URL(J),j=Q?.trim()||e(X);if(X.protocol==="ws:")X.protocol="http:";else if(X.protocol==="wss:")X.protocol="https:";if(X.pathname="/drain",X.hash="",Z)X.searchParams.set("reason",Z);if($?.off)X.searchParams.set("off","1");return(await fetch(X,{method:"POST",headers:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b(J,Q){let Z=new URL(J),$=Q?.trim()||e(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:$?{authorization:`Bearer ${$}`}:void 0})).ok}import{spawn as E2}from"node:child_process";import{userInfo as S2}from"node:os";import{basename as g2,delimiter as m}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",h0="__CLINE_SIDECAR_PATH_END__",m0=5000,P2=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${h0}"'`,b0="CLINE_SIDECAR_SKIP_SHELL_PATH";function v0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function I2(J,Q){try{let Z=S2().shell?.trim();if(Z)return Z}catch{}return Q.SHELL?.trim()||v0(J)}function T2(J,Q){let Z=g2(J);if(Z==="csh"||Z==="tcsh")return{args:["-c",Q],argv0:`-${Z}`};return{args:["-i","-l","-c",Q]}}function w2(J){let Q=J.indexOf(Z0);if(Q===-1)return;let Z=J.indexOf(h0,Q);if(Z===-1)return;let $=J.slice(Q+Z0.length,Z).trim();return $.length>0?$:void 0}function H2(J,Q){let Z=[...J.split(m),...Q.split(m)].map(($)=>$.trim()).filter(($)=>$.length>0);return Array.from(new Set(Z)).join(m)}function k2(J,Q=m0){return new Promise((Z)=>{let $=T2(J,P2),X=E2(J,$.args,{argv0:$.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),j="",V=0,N=()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}},Y=!1,K=(F)=>{if(Y)return;Y=!0,clearTimeout(z),X.stdout?.destroy(),N(),Z(F)},z=setTimeout(()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}K(void 0)},Q);X.stdout?.on("data",(F)=>{if(Y)return;if(V+=F.length,V>65536){K(void 0);return}j+=F.toString("utf8")}),X.on("error",()=>K(void 0)),X.on("close",()=>K(w2(j)))})}async function u0(J){let Q=J?.platform??process.platform,Z=J?.env??process.env;if(Q==="win32")return{status:"skipped",reason:"windows"};if(Z[b0]?.trim())return{status:"skipped",reason:b0};let $=J?.userShell??I2(Q,Z),X=J?.fallbackShell??v0(Q),j=J?.timeoutMs??m0,V=$===X?[[$,j]]:[[$,j],[X,j/2]];for(let[N,Y]of V){let K=await k2(N,Y);if(!K)continue;let z=H2(K,Z.PATH??"");return Z.PATH=z,{status:"applied",pathEntries:z.split(m).length,shell:N}}return{status:"failed",shell:$}}var p0={readHubDiscovery:O,clearHubDiscoveryIfOwned:L0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:b2,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:u0,setHomeDirIfUnset:h2,homeDir:y2,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function l0(J,Q){let Z=J.indexOf(Q);return(Z>=0?J[Z+1]:void 0)?.trim()||void 0}function c0(J,Q){let Z=l0(J,"--discovery-path");if(!Z)throw Error("--discovery-path is required for remote Hub management");return Q.env.CLINE_HUB_DISCOVERY_PATH=Z,Z}async function m2(J=process.argv,Q=p0){Q.setHomeDirIfUnset(Q.homeDir()),await Q.ensureLoginShellPath();let Z=l0(J,"--cwd")??Q.cwd();c0(J,Q);let $=await Q.ensureDetachedHubServer(Z,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});Q.writeOutput(`${JSON.stringify({...$,cwd:Z,platform:process.platform,arch:process.arch})}
4
+ `)}async function i0(J=process.argv,Q=p0){if(J.includes("--remote-hub-stop")){let Z=c0(J,Q),$=await Q.readHubDiscovery(Z);if($&&typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)try{Q.probeProcess($.pid)}catch(X){if(X?.code==="ESRCH")return await Q.clearHubDiscoveryIfOwned(Z,$.hubId),!0}if($&&!await Q.requestHubShutdown($.url,$.authToken))throw Error("Remote Hub shutdown failed");return!0}if(J.includes("--remote-hub-ensure"))return await m2(J,Q),!0;if(Q.claimHubDaemonProcess())return await Q.loadHubDaemon(),!0;return!1}(async()=>{if(!await i0())throw Error("A remote helper command is required")})().catch((J)=>{process.stderr.write(`${J instanceof Error?J.message:String(J)}
5
5
  `),process.exitCode=1});
@@ -1,4 +1,4 @@
1
- import{createRequire as i0}from"node:module";var n0=i0(import.meta.url);import{homedir as k2}from"node:os";import{claimHubDaemonProcess as y2}from"@cline/shared";import{setHomeDirIfUnset as b2}from"@cline/shared/storage";import{createSessionId as Y2,isHubProtocolCompatible as N2,resolveClineBuildEnv as K2,resolveHubCommandTimeoutMs as W2}from"@cline/shared";import G2 from"ws";var $0="session_not_found";class v extends Error{sessionId;code="session_not_found";constructor(J,Q){super(Q??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as S1}from"node:child_process";import{closeSync as g1,mkdirSync as T1,openSync as I1,readFileSync as P1,unlinkSync as w1}from"node:fs";import{basename as H1,dirname as k1,join as y1}from"node:path";import{fileURLToPath as b1}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as h1,isHubDaemonProcess as m1,resolveClineBuildEnv as R0,withResolvedClineBuildEnv as v1}from"@cline/shared";import{createHash as t0,randomBytes as d0}from"node:crypto";import{mkdir as p,open as X0,readFile as N0,rename as a0,rm as T,writeFile as o0}from"node:fs/promises";import{dirname as K0,join as l}from"node:path";import{isHubProtocolCompatible as r0}from"@cline/shared";import{resolveClineDataDir as _,resolveClineDir as t2}from"@cline/shared/storage";var g={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.85",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var e0="CLINE_HUB_DISCOVERY_PATH",J1="CLINE_HUB_BUILD_ID",Q1="CLINE_HUB_BUILD_EPOCH_MS",Z1=30000,$1=15000,j0=100;function X1(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function j1(J){return t0("sha256").update(J).digest("hex").slice(0,12)}function z1(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function z0(J){return new Promise((Q)=>setTimeout(Q,J))}function V1(J){return`${J}.lock`}async function Y1(J){try{let Q=JSON.parse(await N0(l(J,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function u(J){await T(J,{recursive:!0,force:!0}).catch(()=>{return})}function C(){let J=process.env[J1]?.trim();if(J)return J;return"sdk-v1-7a06925efdddafd91fa32d8c54bdc4f26c316a2e7a7db1f707c69264416f8117".trim()||`source-${String(g.version)}`}function N1(){let J=Number(process.env[Q1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1790064761572)?1790064761572:void 0}function I(J,Q=C()){let Z=r0(J);if(!Z.compatible)return Z;let $=J.buildId?.trim();if(!$)return{compatible:!1,reason:"missing_build"};if($!==Q)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function V0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function Y0(J){let Q=J?.trim().split(/[-+]/,1)[0];if(!Q)return;let Z=Q.split(".").map(($)=>Number($));if(Z.length===0||Z.some(($)=>!Number.isInteger($)||$<0))return;return Z}function K1(J,Q){for(let Z=0;Z<Math.max(J.length,Q.length);Z++){let $=J[Z]??0,X=Q[Z]??0;if($!==X)return $<X?-1:1}return 0}function W0(J,Q){let Z=J.buildId?.trim(),$=Q.buildId?.trim();if(Z&&$&&Z===$)return 0;let X=V0(J.buildEpochMs),j=V0(Q.buildEpochMs);if(X!==void 0&&j!==void 0&&X!==j)return X<j?-1:1;let V=Y0(J.coreVersion),N=Y0(Q.coreVersion);if(V&&N){let Y=K1(V,N);if(Y!==0)return Y}if(Z&&$&&Z!==$)return Z<$?-1:1;return 0}function G0(){return{buildId:C(),buildEpochMs:N1(),coreVersion:String(g.version)}}function P(J,Q){let Z=Q?.self??G0(),$=I(J,Z.buildId??"");if($.compatible)return!0;if($.reason!=="build_mismatch"&&$.reason!=="missing_build")return!1;return W0(Z,J)<=0}function q0(J=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${j1(J)}`,Z=process.env[e0]?.trim()||l(_(),"locks","hub","owners",`${X1(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}async function O(J){try{let Q=JSON.parse(await N0(J,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function F0(J,Q){await c(J,async()=>{let Z=K0(J);await p(Z,{recursive:!0});let $=`${J}.${process.pid}.${d0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(Q,null,2)}
2
- `,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,await a0($,J);let j;try{j=await X0(Z,"r"),await j.sync()}catch{}finally{await j?.close().catch(()=>{return})}}catch(j){throw await X?.close().catch(()=>{return}),await T($,{force:!0}).catch(()=>{return}),j}})}async function x(J){await c(J,async()=>{await T(J,{force:!0}).catch(()=>{return})})}async function L0(J,Q){return await c(J,async()=>{if((await O(J))?.hubId!==Q)return!1;return await T(J,{force:!0}),!0})}async function B0(J,Q,Z){let $=V1(J);await p(K0($),{recursive:!0});let X=Date.now()+$1;while(!0){try{await p($,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let N=await Y1($);if(!N){if(Date.now()>=X){await u($);continue}await z0(j0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!z1(N.pid)||Y>Z1){await u($);continue}if(Date.now()>=X)throw Error(`Timed out waiting for hub ${Q} lock ${$}`);await z0(j0);continue}try{return await o0(l($,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
- `,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?W1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function W1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as G1,CLINE_HUB_PORT as q1,resolveClineBuildEnv as F1}from"@cline/shared";var L1="CLINE_HUB_HOST",B1="CLINE_HUB_PORT",O1="CLINE_HUB_PATHNAME",A1="127.0.0.1",U1=q1,M1="/hub";function M0(J){return F1(J)==="development"?G1:U1}function f1(J={}){return(J.env??process.env)[L1]?.trim()||A1}function C1(J={}){let Z=(J.env??process.env)[B1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function x1(J={}){return(J.env??process.env)[O1]?.trim()||M1}function f0(J={},Q={}){return{host:J.host??f1(Q),port:J.port??C1(Q),pathname:J.pathname??x1(Q)}}import{join as _1}from"node:path";import{processWorkspaceInfo as J4}from"@cline/shared";import Z4 from"simple-git";var D1="shared:cline",R1="CLINE_HUB_DISCOVERY_PATH",E1="hub-production";function D(J=D1){return q0(`${J}@${C()}`)}function H(){return{ownerId:E1,discoveryPath:process.env[R1]?.trim()||_1(_(),"locks","hub","production.json")}}var u1=8000,p1=200,C0=3000,l1=100,c1=[100,250,500,1000,2000],i1="--cline-hub-daemon",n1=3,s1=60000,x0=new Map;function t1(J,Q=Date.now()){let Z=x0.get(J);if(!Z||Q-Z.windowStartedAt>s1)return x0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=n1}function d1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function a1(){try{let J=y1(_(),"logs","hub-daemon.log");return T1(k1(J),{recursive:!0}),{fd:I1(J,"a"),logPath:J}}catch{return}}function o1(){return R0()==="production"?H():D()}function R(J){return P(J)}function r1(J){try{let Q=JSON.parse(P1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{w1(`${J}.superseded`)}catch{}}function _0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function E(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function D0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await E(J))?.url)return!0;await new Promise((X)=>setTimeout(X,l1))}return!1}async function s(J,Q){if(!t1(J.url))return!1;await S(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await D0(J.url,C0);if(!Z&&J.pid&&e1(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await D0(J.url,C0)}if(Z)await x(Q).catch(()=>{return});return Z}function e1(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function J2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await S(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await J2(J)){if(Z)await S(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await S(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Q2(J){if(R0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await x(Q.discoveryPath).catch(()=>{return})}function Z2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return b1(new URL(`./entry.${J}`,import.meta.url))}function $2(J,Q){let Z=Z2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=H1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[i1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...d1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...v1(process.env),CLINE_NO_INTERACTIVE:"1",[h1]:"1"}}}function X2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function j2(J,Q={}){if(m1())return;let Z=$2(J,Q),$=a1();try{S1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)g1($.fd)}}async function z2(J,Q={}){for(let Z=0;;Z++)try{j2(J,Q);return}catch($){let X=c1[Z];if(!X2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function V2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Q2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:r1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await E(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await x(J.discoveryPath).catch(()=>{return})}}let z=await E(j);if(z?.url){let W=_0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let c0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,c0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await z2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+u1;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await E(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await E(j);if(G?.url&&!R(G)){let L=_0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,p1))}throw Error("Timed out waiting for detached hub startup.")}async function k(J,Q={}){let Z=o1();return await O0(Z.discoveryPath,async()=>V2(Z,J,Q))}function q2(){return K2()==="production"?H():D()}function F2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function P0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return P0(J.data);return String(J)}function L2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function E0(J){let Q=J,Z=L2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function S0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,B2="cline-hub-auth.",w0=new Map,H0=new Set,O2=3000;var a="Hub connection closed",A2=250,U2=5000,g0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function M2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?w0.get($):void 0}function f2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!f2(J))return;let Q=new URL(k0(J));return Q.search="",Q.hash="",Q.toString()}function T0(J){let Q=J0(J);return!!Q&&H0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(H0.add(Z),Q?.trim())w0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=S0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new G2(J.toString(),{headers:{...X}}):new(F2())(J.toString(),Q?[`${B2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=S0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:E0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(P0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=E0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();$?.beforeDispatch?.();let j=Y2("hubreq_"),V=W2(J,$?.timeoutMs),N=new Promise((K,z)=>{let F=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;z(new o(J,"hub_command_timeout",`Hub command ${J} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(B)=>{if(F)clearTimeout(F);K(B)},reject:(B)=>{if(F)clearTimeout(F);z(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:Q}})}catch(K){throw this.pendingReplies.delete(j),K}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let K=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new v(K,Y.error.message)}throw new o(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!T0(this.currentUrl)||!M2(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let J=Math.min(A2*2**this.reconnectAttempt,U2),Q=Math.round(J*(1-g0)+Math.random()*J*g0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!T0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",a);for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Q){let Z=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Q)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Q?{sessionId:Q}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(J,Q){let Z=this.subscriptionKeyForSessionId(J),$=(this.subscriptionCounts.get(Z)??0)+Q;if($<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Z,$),Q>0&&$===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??d}subscriptionSessionIdFromKey(J){return J===d?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Q=J.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve(J.envelope);return}case"event":{let Q=J.envelope.sequence;if(typeof Q==="number"){let Z=J.envelope.sessionId?.trim();for(let $ of[d,Z]){if(!$||!this.subscriptionCounts.has($))continue;let X=this.lastEventSequenceByKey.get($)??0;if(Q>X)this.lastEventSequenceByKey.set($,Q)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==J.envelope.sessionId?.trim())continue;Z.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function k0(J){let Q=new URL(J);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function A(J,Q){let Z=new Q0({url:J,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function r(J,Q){let Z=k0(J),$=await w(Z,{authToken:Q?.authToken});if(!$)return{status:"unreachable",url:Z};if(Q?.requireCurrentBuild){let X=C(),j=I($,X);if(!j.compatible&&!P($))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!N2($).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await A(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function C2(J){let Q=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Z=0,$=new Set;for(let X of Q){if(!X||typeof X!=="object")continue;let j=X.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let N=V&&typeof V==="object"?V.clientId:void 0;if(typeof N==="string"&&N.trim())$.add(N)}}return{activeSessionCount:Z,participantClientCount:$.size}}async function t(J,Q,Z){let $=new Q0({url:J,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let X=await $.command("session.list",{limit:500},void 0,{timeoutMs:O2});return C2(X.payload)}finally{await $.dispose().catch(()=>{return})}}async function x2(J,Q,Z){try{return(await t(J,Q,Z)).activeSessionCount===0}catch{return!1}}async function _2(J,Q){let Z=`${J.discoveryPath}.superseded`,$=await O(Z);if(!$?.url||!$.authToken)return;let X=await r($.url,{authToken:$.authToken});if(X.status!=="compatible")return;if(await x2(X.url,$.authToken,Q))return;return y(X.url,$.authToken)}async function D2(J={}){if(J.endpoint?.trim()){let X=await r(J.endpoint);return X.status==="compatible"?X.url:void 0}let Q=q2(),Z=await O(Q.discoveryPath);if(!Z?.url)return await _2(Q,J);let $=await r(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if($.status==="compatible")return y($.url,Z.authToken);if($.status==="protocol_mismatch")await x(Q.discoveryPath).catch(()=>{return});return}async function I0(J={}){let Q=await D2(J);if(Q&&await A(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Q;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch{return}}async function S(J,Q,Z,$){let X=new URL(J),j=Q?.trim()||e(X);if(X.protocol==="ws:")X.protocol="http:";else if(X.protocol==="wss:")X.protocol="https:";if(X.pathname="/drain",X.hash="",Z)X.searchParams.set("reason",Z);if($?.off)X.searchParams.set("off","1");return(await fetch(X,{method:"POST",headers:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b(J,Q){let Z=new URL(J),$=Q?.trim()||e(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:$?{authorization:`Bearer ${$}`}:void 0})).ok}import{spawn as R2}from"node:child_process";import{userInfo as E2}from"node:os";import{basename as S2,delimiter as m}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",b0="__CLINE_SIDECAR_PATH_END__",h0=5000,g2=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${b0}"'`,y0="CLINE_SIDECAR_SKIP_SHELL_PATH";function m0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function T2(J,Q){try{let Z=E2().shell?.trim();if(Z)return Z}catch{}return Q.SHELL?.trim()||m0(J)}function I2(J,Q){let Z=S2(J);if(Z==="csh"||Z==="tcsh")return{args:["-c",Q],argv0:`-${Z}`};return{args:["-i","-l","-c",Q]}}function P2(J){let Q=J.indexOf(Z0);if(Q===-1)return;let Z=J.indexOf(b0,Q);if(Z===-1)return;let $=J.slice(Q+Z0.length,Z).trim();return $.length>0?$:void 0}function w2(J,Q){let Z=[...J.split(m),...Q.split(m)].map(($)=>$.trim()).filter(($)=>$.length>0);return Array.from(new Set(Z)).join(m)}function H2(J,Q=h0){return new Promise((Z)=>{let $=I2(J,g2),X=R2(J,$.args,{argv0:$.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),j="",V=0,N=()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}},Y=!1,K=(F)=>{if(Y)return;Y=!0,clearTimeout(z),X.stdout?.destroy(),N(),Z(F)},z=setTimeout(()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}K(void 0)},Q);X.stdout?.on("data",(F)=>{if(Y)return;if(V+=F.length,V>65536){K(void 0);return}j+=F.toString("utf8")}),X.on("error",()=>K(void 0)),X.on("close",()=>K(P2(j)))})}async function v0(J){let Q=J?.platform??process.platform,Z=J?.env??process.env;if(Q==="win32")return{status:"skipped",reason:"windows"};if(Z[y0]?.trim())return{status:"skipped",reason:y0};let $=J?.userShell??T2(Q,Z),X=J?.fallbackShell??m0(Q),j=J?.timeoutMs??h0,V=$===X?[[$,j]]:[[$,j],[X,j/2]];for(let[N,Y]of V){let K=await H2(N,Y);if(!K)continue;let z=w2(K,Z.PATH??"");return Z.PATH=z,{status:"applied",pathEntries:z.split(m).length,shell:N}}return{status:"failed",shell:$}}var u0={readHubDiscovery:O,clearHubDiscoveryIfOwned:L0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:y2,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:v0,setHomeDirIfUnset:b2,homeDir:k2,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function p0(J,Q){let Z=J.indexOf(Q);return(Z>=0?J[Z+1]:void 0)?.trim()||void 0}function l0(J,Q){let Z=p0(J,"--discovery-path");if(!Z)throw Error("--discovery-path is required for remote Hub management");return Q.env.CLINE_HUB_DISCOVERY_PATH=Z,Z}async function h2(J=process.argv,Q=u0){Q.setHomeDirIfUnset(Q.homeDir()),await Q.ensureLoginShellPath();let Z=p0(J,"--cwd")??Q.cwd();l0(J,Q);let $=await Q.ensureDetachedHubServer(Z,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});Q.writeOutput(`${JSON.stringify({...$,cwd:Z,platform:process.platform,arch:process.arch})}
4
- `)}async function b4(J=process.argv,Q=u0){if(J.includes("--remote-hub-stop")){let Z=l0(J,Q),$=await Q.readHubDiscovery(Z);if($&&typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)try{Q.probeProcess($.pid)}catch(X){if(X?.code==="ESRCH")return await Q.clearHubDiscoveryIfOwned(Z,$.hubId),!0}if($&&!await Q.requestHubShutdown($.url,$.authToken))throw Error("Remote Hub shutdown failed");return!0}if(J.includes("--remote-hub-ensure"))return await h2(J,Q),!0;if(Q.claimHubDaemonProcess())return await Q.loadHubDaemon(),!0;return!1}export{h2 as runRemoteHubEnsure,b4 as runRemoteHelperEntrypoint};
1
+ import{createRequire as n0}from"node:module";var s0=n0(import.meta.url);import{homedir as k2}from"node:os";import{claimHubDaemonProcess as y2}from"@cline/shared";import{setHomeDirIfUnset as b2}from"@cline/shared/storage";import{createSessionId as Y2,isHubProtocolCompatible as N2,resolveClineBuildEnv as K2,resolveHubCommandTimeoutMs as W2}from"@cline/shared";import G2 from"ws";var $0="session_not_found";class v extends Error{sessionId;code="session_not_found";constructor(J,Q){super(Q??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as g1}from"node:child_process";import{closeSync as I1,mkdirSync as P1,openSync as T1,readFileSync as w1,unlinkSync as H1}from"node:fs";import{basename as k1,dirname as y1,join as b1}from"node:path";import{fileURLToPath as h1}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as m1,isHubDaemonProcess as v1,resolveClineBuildEnv as E0,withResolvedClineBuildEnv as u1}from"@cline/shared";import{createHash as d0,randomBytes as a0}from"node:crypto";import{mkdir as p,open as X0,readFile as N0,rename as o0,rm as I,writeFile as r0}from"node:fs/promises";import{dirname as K0,join as l}from"node:path";import{isHubProtocolCompatible as e0}from"@cline/shared";import{resolveClineDataDir as _,resolveClineDir as t2}from"@cline/shared/storage";var g={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.86-nightly.1790303239",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var J1="CLINE_HUB_DISCOVERY_PATH",Q1="CLINE_HUB_BUILD_ID",Z1="CLINE_HUB_BUILD_EPOCH_MS",$1=30000,X1=15000,j0=100;function j1(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function z1(J){return d0("sha256").update(J).digest("hex").slice(0,12)}function V1(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function z0(J){return new Promise((Q)=>setTimeout(Q,J))}function Y1(J){return`${J}.lock`}async function N1(J){try{let Q=JSON.parse(await N0(l(J,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function u(J){await I(J,{recursive:!0,force:!0}).catch(()=>{return})}function f(){let J=process.env[Q1]?.trim();if(J)return J;return"sdk-v1-4729c27f0fc26c26414b80b44ca4c07412b582c17389eb6b8850c1d86602faf2".trim()||`source-${String(g.version)}`}function K1(){let J=Number(process.env[Z1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1790303265252)?1790303265252:void 0}function P(J,Q=f()){let Z=e0(J);if(!Z.compatible)return Z;let $=J.buildId?.trim();if(!$)return{compatible:!1,reason:"missing_build"};if($!==Q)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function V0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function Y0(J){let Q=J?.trim().split(/[-+]/,1)[0];if(!Q)return;let Z=Q.split(".").map(($)=>Number($));if(Z.length===0||Z.some(($)=>!Number.isInteger($)||$<0))return;return Z}function W1(J,Q){for(let Z=0;Z<Math.max(J.length,Q.length);Z++){let $=J[Z]??0,X=Q[Z]??0;if($!==X)return $<X?-1:1}return 0}function W0(J,Q){let Z=J.buildId?.trim(),$=Q.buildId?.trim();if(Z&&$&&Z===$)return 0;let X=V0(J.buildEpochMs),j=V0(Q.buildEpochMs);if(X!==void 0&&j!==void 0&&X!==j)return X<j?-1:1;let V=Y0(J.coreVersion),N=Y0(Q.coreVersion);if(V&&N){let Y=W1(V,N);if(Y!==0)return Y}if(Z&&$&&Z!==$)return Z<$?-1:1;return 0}function G0(){return{buildId:f(),buildEpochMs:K1(),coreVersion:String(g.version)}}function T(J,Q){let Z=Q?.self??G0(),$=P(J,Z.buildId??"");if($.compatible)return!0;if($.reason!=="build_mismatch"&&$.reason!=="missing_build")return!1;return W0(Z,J)<=0}function q0(J=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${z1(J)}`,Z=process.env[J1]?.trim()||l(_(),"locks","hub","owners",`${j1(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}async function O(J){try{let Q=JSON.parse(await N0(J,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function F0(J,Q){await c(J,async()=>{let Z=K0(J);await p(Z,{recursive:!0});let $=`${J}.${process.pid}.${a0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(Q,null,2)}
2
+ `,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,await o0($,J);let j;try{j=await X0(Z,"r"),await j.sync()}catch{}finally{await j?.close().catch(()=>{return})}}catch(j){throw await X?.close().catch(()=>{return}),await I($,{force:!0}).catch(()=>{return}),j}})}async function C(J){await c(J,async()=>{await I(J,{force:!0}).catch(()=>{return})})}async function L0(J,Q){return await c(J,async()=>{if((await O(J))?.hubId!==Q)return!1;return await I(J,{force:!0}),!0})}async function B0(J,Q,Z){let $=Y1(J);await p(K0($),{recursive:!0});let X=Date.now()+X1;while(!0){try{await p($,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let N=await N1($);if(!N){if(Date.now()>=X){await u($);continue}await z0(j0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!V1(N.pid)||Y>$1){await u($);continue}if(Date.now()>=X)throw Error(`Timed out waiting for hub ${Q} lock ${$}`);await z0(j0);continue}try{return await r0(l($,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
+ `,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?G1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function G1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as q1,CLINE_HUB_PORT as F1,resolveClineBuildEnv as L1}from"@cline/shared";var B1="CLINE_HUB_HOST",O1="CLINE_HUB_PORT",A1="CLINE_HUB_PATHNAME",U1="127.0.0.1",M1=F1,x1="/hub";function M0(J){return L1(J)==="development"?q1:M1}function f1(J={}){return(J.env??process.env)[B1]?.trim()||U1}function C1(J={}){let Z=(J.env??process.env)[O1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function _1(J={}){return(J.env??process.env)[A1]?.trim()||x1}function x0(J={},Q={}){return{host:J.host??f1(Q),port:J.port??C1(Q),pathname:J.pathname??_1(Q)}}import{join as D1}from"node:path";import{processWorkspaceInfo as J6}from"@cline/shared";import Z6 from"simple-git";var R1="shared:cline",E1="CLINE_HUB_DISCOVERY_PATH",S1="hub-production";function D(J=R1){return q0(`${J}@${f()}`)}function H(){return{ownerId:S1,discoveryPath:process.env[E1]?.trim()||D1(_(),"locks","hub","production.json")}}var f0=15000,p1=200,C0=3000,l1=100,c1=[100,250,500,1000,2000],i1="--cline-hub-daemon",n1=3,s1=60000,_0=new Map;function t1(J,Q=Date.now()){let Z=_0.get(J);if(!Z||Q-Z.windowStartedAt>s1)return _0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=n1}function d1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function a1(){try{let J=b1(_(),"logs","hub-daemon.log");return P1(y1(J),{recursive:!0}),{fd:T1(J,"a"),logPath:J}}catch{return}}function o1(){return E0()==="production"?H():D()}function R(J){return T(J)}function r1(J){try{let Q=JSON.parse(w1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{H1(`${J}.superseded`)}catch{}}function D0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function E(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function R0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await E(J))?.url)return!0;await new Promise((X)=>setTimeout(X,l1))}return!1}async function s(J,Q){if(!t1(J.url))return!1;await S(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await R0(J.url,C0);if(!Z&&J.pid&&e1(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await R0(J.url,C0)}if(Z)await C(Q).catch(()=>{return});return Z}function e1(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function J2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await S(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await J2(J)){if(Z)await S(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await S(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Q2(J){if(E0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await C(Q.discoveryPath).catch(()=>{return})}function Z2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return h1(new URL(`./entry.${J}`,import.meta.url))}function $2(J,Q){let Z=Z2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=k1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[i1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...d1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...u1(process.env),CLINE_NO_INTERACTIVE:"1",[m1]:"1"}}}function X2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function j2(J,Q={}){if(v1())return;let Z=$2(J,Q),$=a1();try{g1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)I1($.fd)}}async function z2(J,Q={}){for(let Z=0;;Z++)try{j2(J,Q);return}catch($){let X=c1[Z];if(!X2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function V2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=x0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Q2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:r1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await E(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await C(J.discoveryPath).catch(()=>{return})}}let z=await E(j);if(z?.url){let W=D0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((x)=>typeof x==="string"&&x.trim().length>0);for(let x of L){if(!await A(z.url,{authToken:x}))continue;let i0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:x,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,i0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:x})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await z2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+f0;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await E(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await E(j);if(G?.url&&!R(G)){let L=D0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,p1))}throw Error(`Timed out after ${f0}ms waiting for detached hub startup.`)}async function k(J,Q={}){let Z=o1();return await O0(Z.discoveryPath,async()=>V2(Z,J,Q))}function q2(){return K2()==="production"?H():D()}function F2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function w0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return w0(J.data);return String(J)}function L2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function S0(J){let Q=J,Z=L2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function g0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,B2="cline-hub-auth.",H0=new Map,k0=new Set,O2=3000;var a="Hub connection closed",A2=250,U2=5000,I0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function M2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?H0.get($):void 0}function x2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!x2(J))return;let Q=new URL(y0(J));return Q.search="",Q.hash="",Q.toString()}function P0(J){let Q=J0(J);return!!Q&&k0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(k0.add(Z),Q?.trim())H0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=g0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new G2(J.toString(),{headers:{...X}}):new(F2())(J.toString(),Q?[`${B2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=g0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:S0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(w0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=S0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();$?.beforeDispatch?.();let j=Y2("hubreq_");$?.onDispatch?.(j);let V=W2(J,$?.timeoutMs),N=new Promise((K,z)=>{let F=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;z(new o(J,"hub_command_timeout",`Hub command ${J} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(B)=>{if(F)clearTimeout(F);K(B)},reject:(B)=>{if(F)clearTimeout(F);z(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:Q}})}catch(K){throw this.pendingReplies.delete(j),K}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let K=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new v(K,Y.error.message)}throw new o(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!P0(this.currentUrl)||!M2(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await T0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let J=Math.min(A2*2**this.reconnectAttempt,U2),Q=Math.round(J*(1-I0)+Math.random()*J*I0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!P0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await T0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",a);for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Q){let Z=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Q)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Q?{sessionId:Q}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(J,Q){let Z=this.subscriptionKeyForSessionId(J),$=(this.subscriptionCounts.get(Z)??0)+Q;if($<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Z,$),Q>0&&$===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??d}subscriptionSessionIdFromKey(J){return J===d?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Q=J.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve(J.envelope);return}case"event":{let Q=J.envelope.sequence;if(typeof Q==="number"){let Z=J.envelope.sessionId?.trim();for(let $ of[d,Z]){if(!$||!this.subscriptionCounts.has($))continue;let X=this.lastEventSequenceByKey.get($)??0;if(Q>X)this.lastEventSequenceByKey.set($,Q)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==J.envelope.sessionId?.trim())continue;Z.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function y0(J){let Q=new URL(J);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function A(J,Q){let Z=new Q0({url:J,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function r(J,Q){let Z=y0(J),$=await w(Z,{authToken:Q?.authToken});if(!$)return{status:"unreachable",url:Z};if(Q?.requireCurrentBuild){let X=f(),j=P($,X);if(!j.compatible&&!T($))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!N2($).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await A(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function f2(J){let Q=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Z=0,$=new Set;for(let X of Q){if(!X||typeof X!=="object")continue;let j=X.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let N=V&&typeof V==="object"?V.clientId:void 0;if(typeof N==="string"&&N.trim())$.add(N)}}return{activeSessionCount:Z,participantClientCount:$.size}}async function t(J,Q,Z){let $=new Q0({url:J,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let X=await $.command("session.list",{limit:500},void 0,{timeoutMs:O2});return f2(X.payload)}finally{await $.dispose().catch(()=>{return})}}async function C2(J,Q,Z){try{return(await t(J,Q,Z)).activeSessionCount===0}catch{return!1}}async function _2(J,Q){let Z=`${J.discoveryPath}.superseded`,$=await O(Z);if(!$?.url||!$.authToken)return;let X=await r($.url,{authToken:$.authToken});if(X.status!=="compatible")return;if(await C2(X.url,$.authToken,Q))return;return y(X.url,$.authToken)}async function D2(J={}){if(J.endpoint?.trim()){let X=await r(J.endpoint);return X.status==="compatible"?X.url:void 0}let Q=q2(),Z=await O(Q.discoveryPath);if(!Z?.url)return await _2(Q,J);let $=await r(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if($.status==="compatible")return y($.url,Z.authToken);if($.status==="protocol_mismatch")await C(Q.discoveryPath).catch(()=>{return});return}async function T0(J={}){let Q=await D2(J);if(Q&&await A(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Q;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch(Z){J.onStartupError?.(Z);return}}async function S(J,Q,Z,$){let X=new URL(J),j=Q?.trim()||e(X);if(X.protocol==="ws:")X.protocol="http:";else if(X.protocol==="wss:")X.protocol="https:";if(X.pathname="/drain",X.hash="",Z)X.searchParams.set("reason",Z);if($?.off)X.searchParams.set("off","1");return(await fetch(X,{method:"POST",headers:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b(J,Q){let Z=new URL(J),$=Q?.trim()||e(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:$?{authorization:`Bearer ${$}`}:void 0})).ok}import{spawn as R2}from"node:child_process";import{userInfo as E2}from"node:os";import{basename as S2,delimiter as m}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",h0="__CLINE_SIDECAR_PATH_END__",m0=5000,g2=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${h0}"'`,b0="CLINE_SIDECAR_SKIP_SHELL_PATH";function v0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function I2(J,Q){try{let Z=E2().shell?.trim();if(Z)return Z}catch{}return Q.SHELL?.trim()||v0(J)}function P2(J,Q){let Z=S2(J);if(Z==="csh"||Z==="tcsh")return{args:["-c",Q],argv0:`-${Z}`};return{args:["-i","-l","-c",Q]}}function T2(J){let Q=J.indexOf(Z0);if(Q===-1)return;let Z=J.indexOf(h0,Q);if(Z===-1)return;let $=J.slice(Q+Z0.length,Z).trim();return $.length>0?$:void 0}function w2(J,Q){let Z=[...J.split(m),...Q.split(m)].map(($)=>$.trim()).filter(($)=>$.length>0);return Array.from(new Set(Z)).join(m)}function H2(J,Q=m0){return new Promise((Z)=>{let $=P2(J,g2),X=R2(J,$.args,{argv0:$.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),j="",V=0,N=()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}},Y=!1,K=(F)=>{if(Y)return;Y=!0,clearTimeout(z),X.stdout?.destroy(),N(),Z(F)},z=setTimeout(()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}K(void 0)},Q);X.stdout?.on("data",(F)=>{if(Y)return;if(V+=F.length,V>65536){K(void 0);return}j+=F.toString("utf8")}),X.on("error",()=>K(void 0)),X.on("close",()=>K(T2(j)))})}async function u0(J){let Q=J?.platform??process.platform,Z=J?.env??process.env;if(Q==="win32")return{status:"skipped",reason:"windows"};if(Z[b0]?.trim())return{status:"skipped",reason:b0};let $=J?.userShell??I2(Q,Z),X=J?.fallbackShell??v0(Q),j=J?.timeoutMs??m0,V=$===X?[[$,j]]:[[$,j],[X,j/2]];for(let[N,Y]of V){let K=await H2(N,Y);if(!K)continue;let z=w2(K,Z.PATH??"");return Z.PATH=z,{status:"applied",pathEntries:z.split(m).length,shell:N}}return{status:"failed",shell:$}}var p0={readHubDiscovery:O,clearHubDiscoveryIfOwned:L0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:y2,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:u0,setHomeDirIfUnset:b2,homeDir:k2,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function l0(J,Q){let Z=J.indexOf(Q);return(Z>=0?J[Z+1]:void 0)?.trim()||void 0}function c0(J,Q){let Z=l0(J,"--discovery-path");if(!Z)throw Error("--discovery-path is required for remote Hub management");return Q.env.CLINE_HUB_DISCOVERY_PATH=Z,Z}async function h2(J=process.argv,Q=p0){Q.setHomeDirIfUnset(Q.homeDir()),await Q.ensureLoginShellPath();let Z=l0(J,"--cwd")??Q.cwd();c0(J,Q);let $=await Q.ensureDetachedHubServer(Z,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});Q.writeOutput(`${JSON.stringify({...$,cwd:Z,platform:process.platform,arch:process.arch})}
4
+ `)}async function b6(J=process.argv,Q=p0){if(J.includes("--remote-hub-stop")){let Z=c0(J,Q),$=await Q.readHubDiscovery(Z);if($&&typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)try{Q.probeProcess($.pid)}catch(X){if(X?.code==="ESRCH")return await Q.clearHubDiscoveryIfOwned(Z,$.hubId),!0}if($&&!await Q.requestHubShutdown($.url,$.authToken))throw Error("Remote Hub shutdown failed");return!0}if(J.includes("--remote-hub-ensure"))return await h2(J,Q),!0;if(Q.claimHubDaemonProcess())return await Q.loadHubDaemon(),!0;return!1}export{h2 as runRemoteHubEnsure,b6 as runRemoteHelperEntrypoint};
@@ -68,6 +68,7 @@ export declare class SessionRuntime {
68
68
  private readonly logger?;
69
69
  readonly telemetry?: ITelemetryService;
70
70
  private readonly conversation;
71
+ private pendingTerminalError;
71
72
  private readonly mistakeTracker;
72
73
  private readonly loopTracker;
73
74
  /**
@@ -173,7 +174,9 @@ export declare class SessionRuntime {
173
174
  run(userMessage: string, userImages?: string[], userFiles?: string[]): Promise<AgentResult>;
174
175
  continue(userMessage?: string, userImages?: string[], userFiles?: string[]): Promise<AgentResult>;
175
176
  private composeSystemPrompt;
177
+ private getRunAdmissionError;
176
178
  private executeRun;
179
+ private recordTerminalError;
177
180
  /**
178
181
  * Retry a run once when it failed with an auth-like error and the host
179
182
  * refreshed credentials via `config.onAuthError`. The failed attempt's
@@ -8,8 +8,8 @@ export type GlobalCompactionStrategy = z.infer<typeof GlobalCompactionStrategySc
8
8
  /** Compaction strategy plus the "off" state surfaced by the CLI settings UI. */
9
9
  export type GlobalCompactionMode = GlobalCompactionStrategy | "off";
10
10
  declare const GlobalPlanActModeSchema: z.ZodEnum<{
11
- act: "act";
12
11
  plan: "plan";
12
+ act: "act";
13
13
  }>;
14
14
  export type GlobalPlanActMode = z.infer<typeof GlobalPlanActModeSchema>;
15
15
  export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
@@ -21,8 +21,8 @@ export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
21
21
  }>>>;
22
22
  compactionEnabled: z.ZodCatch<z.ZodOptional<z.ZodBoolean>>;
23
23
  planActMode: z.ZodCatch<z.ZodOptional<z.ZodEnum<{
24
- act: "act";
25
24
  plan: "plan";
25
+ act: "act";
26
26
  }>>>;
27
27
  toolAutoApprove: z.ZodCatch<z.ZodOptional<z.ZodBoolean>>;
28
28
  tuiTheme: z.ZodCatch<z.ZodOptional<z.ZodString>>;
@@ -51,7 +51,7 @@ export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
51
51
  autoUpdateEnabled: boolean;
52
52
  compactionStrategy?: "basic" | "agentic" | undefined;
53
53
  compactionEnabled?: boolean | undefined;
54
- planActMode?: "act" | "plan" | undefined;
54
+ planActMode?: "plan" | "act" | undefined;
55
55
  toolAutoApprove?: boolean | undefined;
56
56
  tuiTheme?: string | undefined;
57
57
  disabledTools?: string[] | undefined;
@@ -17,23 +17,23 @@ export declare const ProviderIdSchema: z.ZodString;
17
17
  export declare const ProviderProtocolSchema: z.ZodEnum<{
18
18
  anthropic: "anthropic";
19
19
  gemini: "gemini";
20
- "openai-chat": "openai-chat";
21
- "openai-responses": "openai-responses";
22
20
  "openai-r1": "openai-r1";
23
21
  "ai-sdk": "ai-sdk";
22
+ "openai-responses": "openai-responses";
23
+ "openai-chat": "openai-chat";
24
24
  }>;
25
25
  export declare const ProviderClientSchema: z.ZodEnum<{
26
26
  custom: "custom";
27
27
  anthropic: "anthropic";
28
+ bedrock: "bedrock";
28
29
  gemini: "gemini";
30
+ vertex: "vertex";
31
+ "openai-compatible": "openai-compatible";
32
+ openai: "openai";
29
33
  "openai-r1": "openai-r1";
30
34
  "ai-sdk": "ai-sdk";
31
35
  "ai-sdk-community": "ai-sdk-community";
32
- openai: "openai";
33
- "openai-compatible": "openai-compatible";
34
- bedrock: "bedrock";
35
36
  fetch: "fetch";
36
- vertex: "vertex";
37
37
  }>;
38
38
  export declare const AuthSettingsSchema: z.ZodObject<{
39
39
  apiKey: z.ZodOptional<z.ZodString>;
@@ -68,10 +68,10 @@ export declare const AwsSettingsSchema: z.ZodObject<{
68
68
  region: z.ZodOptional<z.ZodString>;
69
69
  profile: z.ZodOptional<z.ZodString>;
70
70
  authentication: z.ZodOptional<z.ZodEnum<{
71
- profile: "profile";
72
71
  iam: "iam";
73
72
  "api-key": "api-key";
74
73
  apikey: "apikey";
74
+ profile: "profile";
75
75
  }>>;
76
76
  usePromptCache: z.ZodOptional<z.ZodBoolean>;
77
77
  useCrossRegionInference: z.ZodOptional<z.ZodBoolean>;
@@ -106,8 +106,8 @@ export declare const SapSettingsSchema: z.ZodObject<{
106
106
  export type SapSettings = z.infer<typeof SapSettingsSchema>;
107
107
  export declare const OcaSettingsSchema: z.ZodObject<{
108
108
  mode: z.ZodOptional<z.ZodEnum<{
109
- internal: "internal";
110
109
  external: "external";
110
+ internal: "internal";
111
111
  }>>;
112
112
  usePromptCache: z.ZodOptional<z.ZodBoolean>;
113
113
  }, z.core.$strip>;
@@ -140,23 +140,23 @@ export declare const ProviderSettingsSchema: z.ZodObject<{
140
140
  protocol: z.ZodOptional<z.ZodEnum<{
141
141
  anthropic: "anthropic";
142
142
  gemini: "gemini";
143
- "openai-chat": "openai-chat";
144
- "openai-responses": "openai-responses";
145
143
  "openai-r1": "openai-r1";
146
144
  "ai-sdk": "ai-sdk";
145
+ "openai-responses": "openai-responses";
146
+ "openai-chat": "openai-chat";
147
147
  }>>;
148
148
  client: z.ZodOptional<z.ZodEnum<{
149
149
  custom: "custom";
150
150
  anthropic: "anthropic";
151
+ bedrock: "bedrock";
151
152
  gemini: "gemini";
153
+ vertex: "vertex";
154
+ "openai-compatible": "openai-compatible";
155
+ openai: "openai";
152
156
  "openai-r1": "openai-r1";
153
157
  "ai-sdk": "ai-sdk";
154
158
  "ai-sdk-community": "ai-sdk-community";
155
- openai: "openai";
156
- "openai-compatible": "openai-compatible";
157
- bedrock: "bedrock";
158
159
  fetch: "fetch";
159
- vertex: "vertex";
160
160
  }>>;
161
161
  routingProviderId: z.ZodOptional<z.ZodString>;
162
162
  maxTokens: z.ZodOptional<z.ZodNumber>;
@@ -184,10 +184,10 @@ export declare const ProviderSettingsSchema: z.ZodObject<{
184
184
  region: z.ZodOptional<z.ZodString>;
185
185
  profile: z.ZodOptional<z.ZodString>;
186
186
  authentication: z.ZodOptional<z.ZodEnum<{
187
- profile: "profile";
188
187
  iam: "iam";
189
188
  "api-key": "api-key";
190
189
  apikey: "apikey";
190
+ profile: "profile";
191
191
  }>>;
192
192
  usePromptCache: z.ZodOptional<z.ZodBoolean>;
193
193
  useCrossRegionInference: z.ZodOptional<z.ZodBoolean>;
@@ -218,8 +218,8 @@ export declare const ProviderSettingsSchema: z.ZodObject<{
218
218
  }, z.core.$strip>>;
219
219
  oca: z.ZodOptional<z.ZodObject<{
220
220
  mode: z.ZodOptional<z.ZodEnum<{
221
- internal: "internal";
222
221
  external: "external";
222
+ internal: "internal";
223
223
  }>>;
224
224
  usePromptCache: z.ZodOptional<z.ZodBoolean>;
225
225
  }, z.core.$strip>>;
@@ -231,10 +231,10 @@ export declare const ProviderSettingsSchema: z.ZodObject<{
231
231
  capabilities: z.ZodOptional<z.ZodArray<z.ZodEnum<{
232
232
  tools: "tools";
233
233
  reasoning: "reasoning";
234
- "prompt-cache": "prompt-cache";
235
234
  streaming: "streaming";
236
- vision: "vision";
235
+ "prompt-cache": "prompt-cache";
237
236
  "computer-use": "computer-use";
237
+ vision: "vision";
238
238
  oauth: "oauth";
239
239
  popular: "popular";
240
240
  }>>>;
@@ -0,0 +1,28 @@
1
+ import { type BasicLogger } from "@cline/shared";
2
+ export interface PluginSlashCommand {
3
+ /** Normalized token: lowercase, no leading slash. */
4
+ name: string;
5
+ description?: string;
6
+ }
7
+ export interface PluginCommandResult {
8
+ reply?: string;
9
+ submitPrompt?: string;
10
+ }
11
+ /**
12
+ * Executes plugin-registered slash commands (`api.registerCommand`) for one
13
+ * workspace. Plugins are loaded on first use and kept alive so repeated
14
+ * commands answer instantly; the loaded set is refreshed when plugin module
15
+ * paths or mtimes change (installs, updates, toggles).
16
+ */
17
+ export interface PluginCommandService {
18
+ listCommands(): Promise<PluginSlashCommand[]>;
19
+ /** Runs `/name input`. Resolves undefined when no plugin declares `name`. */
20
+ run(name: string, input: string): Promise<PluginCommandResult | undefined>;
21
+ shutdown(): Promise<void>;
22
+ }
23
+ export declare function normalizePluginCommandName(name: string): string;
24
+ export declare function createPluginCommandService(options: {
25
+ cwd: string;
26
+ workspacePath?: string;
27
+ logger?: BasicLogger;
28
+ }): PluginCommandService;