@cline/core 0.0.86 → 0.0.88-nightly.1790735522
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloud/api.d.ts +32 -5
- package/dist/cloud/controller.d.ts +32 -4
- package/dist/cloud/index.d.ts +3 -1
- package/dist/cloud/index.js +21 -11
- package/dist/cloud/models.d.ts +9 -0
- package/dist/cloud/types.d.ts +11 -1
- package/dist/extensions/plugin-sandbox-bootstrap.js +1 -1
- package/dist/extensions/tools/executors/bash.d.ts +26 -0
- package/dist/extensions/tools/executors/index.d.ts +1 -1
- package/dist/extensions/tools/index.d.ts +1 -1
- package/dist/hub/client/index.d.ts +4 -0
- package/dist/hub/client/session-client.d.ts +0 -3
- package/dist/hub/daemon/bind-diagnostics.d.ts +16 -0
- package/dist/hub/daemon/entry.js +304 -304
- package/dist/hub/daemon/index.d.ts +8 -0
- package/dist/hub/discovery/index.d.ts +1 -0
- package/dist/hub/index.js +293 -294
- package/dist/index.d.ts +5 -3
- package/dist/index.js +339 -334
- package/dist/remote/remote-helper-entry.js +4 -4
- package/dist/remote/remote-helper.js +4 -4
- package/dist/services/agent-events.d.ts +1 -0
- package/dist/services/cloud-handoff/git-preflight.d.ts +24 -0
- package/dist/services/cloud-handoff/index.d.ts +4 -0
- package/dist/services/cloud-handoff/metadata.d.ts +7 -0
- package/dist/services/cloud-handoff/transcript.d.ts +5 -0
- package/dist/services/cloud-handoff/types.d.ts +35 -0
- package/dist/services/feature-flags/posthog.js +1 -1
- package/dist/services/telemetry/core-events.d.ts +3 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/services/workspace/workspace-manifest.d.ts +34 -0
- package/dist/session/fork-metadata.d.ts +7 -0
- package/dist/session/services/persistence-service.d.ts +1 -0
- package/dist/types/chat-schema.d.ts +2 -2
- package/dist/types/provider-settings.d.ts +11 -0
- package/package.json +4 -4
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`,{encoding:"utf8"}),await
|
|
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
|
|
1
|
+
import{homedir as Wn}from"node:os";import{claimHubDaemonProcess as $n}from"@cline/shared";import{setHomeDirIfUnset as Gn}from"@cline/shared/storage";import{createSessionId as hn,ensureLoopbackProxyBypass as Ae,isHubProtocolCompatible as gn,resolveClineBuildEnv as bn,resolveHubCommandTimeoutMs as yn}from"@cline/shared";import wn from"ws";var H={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.88-nightly.1790735522",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 re="session_not_found";class F extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}import{spawn as Dt}from"node:child_process";import{closeSync as At,mkdirSync as Lt,openSync as Ut,readFileSync as Mt,unlinkSync as Nt}from"node:fs";import{basename as Bt,dirname as Ft,join as Vt}from"node:path";import{fileURLToPath as Wt}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as $t,isBunEmbeddedModulePath as Gt,isHubDaemonProcess as jt,resolveClineBuildEnv as Te,withResolvedClineBuildEnv as qt}from"@cline/shared";import{createHash as Ye,randomBytes as Xe}from"node:crypto";import{mkdir as W,open as ie,readFile as de,rename as Ze,rm as I,writeFile as Qe}from"node:fs/promises";import{dirname as le,join as G}from"node:path";import{ensureLoopbackProxyBypass as et,isHubProtocolCompatible as tt}from"@cline/shared";import{resolveClineDataDir as P,resolveClineDir as Qn}from"@cline/shared/storage";var nt="CLINE_HUB_DISCOVERY_PATH",ot="CLINE_HUB_BUILD_ID",rt="CLINE_HUB_BUILD_EPOCH_MS",it=30000,st=15000,se=100;function at(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ct(e){return Ye("sha256").update(e).digest("hex").slice(0,12)}function ut(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function ae(e){return new Promise((t)=>setTimeout(t,e))}function dt(e){return`${e}.lock`}async function lt(e){try{let t=JSON.parse(await de(G(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function V(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[ot]?.trim();if(e)return e;return"sdk-v1-0982e787428525296f7c82ef42aff77c3cee5087192bf30b19f8018599e7f0ab".trim()||`source-${String(H.version)}`}function pt(){let e=Number(process.env[rt]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735549231)?1790735549231:void 0}function x(e,t=k()){let n=tt(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ce(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ue(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function ft(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function pe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ce(e.buildEpochMs),i=ce(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let a=ue(e.coreVersion),u=ue(t.coreVersion);if(a&&u){let c=ft(a,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function fe(){return{buildId:k(),buildEpochMs:pt(),coreVersion:String(H.version)}}function O(e,t){let n=t?.self??fe(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return pe(n,e)<=0}function me(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${ct(e)}`,n=process.env[nt]?.trim()||G(P(),"locks","hub","owners",`${at(t)}.json`);return{ownerId:t,discoveryPath:n}}async function b(e){try{let t=JSON.parse(await de(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function he(e,t){await j(e,async()=>{let n=le(e);await W(n,{recursive:!0});let o=`${e}.${process.pid}.${Xe(6).toString("hex")}.tmp`,r;try{r=await ie(o,"wx",384),await r.writeFile(`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{encoding:"utf8"}),await r.sync(),await r.close(),r=void 0,await Ze(o,e);let i;try{i=await ie(n,"r"),await i.sync()}catch{}finally{await i?.close().catch(()=>{return})}}catch(i){throw await r?.close().catch(()=>{return}),await I(o,{force:!0}).catch(()=>{return}),i}})}async function C(e){await j(e,async()=>{await I(e,{force:!0}).catch(()=>{return})})}async function ge(e,t){return await j(e,async()=>{if((await b(e))?.hubId!==t)return!1;return await I(e,{force:!0}),!0})}async function be(e,t,n){let o=dt(e);await W(le(o),{recursive:!0});let r=Date.now()+st;while(!0){try{await W(o,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let u=await lt(o);if(!u){if(Date.now()>=r){await V(o);continue}await ae(se);continue}let c=Date.now()-Date.parse(u.acquiredAt);if(!ut(u.pid)||c>it){await V(o);continue}if(Date.now()>=r)throw Error(`Timed out waiting for hub ${t} lock ${o}`);await ae(se);continue}try{return await Qe(G(o,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
3
|
+
`,"utf8"),await n()}finally{await V(o)}}}function j(e,t){return be(`${e}.mutation`,"discovery mutation",t)}function ye(e,t){return be(e,"startup",t)}async function D(e,t){et();try{let n=await fetch(t?.authToken?mt(e):ve(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let o=await n.json();if(typeof o.protocolVersion!=="string"||typeof o.host!=="string"||typeof o.port!=="number"||typeof o.url!=="string")return;return{protocolVersion:o.protocolVersion,minClientProtocolVersion:typeof o.minClientProtocolVersion==="string"?o.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof o.maxClientProtocolVersion==="string"?o.maxClientProtocolVersion:void 0,capabilities:Array.isArray(o.capabilities)?o.capabilities.filter((r)=>typeof r==="string"):void 0,coreVersion:typeof o.coreVersion==="string"?o.coreVersion:void 0,buildId:typeof o.buildId==="string"?o.buildId:void 0,buildEpochMs:typeof o.buildEpochMs==="number"?o.buildEpochMs:void 0,host:o.host,port:o.port,url:o.url,hubId:typeof o.hubId==="string"?o.hubId:void 0,authToken:typeof o.authToken==="string"?o.authToken:void 0,pid:typeof o.pid==="number"?o.pid:void 0,startedAt:typeof o.startedAt==="string"?o.startedAt:void 0,updatedAt:typeof o.updatedAt==="string"?o.updatedAt:void 0}}catch{return}}function we(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function ve(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function mt(e){let t=new URL(ve(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as ht,CLINE_HUB_PORT as gt,resolveClineBuildEnv as bt}from"@cline/shared";var yt="CLINE_HUB_HOST",wt="CLINE_HUB_PORT",vt="CLINE_HUB_PATHNAME",St="127.0.0.1",kt=gt,Ct="/hub";function Se(e){return bt(e)==="development"?ht:kt}function Ht(e={}){return(e.env??process.env)[yt]?.trim()||St}function Pt(e={}){let n=(e.env??process.env)[wt]?.trim();if(!n)return Se(e);let o=Number.parseInt(n,10);if(!Number.isInteger(o)||o<1||o>65535)return Se(e);return o}function _t(e={}){return(e.env??process.env)[vt]?.trim()||Ct}function ke(e={},t={}){return{host:e.host??Ht(t),port:e.port??Pt(t),pathname:e.pathname??_t(t)}}import{join as Et}from"node:path";import{execFile as Rt}from"node:child_process";import{promisify as Tt}from"node:util";import{processWorkspaceInfo as ao}from"@cline/shared";import uo from"simple-git";var lo=Tt(Rt);var It="shared:cline",xt="CLINE_HUB_DISCOVERY_PATH",Ot="hub-production";function _(e=It){return me(`${e}@${k()}`)}function A(){return{ownerId:Ot,discoveryPath:process.env[xt]?.trim()||Et(P(),"locks","hub","production.json")}}var Ce=15000,Kt=200,He=3000,zt=100,Jt=[100,250,500,1000,2000],Yt="--cline-hub-daemon",Xt=3,Zt=60000,Pe=new Map;function Qt(e,t=Date.now()){let n=Pe.get(e);if(!n||t-n.windowStartedAt>Zt)return Pe.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Xt}function en(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function tn(){try{let e=Vt(P(),"logs","hub-daemon.log");return Lt(Ft(e),{recursive:!0}),{fd:Ut(e,"a"),logPath:e}}catch{return}}function nn(){return Te()==="production"?A():_()}function R(e){return O(e)}function on(e){try{let t=JSON.parse(Mt(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function q(e){try{Nt(`${e}.superseded`)}catch{}}function _e(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function T(e,t){try{return await D(e,{authToken:t})}catch{return}}async function Re(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await T(e))?.url)return!0;await new Promise((r)=>setTimeout(r,zt))}return!1}async function z(e,t){if(!Qt(e.url))return!1;await E(e.url,e.authToken,"retired by newer install").catch(()=>!1),await M(e.url,e.authToken).catch(()=>!1);let n=await Re(e.url,He);if(!n&&e.pid&&rn(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Re(e.url,He)}if(n)await C(t).catch(()=>{return});return n}function rn(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function sn(e){try{return(await J(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function K(e,t){if(R(e))return"reusable";let n=await E(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await sn(e)){if(n)await E(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let o=await z(e,t);if(!o&&n)await E(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return o?"retired":"failed"}async function an(e){if(Te()!=="production")return;let t=_();if(t.discoveryPath===e.discoveryPath)return;let n=await b(t.discoveryPath);if(n?.url)await z(n,t.discoveryPath);else await C(t.discoveryPath).catch(()=>{return})}function cn(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return Wt(new URL(`./entry.${e}`,import.meta.url))}function un(e,t){if(Gt(e))return[Yt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function dn(e,t){let n=cn(),o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let r=Bt(o).toLowerCase().includes("bun"),i=un(n,r);return{launcher:o,args:[...i,"--cwd",e,...en(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...qt(process.env),CLINE_NO_INTERACTIVE:"1",[$t]:"1"}}}function ln(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function pn(e,t={}){if(jt())return;let n=dn(e,t),o=tn();try{Dt(n.launcher,n.args,{detached:!0,stdio:o?["ignore",o.fd,o.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(o)At(o.fd)}}async function fn(e,t={}){for(let n=0;;n++)try{pn(e,t);return}catch(o){let r=Jt[n];if(!ln(o)||r===void 0)throw o;await new Promise((i)=>setTimeout(i,r))}}async function mn(e,t,n={}){let o=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),r=ke(n),i=we(r.host,r.port,r.pathname),a=(l)=>{if(!o)U(l.url,l.authToken);return l};await an(e).catch(()=>{return});let u=await b(e.discoveryPath),c=u?.url?void 0:on(e.discoveryPath),d=!1;if(u?.url){let l=u.authToken;if(!l)d=!0,await z(u,e.discoveryPath);else{let p=await T(u.url,l);if(p?.url&&R(p)&&await y(p.url,{authToken:l}))return q(e.discoveryPath),a({url:p.url,authToken:l});if(p?.url){if(await K({...p,authToken:l},e.discoveryPath)==="deferred_busy"&&await y(p.url,{authToken:l}))return a({url:p.url,authToken:l})}else await C(e.discoveryPath).catch(()=>{return})}}let s=await T(i);if(s?.url){let l=_e(s,u??c,i);if(R(s)){let h=[s.authToken,u?.authToken,c?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0);for(let S of h){if(!await y(s.url,{authToken:S}))continue;let ze={hubId:s.hubId??`repaired-${s.port}`,protocolVersion:s.protocolVersion,minClientProtocolVersion:s.minClientProtocolVersion,maxClientProtocolVersion:s.maxClientProtocolVersion,capabilities:s.capabilities,coreVersion:s.coreVersion,buildId:s.buildId,authToken:S,host:s.host,port:s.port,url:s.url,pid:s.pid??u?.pid??c?.pid,startedAt:s.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await he(e.discoveryPath,ze)}catch{}return q(e.discoveryPath),a({url:s.url,authToken:S})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${d?" 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 p=await K(l,e.discoveryPath);if(p==="deferred_busy"){for(let h of[l.authToken,u?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0))if(await y(s.url,{authToken:h}))return a({url:s.url,authToken:h});if(n.allowPortFallback!==!0&&r.port!==0)throw Error(`An older Cline Hub is running at ${i} 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(p==="failed"&&n.allowPortFallback!==!0&&r.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let g=n.allowPortFallback===!0&&r.port!==0?{...r,port:0}:r;await fn(t,{...g,manageConnectors:n.manageConnectors});let w=Date.now()+Ce;while(Date.now()<w){let l=await b(e.discoveryPath);if(l?.url&&l.authToken){let h=await T(l.url,l.authToken);if(h?.url&&R(h)&&await y(h.url,{authToken:l.authToken}))return q(e.discoveryPath),a({url:h.url,authToken:l.authToken})}let p=await T(i);if(p?.url&&!R(p)){let h=_e(p,l??c,i),v=await K(h,e.discoveryPath);if(v==="deferred_busy"&&l?.authToken&&await y(p.url,{authToken:l.authToken}))return a({url:p.url,authToken:l.authToken});if(v==="failed"&&n.allowPortFallback!==!0&&r.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((h)=>setTimeout(h,Kt))}throw Error(`Timed out after ${Ce}ms waiting for detached hub startup.`)}async function L(e,t={}){let n=nn();return await ye(n.discoveryPath,async()=>mn(n,e,t))}function vn(){return bn()==="production"?A():_()}function Sn(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Le(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return Le(e.data);return String(e)}function kn(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function Ee(e){let t=e,n=kn(t.reason);return new f("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:X,{closeCode:t.code,closeReason:n||void 0})}function Ie(e,t){if(e instanceof f)return e;if(e instanceof Error)return new f("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new f("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new f("hub_connect_failed",n);let o=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new f("hub_connect_failed",o?`Failed to connect to hub at ${t.toString()} (${o} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var Y="*",N=8000,Cn="cline-hub-auth.",Ue=new Map,Me=new Set,Hn=3000;var X="Hub connection closed",Pn=250,_n=5000,xe=0.5;class f extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Rn(e){return e instanceof f}class Z extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function ee(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let o=te(e.toString());return o?Ue.get(o):void 0}function Tn(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function te(e){if(!Tn(e))return;let t=new URL(Ne(e));return t.search="",t.hash="",t.toString()}function Oe(e){let t=te(e);return!!t&&Me.has(t)}function U(e,t){let n=te(e);if(n){if(Me.add(n),t?.trim())Ue.set(n,t)}return e}class ne{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 f("hub_connection_closed",X);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.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(e){if(this.capabilities=e.map((t)=>({...t})),!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 e=new URL(this.currentUrl),t=this.options.authToken?.trim()||ee(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,o=this.openSocket(e,t,n),r;this.connectPromise=o.then(async(a)=>{if(r=a,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,metadata:{...this.options.metadata,version:this.options.clientVersion??String(H.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{a.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let u of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(u));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(a){if(this.connectPromise===i)this.connectPromise=void 0;if(r&&this.socket===r){this.lastCloseError=Ie(a,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{r.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw a}}async openSocket(e,t,n){let o=this.options.resolveConnectionHeaders,r;if(o){let c;try{r=await Promise.race([Promise.resolve().then(()=>o()),new Promise((d,s)=>{c=setTimeout(()=>{s(new f("hub_connect_timeout",`Timed out resolving hub connection headers after ${N}ms`))},N)})])}catch(d){let s=d instanceof f?d:new f("hub_connect_failed",d instanceof Error?d.message:String(d));if(n===this.connectGeneration)this.lastCloseError=s;throw s}finally{clearTimeout(c)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(r&&Object.keys(r).some((c)=>c.toLowerCase()==="sec-websocket-protocol")){let c=new f("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=c;throw c}let i=r?new wn(e.toString(),{headers:{...r}}):new(Sn())(e.toString(),t?[`${Cn}${t}`]:void 0);this.socket=i;let a=!1,u=new Promise((c,d)=>{let s=!1,m=setTimeout(()=>{if(s)return;s=!0,a=!0;let g=new f("hub_connect_timeout",`Timed out connecting to hub after ${N}ms`);if(this.socket===i)this.lastCloseError=g,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}d(g)},N);i.addEventListener("open",()=>{if(s)return;s=!0,clearTimeout(m),c()}),i.addEventListener("error",(g)=>{if(s)return;s=!0,clearTimeout(m);let w=Ie(g,e);if(this.socket===i)this.lastCloseError=w,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;d(w)}),i.addEventListener("close",(g)=>{if(s)return;s=!0,clearTimeout(m);let w=a?this.lastCloseError:Ee(g);if(this.socket===i){if(!a)this.lastCloseError=w,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}d(w)})});return i.addEventListener("message",(c)=>{this.handleFrame(JSON.parse(Le(c)))}),i.addEventListener("close",(c)=>{if(this.socket!==i)return;if(!a)this.lastCloseError=Ee(c),this.sawSocketClose=!0;this.registered=!1;for(let d of this.pendingReplies.values())d.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await u,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,o={listener:e,sessionId:n};return this.listeners.add(o),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(o))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,o){let r=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,o)}catch(a){if(!i||r>=1||!await this.recoverLocalHubTransport(a))throw a;r+=1}}async commandOnce(e,t,n,o,r=!0){if(r)await this.connect();o?.beforeDispatch?.();let i=hn("hubreq_");o?.onDispatch?.(i);let a=yn(e,o?.timeoutMs),u=new Promise((d,s)=>{let m=a===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;s(new Z(e,"hub_command_timeout",`Hub command ${e} timed out after ${a}ms (hub=${this.currentUrl}, requestId=${i}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},a);this.pendingReplies.set(i,{resolve:(g)=>{if(m)clearTimeout(m);d(g)},reject:(g)=>{if(m)clearTimeout(m);s(g)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:a,payload:t}})}catch(d){throw this.pendingReplies.delete(i),d}let c=await u;if(!c.ok){if(c.error?.code===re){let d=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new F(d,c.error.message)}throw new Z(e,c.error?.code,c.error?.message??`Hub command ${e} failed`)}return c}async recoverLocalHubTransport(e){if(!Oe(this.currentUrl)||!Rn(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await De({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,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 e=Math.min(Pn*2**this.reconnectAttempt,_n),t=Math.round(e*(1-xe)+Math.random()*e*xe);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Oe(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await De({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new f("hub_connection_closed",X);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.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(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new f("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),o=(this.subscriptionCounts.get(n)??0)+t;if(o<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,o),t>0&&o===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??Y}subscriptionSessionIdFromKey(e){return e===Y?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let o of[Y,n]){if(!o||!this.subscriptionCounts.has(o))continue;let r=this.lastEventSequenceByKey.get(o)??0;if(t>r)this.lastEventSequenceByKey.set(o,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Ne(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function y(e,t){let n=new ne({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function Q(e,t){let n=Ne(e),o=await D(n,{authToken:t?.authToken});if(!o)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let r=k(),i=x(o,r);if(!i.compatible&&!O(o))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!gn(o).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await y(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function En(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,o=new Set;for(let r of t){if(!r||typeof r!=="object")continue;let i=r.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let a of i){let u=a&&typeof a==="object"?a.clientId:void 0;if(typeof u==="string"&&u.trim())o.add(u)}}return{activeSessionCount:n,participantClientCount:o.size}}async function J(e,t,n){let o=new ne({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let r=await o.command("session.list",{limit:500},void 0,{timeoutMs:Hn});return En(r.payload)}finally{await o.dispose().catch(()=>{return})}}async function In(e,t,n){try{return(await J(e,t,n)).activeSessionCount===0}catch{return!1}}async function xn(e,t){let n=`${e.discoveryPath}.superseded`,o=await b(n);if(!o?.url||!o.authToken)return;let r=await Q(o.url,{authToken:o.authToken});if(r.status!=="compatible")return;if(await In(r.url,o.authToken,t))return;return U(r.url,o.authToken)}async function On(e={}){if(e.endpoint?.trim()){let r=await Q(e.endpoint);return r.status==="compatible"?r.url:void 0}let t=vn(),n=await b(t.discoveryPath);if(!n?.url)return await xn(t,e);let o=await Q(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(o.status==="compatible")return U(o.url,n.authToken);if(o.status==="protocol_mismatch")await C(t.discoveryPath).catch(()=>{return});return}async function De(e={}){let t=await On(e);if(t&&await y(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await L(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function E(e,t,n,o){Ae();let r=new URL(e),i=t?.trim()||ee(r);if(r.protocol==="ws:")r.protocol="http:";else if(r.protocol==="wss:")r.protocol="https:";if(r.pathname="/drain",r.hash="",n)r.searchParams.set("reason",n);if(o?.off)r.searchParams.set("off","1");return(await fetch(r,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function M(e,t){Ae();let n=new URL(e),o=t?.trim()||ee(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:o?{authorization:`Bearer ${o}`}:void 0})).ok}import{spawn as Dn}from"node:child_process";import{userInfo as An}from"node:os";import{basename as Ln,delimiter as B}from"node:path";var oe="__CLINE_SIDECAR_PATH_START__",Fe="__CLINE_SIDECAR_PATH_END__",Ve=5000,Un=`/bin/sh -c 'printf "%s%s%s" "${oe}" "$PATH" "${Fe}"'`,Be="CLINE_SIDECAR_SKIP_SHELL_PATH";function We(e){return e==="darwin"?"/bin/zsh":"/bin/bash"}function Mn(e,t){try{let n=An().shell?.trim();if(n)return n}catch{}return t.SHELL?.trim()||We(e)}function Nn(e,t){let n=Ln(e);if(n==="csh"||n==="tcsh")return{args:["-c",t],argv0:`-${n}`};return{args:["-i","-l","-c",t]}}function Bn(e){let t=e.indexOf(oe);if(t===-1)return;let n=e.indexOf(Fe,t);if(n===-1)return;let o=e.slice(t+oe.length,n).trim();return o.length>0?o:void 0}function Fn(e,t){let n=[...e.split(B),...t.split(B)].map((o)=>o.trim()).filter((o)=>o.length>0);return Array.from(new Set(n)).join(B)}function Vn(e,t=Ve){return new Promise((n)=>{let o=Nn(e,Un),r=Dn(e,o.args,{argv0:o.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),i="",a=0,u=()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}},c=!1,d=(m)=>{if(c)return;c=!0,clearTimeout(s),r.stdout?.destroy(),u(),n(m)},s=setTimeout(()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}d(void 0)},t);r.stdout?.on("data",(m)=>{if(c)return;if(a+=m.length,a>65536){d(void 0);return}i+=m.toString("utf8")}),r.on("error",()=>d(void 0)),r.on("close",()=>d(Bn(i)))})}async function $e(e){let t=e?.platform??process.platform,n=e?.env??process.env;if(t==="win32")return{status:"skipped",reason:"windows"};if(n[Be]?.trim())return{status:"skipped",reason:Be};let o=e?.userShell??Mn(t,n),r=e?.fallbackShell??We(t),i=e?.timeoutMs??Ve,a=o===r?[[o,i]]:[[o,i],[r,i/2]];for(let[u,c]of a){let d=await Vn(u,c);if(!d)continue;let s=Fn(d,n.PATH??"");return n.PATH=s,{status:"applied",pathEntries:s.split(B).length,shell:u}}return{status:"failed",shell:o}}var Ge={readHubDiscovery:b,clearHubDiscoveryIfOwned:ge,probeProcess:(e)=>{process.kill(e,0)},requestHubShutdown:M,ensureDetachedHubServer:L,claimHubDaemonProcess:$n,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:$e,setHomeDirIfUnset:Gn,homeDir:Wn,cwd:()=>process.cwd(),env:process.env,writeOutput:(e)=>process.stdout.write(e)};function je(e,t){let n=e.indexOf(t);return(n>=0?e[n+1]:void 0)?.trim()||void 0}function qe(e,t){let n=je(e,"--discovery-path");if(!n)throw Error("--discovery-path is required for remote Hub management");return t.env.CLINE_HUB_DISCOVERY_PATH=n,n}async function jn(e=process.argv,t=Ge){t.setHomeDirIfUnset(t.homeDir()),await t.ensureLoginShellPath();let n=je(e,"--cwd")??t.cwd();qe(e,t);let o=await t.ensureDetachedHubServer(n,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});t.writeOutput(`${JSON.stringify({...o,cwd:n,platform:process.platform,arch:process.arch})}
|
|
4
|
+
`)}async function Ke(e=process.argv,t=Ge){if(e.includes("--remote-hub-stop")){let n=qe(e,t),o=await t.readHubDiscovery(n);if(o&&typeof o.pid==="number"&&Number.isInteger(o.pid)&&o.pid>0)try{t.probeProcess(o.pid)}catch(r){if(r?.code==="ESRCH")return await t.clearHubDiscoveryIfOwned(n,o.hubId),!0}if(o&&!await t.requestHubShutdown(o.url,o.authToken))throw Error("Remote Hub shutdown failed");return!0}if(e.includes("--remote-hub-ensure"))return await jn(e,t),!0;if(t.claimHubDaemonProcess())return await t.loadHubDaemon(),!0;return!1}(async()=>{if(!await Ke())throw Error("A remote helper command is required")})().catch((e)=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
|
|
5
5
|
`),process.exitCode=1});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`,{encoding:"utf8"}),await
|
|
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
|
|
1
|
+
import{homedir as Vn}from"node:os";import{claimHubDaemonProcess as Wn}from"@cline/shared";import{setHomeDirIfUnset as $n}from"@cline/shared/storage";import{createSessionId as mn,ensureLoopbackProxyBypass as Ae,isHubProtocolCompatible as hn,resolveClineBuildEnv as bn,resolveHubCommandTimeoutMs as gn}from"@cline/shared";import yn from"ws";var H={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.88-nightly.1790735522",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 re="session_not_found";class F extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}import{spawn as Ot}from"node:child_process";import{closeSync as Dt,mkdirSync as At,openSync as Lt,readFileSync as Ut,unlinkSync as Mt}from"node:fs";import{basename as Nt,dirname as Bt,join as Ft}from"node:path";import{fileURLToPath as Vt}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as Wt,isBunEmbeddedModulePath as $t,isHubDaemonProcess as Gt,resolveClineBuildEnv as Te,withResolvedClineBuildEnv as jt}from"@cline/shared";import{createHash as Je,randomBytes as Ye}from"node:crypto";import{mkdir as W,open as ie,readFile as de,rename as Xe,rm as I,writeFile as Ze}from"node:fs/promises";import{dirname as le,join as G}from"node:path";import{ensureLoopbackProxyBypass as Qe,isHubProtocolCompatible as et}from"@cline/shared";import{resolveClineDataDir as P,resolveClineDir as Zn}from"@cline/shared/storage";var tt="CLINE_HUB_DISCOVERY_PATH",nt="CLINE_HUB_BUILD_ID",ot="CLINE_HUB_BUILD_EPOCH_MS",rt=30000,it=15000,se=100;function st(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function at(e){return Je("sha256").update(e).digest("hex").slice(0,12)}function ct(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function ae(e){return new Promise((t)=>setTimeout(t,e))}function ut(e){return`${e}.lock`}async function dt(e){try{let t=JSON.parse(await de(G(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function V(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[nt]?.trim();if(e)return e;return"sdk-v1-0982e787428525296f7c82ef42aff77c3cee5087192bf30b19f8018599e7f0ab".trim()||`source-${String(H.version)}`}function lt(){let e=Number(process.env[ot]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790735549231)?1790735549231:void 0}function x(e,t=k()){let n=et(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ce(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ue(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function pt(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function pe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ce(e.buildEpochMs),i=ce(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let a=ue(e.coreVersion),u=ue(t.coreVersion);if(a&&u){let c=pt(a,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function fe(){return{buildId:k(),buildEpochMs:lt(),coreVersion:String(H.version)}}function O(e,t){let n=t?.self??fe(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return pe(n,e)<=0}function me(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${at(e)}`,n=process.env[tt]?.trim()||G(P(),"locks","hub","owners",`${st(t)}.json`);return{ownerId:t,discoveryPath:n}}async function g(e){try{let t=JSON.parse(await de(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function he(e,t){await j(e,async()=>{let n=le(e);await W(n,{recursive:!0});let o=`${e}.${process.pid}.${Ye(6).toString("hex")}.tmp`,r;try{r=await ie(o,"wx",384),await r.writeFile(`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{encoding:"utf8"}),await r.sync(),await r.close(),r=void 0,await Xe(o,e);let i;try{i=await ie(n,"r"),await i.sync()}catch{}finally{await i?.close().catch(()=>{return})}}catch(i){throw await r?.close().catch(()=>{return}),await I(o,{force:!0}).catch(()=>{return}),i}})}async function C(e){await j(e,async()=>{await I(e,{force:!0}).catch(()=>{return})})}async function be(e,t){return await j(e,async()=>{if((await g(e))?.hubId!==t)return!1;return await I(e,{force:!0}),!0})}async function ge(e,t,n){let o=ut(e);await W(le(o),{recursive:!0});let r=Date.now()+it;while(!0){try{await W(o,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let u=await dt(o);if(!u){if(Date.now()>=r){await V(o);continue}await ae(se);continue}let c=Date.now()-Date.parse(u.acquiredAt);if(!ct(u.pid)||c>rt){await V(o);continue}if(Date.now()>=r)throw Error(`Timed out waiting for hub ${t} lock ${o}`);await ae(se);continue}try{return await Ze(G(o,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
3
|
+
`,"utf8"),await n()}finally{await V(o)}}}function j(e,t){return ge(`${e}.mutation`,"discovery mutation",t)}function ye(e,t){return ge(e,"startup",t)}async function D(e,t){Qe();try{let n=await fetch(t?.authToken?ft(e):ve(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let o=await n.json();if(typeof o.protocolVersion!=="string"||typeof o.host!=="string"||typeof o.port!=="number"||typeof o.url!=="string")return;return{protocolVersion:o.protocolVersion,minClientProtocolVersion:typeof o.minClientProtocolVersion==="string"?o.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof o.maxClientProtocolVersion==="string"?o.maxClientProtocolVersion:void 0,capabilities:Array.isArray(o.capabilities)?o.capabilities.filter((r)=>typeof r==="string"):void 0,coreVersion:typeof o.coreVersion==="string"?o.coreVersion:void 0,buildId:typeof o.buildId==="string"?o.buildId:void 0,buildEpochMs:typeof o.buildEpochMs==="number"?o.buildEpochMs:void 0,host:o.host,port:o.port,url:o.url,hubId:typeof o.hubId==="string"?o.hubId:void 0,authToken:typeof o.authToken==="string"?o.authToken:void 0,pid:typeof o.pid==="number"?o.pid:void 0,startedAt:typeof o.startedAt==="string"?o.startedAt:void 0,updatedAt:typeof o.updatedAt==="string"?o.updatedAt:void 0}}catch{return}}function we(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function ve(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function ft(e){let t=new URL(ve(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as mt,CLINE_HUB_PORT as ht,resolveClineBuildEnv as bt}from"@cline/shared";var gt="CLINE_HUB_HOST",yt="CLINE_HUB_PORT",wt="CLINE_HUB_PATHNAME",vt="127.0.0.1",St=ht,kt="/hub";function Se(e){return bt(e)==="development"?mt:St}function Ct(e={}){return(e.env??process.env)[gt]?.trim()||vt}function Ht(e={}){let n=(e.env??process.env)[yt]?.trim();if(!n)return Se(e);let o=Number.parseInt(n,10);if(!Number.isInteger(o)||o<1||o>65535)return Se(e);return o}function Pt(e={}){return(e.env??process.env)[wt]?.trim()||kt}function ke(e={},t={}){return{host:e.host??Ct(t),port:e.port??Ht(t),pathname:e.pathname??Pt(t)}}import{join as Tt}from"node:path";import{execFile as _t}from"node:child_process";import{promisify as Rt}from"node:util";import{processWorkspaceInfo as so}from"@cline/shared";import co from"simple-git";var uo=Rt(_t);var Et="shared:cline",It="CLINE_HUB_DISCOVERY_PATH",xt="hub-production";function _(e=Et){return me(`${e}@${k()}`)}function A(){return{ownerId:xt,discoveryPath:process.env[It]?.trim()||Tt(P(),"locks","hub","production.json")}}var Ce=15000,qt=200,He=3000,Kt=100,zt=[100,250,500,1000,2000],Jt="--cline-hub-daemon",Yt=3,Xt=60000,Pe=new Map;function Zt(e,t=Date.now()){let n=Pe.get(e);if(!n||t-n.windowStartedAt>Xt)return Pe.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Yt}function Qt(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function en(){try{let e=Ft(P(),"logs","hub-daemon.log");return At(Bt(e),{recursive:!0}),{fd:Lt(e,"a"),logPath:e}}catch{return}}function tn(){return Te()==="production"?A():_()}function R(e){return O(e)}function nn(e){try{let t=JSON.parse(Ut(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function q(e){try{Mt(`${e}.superseded`)}catch{}}function _e(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function T(e,t){try{return await D(e,{authToken:t})}catch{return}}async function Re(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await T(e))?.url)return!0;await new Promise((r)=>setTimeout(r,Kt))}return!1}async function z(e,t){if(!Zt(e.url))return!1;await E(e.url,e.authToken,"retired by newer install").catch(()=>!1),await M(e.url,e.authToken).catch(()=>!1);let n=await Re(e.url,He);if(!n&&e.pid&&on(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Re(e.url,He)}if(n)await C(t).catch(()=>{return});return n}function on(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function rn(e){try{return(await J(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function K(e,t){if(R(e))return"reusable";let n=await E(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await rn(e)){if(n)await E(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let o=await z(e,t);if(!o&&n)await E(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return o?"retired":"failed"}async function sn(e){if(Te()!=="production")return;let t=_();if(t.discoveryPath===e.discoveryPath)return;let n=await g(t.discoveryPath);if(n?.url)await z(n,t.discoveryPath);else await C(t.discoveryPath).catch(()=>{return})}function an(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return Vt(new URL(`./entry.${e}`,import.meta.url))}function cn(e,t){if($t(e))return[Jt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function un(e,t){let n=an(),o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let r=Nt(o).toLowerCase().includes("bun"),i=cn(n,r);return{launcher:o,args:[...i,"--cwd",e,...Qt(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...jt(process.env),CLINE_NO_INTERACTIVE:"1",[Wt]:"1"}}}function dn(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function ln(e,t={}){if(Gt())return;let n=un(e,t),o=en();try{Ot(n.launcher,n.args,{detached:!0,stdio:o?["ignore",o.fd,o.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(o)Dt(o.fd)}}async function pn(e,t={}){for(let n=0;;n++)try{ln(e,t);return}catch(o){let r=zt[n];if(!dn(o)||r===void 0)throw o;await new Promise((i)=>setTimeout(i,r))}}async function fn(e,t,n={}){let o=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),r=ke(n),i=we(r.host,r.port,r.pathname),a=(l)=>{if(!o)U(l.url,l.authToken);return l};await sn(e).catch(()=>{return});let u=await g(e.discoveryPath),c=u?.url?void 0:nn(e.discoveryPath),d=!1;if(u?.url){let l=u.authToken;if(!l)d=!0,await z(u,e.discoveryPath);else{let p=await T(u.url,l);if(p?.url&&R(p)&&await y(p.url,{authToken:l}))return q(e.discoveryPath),a({url:p.url,authToken:l});if(p?.url){if(await K({...p,authToken:l},e.discoveryPath)==="deferred_busy"&&await y(p.url,{authToken:l}))return a({url:p.url,authToken:l})}else await C(e.discoveryPath).catch(()=>{return})}}let s=await T(i);if(s?.url){let l=_e(s,u??c,i);if(R(s)){let h=[s.authToken,u?.authToken,c?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0);for(let S of h){if(!await y(s.url,{authToken:S}))continue;let Ke={hubId:s.hubId??`repaired-${s.port}`,protocolVersion:s.protocolVersion,minClientProtocolVersion:s.minClientProtocolVersion,maxClientProtocolVersion:s.maxClientProtocolVersion,capabilities:s.capabilities,coreVersion:s.coreVersion,buildId:s.buildId,authToken:S,host:s.host,port:s.port,url:s.url,pid:s.pid??u?.pid??c?.pid,startedAt:s.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await he(e.discoveryPath,Ke)}catch{}return q(e.discoveryPath),a({url:s.url,authToken:S})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${d?" 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 p=await K(l,e.discoveryPath);if(p==="deferred_busy"){for(let h of[l.authToken,u?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0))if(await y(s.url,{authToken:h}))return a({url:s.url,authToken:h});if(n.allowPortFallback!==!0&&r.port!==0)throw Error(`An older Cline Hub is running at ${i} 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(p==="failed"&&n.allowPortFallback!==!0&&r.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let b=n.allowPortFallback===!0&&r.port!==0?{...r,port:0}:r;await pn(t,{...b,manageConnectors:n.manageConnectors});let w=Date.now()+Ce;while(Date.now()<w){let l=await g(e.discoveryPath);if(l?.url&&l.authToken){let h=await T(l.url,l.authToken);if(h?.url&&R(h)&&await y(h.url,{authToken:l.authToken}))return q(e.discoveryPath),a({url:h.url,authToken:l.authToken})}let p=await T(i);if(p?.url&&!R(p)){let h=_e(p,l??c,i),v=await K(h,e.discoveryPath);if(v==="deferred_busy"&&l?.authToken&&await y(p.url,{authToken:l.authToken}))return a({url:p.url,authToken:l.authToken});if(v==="failed"&&n.allowPortFallback!==!0&&r.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((h)=>setTimeout(h,qt))}throw Error(`Timed out after ${Ce}ms waiting for detached hub startup.`)}async function L(e,t={}){let n=tn();return await ye(n.discoveryPath,async()=>fn(n,e,t))}function wn(){return bn()==="production"?A():_()}function vn(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Le(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return Le(e.data);return String(e)}function Sn(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function Ee(e){let t=e,n=Sn(t.reason);return new f("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:X,{closeCode:t.code,closeReason:n||void 0})}function Ie(e,t){if(e instanceof f)return e;if(e instanceof Error)return new f("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new f("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new f("hub_connect_failed",n);let o=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new f("hub_connect_failed",o?`Failed to connect to hub at ${t.toString()} (${o} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var Y="*",N=8000,kn="cline-hub-auth.",Ue=new Map,Me=new Set,Cn=3000;var X="Hub connection closed",Hn=250,Pn=5000,xe=0.5;class f extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function _n(e){return e instanceof f}class Z extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function ee(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let o=te(e.toString());return o?Ue.get(o):void 0}function Rn(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function te(e){if(!Rn(e))return;let t=new URL(Ne(e));return t.search="",t.hash="",t.toString()}function Oe(e){let t=te(e);return!!t&&Me.has(t)}function U(e,t){let n=te(e);if(n){if(Me.add(n),t?.trim())Ue.set(n,t)}return e}class ne{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 f("hub_connection_closed",X);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.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(e){if(this.capabilities=e.map((t)=>({...t})),!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 e=new URL(this.currentUrl),t=this.options.authToken?.trim()||ee(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,o=this.openSocket(e,t,n),r;this.connectPromise=o.then(async(a)=>{if(r=a,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,metadata:{...this.options.metadata,version:this.options.clientVersion??String(H.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{a.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let u of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(u));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(a){if(this.connectPromise===i)this.connectPromise=void 0;if(r&&this.socket===r){this.lastCloseError=Ie(a,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{r.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw a}}async openSocket(e,t,n){let o=this.options.resolveConnectionHeaders,r;if(o){let c;try{r=await Promise.race([Promise.resolve().then(()=>o()),new Promise((d,s)=>{c=setTimeout(()=>{s(new f("hub_connect_timeout",`Timed out resolving hub connection headers after ${N}ms`))},N)})])}catch(d){let s=d instanceof f?d:new f("hub_connect_failed",d instanceof Error?d.message:String(d));if(n===this.connectGeneration)this.lastCloseError=s;throw s}finally{clearTimeout(c)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(r&&Object.keys(r).some((c)=>c.toLowerCase()==="sec-websocket-protocol")){let c=new f("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=c;throw c}let i=r?new yn(e.toString(),{headers:{...r}}):new(vn())(e.toString(),t?[`${kn}${t}`]:void 0);this.socket=i;let a=!1,u=new Promise((c,d)=>{let s=!1,m=setTimeout(()=>{if(s)return;s=!0,a=!0;let b=new f("hub_connect_timeout",`Timed out connecting to hub after ${N}ms`);if(this.socket===i)this.lastCloseError=b,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}d(b)},N);i.addEventListener("open",()=>{if(s)return;s=!0,clearTimeout(m),c()}),i.addEventListener("error",(b)=>{if(s)return;s=!0,clearTimeout(m);let w=Ie(b,e);if(this.socket===i)this.lastCloseError=w,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;d(w)}),i.addEventListener("close",(b)=>{if(s)return;s=!0,clearTimeout(m);let w=a?this.lastCloseError:Ee(b);if(this.socket===i){if(!a)this.lastCloseError=w,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}d(w)})});return i.addEventListener("message",(c)=>{this.handleFrame(JSON.parse(Le(c)))}),i.addEventListener("close",(c)=>{if(this.socket!==i)return;if(!a)this.lastCloseError=Ee(c),this.sawSocketClose=!0;this.registered=!1;for(let d of this.pendingReplies.values())d.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await u,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,o={listener:e,sessionId:n};return this.listeners.add(o),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(o))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,o){let r=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,o)}catch(a){if(!i||r>=1||!await this.recoverLocalHubTransport(a))throw a;r+=1}}async commandOnce(e,t,n,o,r=!0){if(r)await this.connect();o?.beforeDispatch?.();let i=mn("hubreq_");o?.onDispatch?.(i);let a=gn(e,o?.timeoutMs),u=new Promise((d,s)=>{let m=a===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;s(new Z(e,"hub_command_timeout",`Hub command ${e} timed out after ${a}ms (hub=${this.currentUrl}, requestId=${i}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},a);this.pendingReplies.set(i,{resolve:(b)=>{if(m)clearTimeout(m);d(b)},reject:(b)=>{if(m)clearTimeout(m);s(b)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:a,payload:t}})}catch(d){throw this.pendingReplies.delete(i),d}let c=await u;if(!c.ok){if(c.error?.code===re){let d=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new F(d,c.error.message)}throw new Z(e,c.error?.code,c.error?.message??`Hub command ${e} failed`)}return c}async recoverLocalHubTransport(e){if(!Oe(this.currentUrl)||!_n(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await De({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,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 e=Math.min(Hn*2**this.reconnectAttempt,Pn),t=Math.round(e*(1-xe)+Math.random()*e*xe);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Oe(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await De({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new f("hub_connection_closed",X);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.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(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new f("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),o=(this.subscriptionCounts.get(n)??0)+t;if(o<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,o),t>0&&o===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??Y}subscriptionSessionIdFromKey(e){return e===Y?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let o of[Y,n]){if(!o||!this.subscriptionCounts.has(o))continue;let r=this.lastEventSequenceByKey.get(o)??0;if(t>r)this.lastEventSequenceByKey.set(o,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Ne(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function y(e,t){let n=new ne({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function Q(e,t){let n=Ne(e),o=await D(n,{authToken:t?.authToken});if(!o)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let r=k(),i=x(o,r);if(!i.compatible&&!O(o))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!hn(o).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await y(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function Tn(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,o=new Set;for(let r of t){if(!r||typeof r!=="object")continue;let i=r.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let a of i){let u=a&&typeof a==="object"?a.clientId:void 0;if(typeof u==="string"&&u.trim())o.add(u)}}return{activeSessionCount:n,participantClientCount:o.size}}async function J(e,t,n){let o=new ne({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let r=await o.command("session.list",{limit:500},void 0,{timeoutMs:Cn});return Tn(r.payload)}finally{await o.dispose().catch(()=>{return})}}async function En(e,t,n){try{return(await J(e,t,n)).activeSessionCount===0}catch{return!1}}async function In(e,t){let n=`${e.discoveryPath}.superseded`,o=await g(n);if(!o?.url||!o.authToken)return;let r=await Q(o.url,{authToken:o.authToken});if(r.status!=="compatible")return;if(await En(r.url,o.authToken,t))return;return U(r.url,o.authToken)}async function xn(e={}){if(e.endpoint?.trim()){let r=await Q(e.endpoint);return r.status==="compatible"?r.url:void 0}let t=wn(),n=await g(t.discoveryPath);if(!n?.url)return await In(t,e);let o=await Q(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(o.status==="compatible")return U(o.url,n.authToken);if(o.status==="protocol_mismatch")await C(t.discoveryPath).catch(()=>{return});return}async function De(e={}){let t=await xn(e);if(t&&await y(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await L(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function E(e,t,n,o){Ae();let r=new URL(e),i=t?.trim()||ee(r);if(r.protocol==="ws:")r.protocol="http:";else if(r.protocol==="wss:")r.protocol="https:";if(r.pathname="/drain",r.hash="",n)r.searchParams.set("reason",n);if(o?.off)r.searchParams.set("off","1");return(await fetch(r,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function M(e,t){Ae();let n=new URL(e),o=t?.trim()||ee(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:o?{authorization:`Bearer ${o}`}:void 0})).ok}import{spawn as On}from"node:child_process";import{userInfo as Dn}from"node:os";import{basename as An,delimiter as B}from"node:path";var oe="__CLINE_SIDECAR_PATH_START__",Fe="__CLINE_SIDECAR_PATH_END__",Ve=5000,Ln=`/bin/sh -c 'printf "%s%s%s" "${oe}" "$PATH" "${Fe}"'`,Be="CLINE_SIDECAR_SKIP_SHELL_PATH";function We(e){return e==="darwin"?"/bin/zsh":"/bin/bash"}function Un(e,t){try{let n=Dn().shell?.trim();if(n)return n}catch{}return t.SHELL?.trim()||We(e)}function Mn(e,t){let n=An(e);if(n==="csh"||n==="tcsh")return{args:["-c",t],argv0:`-${n}`};return{args:["-i","-l","-c",t]}}function Nn(e){let t=e.indexOf(oe);if(t===-1)return;let n=e.indexOf(Fe,t);if(n===-1)return;let o=e.slice(t+oe.length,n).trim();return o.length>0?o:void 0}function Bn(e,t){let n=[...e.split(B),...t.split(B)].map((o)=>o.trim()).filter((o)=>o.length>0);return Array.from(new Set(n)).join(B)}function Fn(e,t=Ve){return new Promise((n)=>{let o=Mn(e,Ln),r=On(e,o.args,{argv0:o.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),i="",a=0,u=()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}},c=!1,d=(m)=>{if(c)return;c=!0,clearTimeout(s),r.stdout?.destroy(),u(),n(m)},s=setTimeout(()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}d(void 0)},t);r.stdout?.on("data",(m)=>{if(c)return;if(a+=m.length,a>65536){d(void 0);return}i+=m.toString("utf8")}),r.on("error",()=>d(void 0)),r.on("close",()=>d(Nn(i)))})}async function $e(e){let t=e?.platform??process.platform,n=e?.env??process.env;if(t==="win32")return{status:"skipped",reason:"windows"};if(n[Be]?.trim())return{status:"skipped",reason:Be};let o=e?.userShell??Un(t,n),r=e?.fallbackShell??We(t),i=e?.timeoutMs??Ve,a=o===r?[[o,i]]:[[o,i],[r,i/2]];for(let[u,c]of a){let d=await Fn(u,c);if(!d)continue;let s=Bn(d,n.PATH??"");return n.PATH=s,{status:"applied",pathEntries:s.split(B).length,shell:u}}return{status:"failed",shell:o}}var Ge={readHubDiscovery:g,clearHubDiscoveryIfOwned:be,probeProcess:(e)=>{process.kill(e,0)},requestHubShutdown:M,ensureDetachedHubServer:L,claimHubDaemonProcess:Wn,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:$e,setHomeDirIfUnset:$n,homeDir:Vn,cwd:()=>process.cwd(),env:process.env,writeOutput:(e)=>process.stdout.write(e)};function je(e,t){let n=e.indexOf(t);return(n>=0?e[n+1]:void 0)?.trim()||void 0}function qe(e,t){let n=je(e,"--discovery-path");if(!n)throw Error("--discovery-path is required for remote Hub management");return t.env.CLINE_HUB_DISCOVERY_PATH=n,n}async function Gn(e=process.argv,t=Ge){t.setHomeDirIfUnset(t.homeDir()),await t.ensureLoginShellPath();let n=je(e,"--cwd")??t.cwd();qe(e,t);let o=await t.ensureDetachedHubServer(n,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});t.writeOutput(`${JSON.stringify({...o,cwd:n,platform:process.platform,arch:process.arch})}
|
|
4
|
+
`)}async function qo(e=process.argv,t=Ge){if(e.includes("--remote-hub-stop")){let n=qe(e,t),o=await t.readHubDiscovery(n);if(o&&typeof o.pid==="number"&&Number.isInteger(o.pid)&&o.pid>0)try{t.probeProcess(o.pid)}catch(r){if(r?.code==="ESRCH")return await t.clearHubDiscoveryIfOwned(n,o.hubId),!0}if(o&&!await t.requestHubShutdown(o.url,o.authToken))throw Error("Remote Hub shutdown failed");return!0}if(e.includes("--remote-hub-ensure"))return await Gn(e,t),!0;if(t.claimHubDaemonProcess())return await t.loadHubDaemon(),!0;return!1}export{qo as runRemoteHelperEntrypoint,Gn as runRemoteHubEnsure};
|
|
@@ -55,5 +55,6 @@ export declare function legacyTokenUsageFromUsageEvent(event: Extract<AgentEvent
|
|
|
55
55
|
cacheWriteTokens: number;
|
|
56
56
|
cacheReadTokens: number;
|
|
57
57
|
totalCost?: number;
|
|
58
|
+
reasoningTokenCount?: number;
|
|
58
59
|
};
|
|
59
60
|
export declare function handleAgentEvent(ctx: AgentEventContext, event: AgentEvent, overrides?: AgentTelemetryContextOverrides): void;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type GitCommand } from "../workspace/workspace-manifest";
|
|
2
|
+
export type { GitCommand } from "../workspace/workspace-manifest";
|
|
3
|
+
export type CloudHandoffGitContext = {
|
|
4
|
+
repoUrl: string;
|
|
5
|
+
branch: string;
|
|
6
|
+
headSha: string;
|
|
7
|
+
workspaceRelativePath?: string;
|
|
8
|
+
};
|
|
9
|
+
export type CloudHandoffGitPreflightErrorCode = "not_git_repository" | "dirty_worktree" | "detached_head" | "missing_upstream" | "unsupported_remote" | "remote_branch_missing" | "unpushed_commits" | "git_command_failed";
|
|
10
|
+
export declare class CloudHandoffGitPreflightError extends Error {
|
|
11
|
+
readonly code: CloudHandoffGitPreflightErrorCode;
|
|
12
|
+
constructor(code: CloudHandoffGitPreflightErrorCode, message: string, options?: ErrorOptions);
|
|
13
|
+
}
|
|
14
|
+
/** Converts supported GitHub clone URLs to the URL expected by cloud sessions. */
|
|
15
|
+
export declare function normalizeGitHubRemoteUrl(remoteUrl: string): string | null;
|
|
16
|
+
/**
|
|
17
|
+
* Refuses handoff unless a fresh GitHub clone of the upstream branch will be
|
|
18
|
+
* byte-for-byte anchored at the current local commit.
|
|
19
|
+
*/
|
|
20
|
+
export declare function preflightCloudHandoffGit(input: {
|
|
21
|
+
cwd: string;
|
|
22
|
+
git?: GitCommand;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
}): Promise<CloudHandoffGitContext>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { CloudHandoffFingerprint, CloudHandoffMetadata } from "./types";
|
|
2
|
+
export declare function createCloudHandoffFingerprint(input: CloudHandoffFingerprint): CloudHandoffFingerprint;
|
|
3
|
+
export declare function cloudHandoffFingerprintsEqual(left: CloudHandoffFingerprint | undefined, right: CloudHandoffFingerprint | undefined): boolean;
|
|
4
|
+
export declare function readCloudHandoffMetadata(metadata: unknown): CloudHandoffMetadata | undefined;
|
|
5
|
+
export declare function mergeCloudHandoffMetadata(metadata: Record<string, unknown> | null | undefined, handoff: CloudHandoffMetadata): Record<string, unknown>;
|
|
6
|
+
export declare function clearCloudHandoffMetadata(metadata: Record<string, unknown> | null | undefined): Record<string, unknown>;
|
|
7
|
+
export declare function buildCloudHandoffDashboardUrl(appBaseUrl: string, outerSessionId: string): string;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Compares the durable JSON wire shape, including image content and order. */
|
|
2
|
+
export declare function cloudHandoffTranscriptsEqual(localMessages: readonly unknown[], cloudMessages: readonly unknown[]): boolean;
|
|
3
|
+
export declare class CloudHandoffTranscriptMismatchError extends Error {
|
|
4
|
+
constructor(localCount: number, cloudCount: number);
|
|
5
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export type CloudHandoffFingerprint = {
|
|
2
|
+
repoUrl: string;
|
|
3
|
+
branch: string;
|
|
4
|
+
headSha: string;
|
|
5
|
+
modelId: string;
|
|
6
|
+
organizationId?: string;
|
|
7
|
+
/** Repository-relative source cwd; omitted when the session is at repo root. */
|
|
8
|
+
workspaceRelativePath?: string;
|
|
9
|
+
/** Source interaction mode; omitted for the default Act mode. */
|
|
10
|
+
mode?: "plan" | "yolo" | "zen";
|
|
11
|
+
};
|
|
12
|
+
export type CloudHandoffMetadata = {
|
|
13
|
+
toCloudSessionId: string;
|
|
14
|
+
handedOffAt: string;
|
|
15
|
+
status: "pending" | "complete";
|
|
16
|
+
innerSessionId?: string;
|
|
17
|
+
dashboardUrl?: string;
|
|
18
|
+
fingerprint?: CloudHandoffFingerprint;
|
|
19
|
+
};
|
|
20
|
+
export type CloudHandoffDestination = "in_app" | "external";
|
|
21
|
+
export type CloudHandoffProgressPhase = "checking" | "creating" | "provisioning" | "connecting" | "seeding" | "verifying" | "starting" | "complete";
|
|
22
|
+
export type CloudHandoffProgress = {
|
|
23
|
+
phase: CloudHandoffProgressPhase;
|
|
24
|
+
message: string;
|
|
25
|
+
sessionId?: string;
|
|
26
|
+
dashboardUrl?: string;
|
|
27
|
+
};
|
|
28
|
+
export type CloudHandoffResult = {
|
|
29
|
+
outerSessionId: string;
|
|
30
|
+
innerSessionId: string;
|
|
31
|
+
dashboardUrl: string;
|
|
32
|
+
destination: CloudHandoffDestination;
|
|
33
|
+
warning?: string;
|
|
34
|
+
warningKind?: "unqueued" | "unconfirmed";
|
|
35
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PostHog as s}from"posthog-node";function a(e,t){return new s(e,{host:"https://data.cline.bot",...t})}class o{client;settings;logger;constructor(e){if(!e.client)throw Error("PostHog client is required for feature flags");this.logger=e.config.logger,this.settings={enabled:!0},this.client=e.client}async getAllFlagsAndPayloads(e){if(!this.enabled)return;let t=this.resolveDistinctId(e.context);if(!t)return this.logger?.log?.("PostHog feature flags requested without a distinct ID"),{};try{return await this.client.getAllFlagsAndPayloads(t,{flagKeys:e.flagKeys?[...e.flagKeys]:void 0})}catch(r){return this.logger?.error?.("Error getting PostHog feature flags",{error:r}),{}}}get enabled(){return this.settings.enabled}getSettings(){return{...this.settings}}async dispose(){try{await this.client.shutdown()}catch(e){this.logger?.error?.("Error shutting down PostHog feature flags client",{error:e})}}resolveDistinctId(e){return e?.distinctId?.trim()||e?.userId?.trim()||void 0}}export{
|
|
1
|
+
import{PostHog as s}from"posthog-node";function a(e,t){return new s(e,{host:"https://data.cline.bot",...t})}class o{client;settings;logger;constructor(e){if(!e.client)throw Error("PostHog client is required for feature flags");this.logger=e.config.logger,this.settings={enabled:!0},this.client=e.client}async getAllFlagsAndPayloads(e){if(!this.enabled)return;let t=this.resolveDistinctId(e.context);if(!t)return this.logger?.log?.("PostHog feature flags requested without a distinct ID"),{};try{return await this.client.getAllFlagsAndPayloads(t,{flagKeys:e.flagKeys?[...e.flagKeys]:void 0})}catch(r){return this.logger?.error?.("Error getting PostHog feature flags",{error:r}),{}}}get enabled(){return this.settings.enabled}getSettings(){return{...this.settings}}async dispose(){try{await this.client.shutdown()}catch(e){this.logger?.error?.("Error shutting down PostHog feature flags client",{error:e})}}resolveDistinctId(e){return e?.distinctId?.trim()||e?.userId?.trim()||void 0}}export{o as PostHogFeatureFlagsProvider,a as buildClinePostHogClient};
|
|
@@ -278,11 +278,14 @@ export declare function captureTokenUsage(telemetry: ITelemetryService | undefin
|
|
|
278
278
|
ulid: string;
|
|
279
279
|
/** Uncached input tokens only — disjoint from the cache buckets. */
|
|
280
280
|
tokensIn: number;
|
|
281
|
+
/** Non-reasoning output tokens only — reasoningTokenCount is disjoint from this. */
|
|
281
282
|
tokensOut: number;
|
|
282
283
|
cacheWriteTokens?: number;
|
|
283
284
|
cacheReadTokens?: number;
|
|
284
285
|
/** This request's cost delta, not a running total. */
|
|
285
286
|
totalCost?: number;
|
|
287
|
+
/** Reasoning/thinking tokens for this request, reported separately since they're no longer folded into tokensOut. */
|
|
288
|
+
reasoningTokenCount?: number;
|
|
286
289
|
provider?: string;
|
|
287
290
|
model: string;
|
|
288
291
|
} & Partial<TelemetryAgentIdentityProperties>): void;
|