@cline/core 0.0.83 → 0.0.84
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/cron/service/schedule-tool.d.ts +3 -3
- package/dist/extensions/composio/composio-tools-extension.d.ts +13 -0
- package/dist/extensions/context/compaction-shared.d.ts +9 -1
- package/dist/extensions/context/compaction.d.ts +10 -2
- package/dist/extensions/tools/team/configured-agent-tool.d.ts +1 -3
- package/dist/hooks/hook-file-hooks.d.ts +27 -0
- package/dist/hooks/subprocess-runner.d.ts +23 -0
- package/dist/hooks/subprocess.d.ts +10 -0
- package/dist/hub/client/index.d.ts +7 -3
- package/dist/hub/daemon/entry.js +217 -214
- package/dist/hub/index.js +208 -205
- package/dist/hub/runtime-host/hub-runtime-host.d.ts +1 -0
- package/dist/hub/server/handlers/session-handlers.d.ts +1 -0
- package/dist/index.d.ts +8 -5
- package/dist/index.js +237 -235
- package/dist/remote/remote-helper-entry.js +2 -2
- package/dist/remote/remote-helper.js +2 -2
- package/dist/runtime/host/runtime-host.d.ts +2 -0
- package/dist/runtime/orchestration/oauth-refresh-lock.d.ts +6 -0
- package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +1 -0
- package/dist/runtime/turn-queue/pending-prompt-service.d.ts +1 -0
- package/dist/services/feature-flags/FeatureFlagsService.d.ts +2 -0
- package/dist/services/feature-flags/cline-account-feature-flags.d.ts +5 -0
- package/dist/services/global-settings.d.ts +3 -3
- package/dist/services/llms/cline-recommended-models.d.ts +1 -0
- package/dist/services/llms/handler-factory.d.ts +12 -0
- package/dist/services/llms/provider-settings.d.ts +18 -18
- package/dist/services/telemetry/core-events.d.ts +56 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/session/models/session-manifest.d.ts +1 -1
- package/dist/session/stores/session-manifest-store.d.ts +2 -4
- package/dist/tasks/agenda-task-tool.d.ts +2 -2
- package/dist/tasks/task-tool.d.ts +5 -5
- package/dist/types/chat-schema.d.ts +7 -7
- package/package.json +4 -4
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as n0}from"node:module";var s0=n0(import.meta.url);import{homedir as y2}from"node:os";import{claimHubDaemonProcess as b2}from"@cline/shared";import{setHomeDirIfUnset as h2}from"@cline/shared/storage";import{createSessionId as N2,isHubProtocolCompatible as K2,resolveClineBuildEnv as W2,resolveHubCommandTimeoutMs as G2}from"@cline/shared";import q2 from"ws";var $0="session_not_found";class v extends Error{sessionId;code="session_not_found";constructor(J,Q){super(Q??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as g1}from"node:child_process";import{closeSync as T1,mkdirSync as I1,openSync as P1,readFileSync as w1,unlinkSync as H1}from"node:fs";import{basename as k1,dirname as y1,join as b1}from"node:path";import{fileURLToPath as h1}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as m1,isHubDaemonProcess as v1,resolveClineBuildEnv as R0,withResolvedClineBuildEnv as u1}from"@cline/shared";import{createHash as d0,randomBytes as a0}from"node:crypto";import{mkdir as p,open as X0,readFile as N0,rename as o0,rm as T,writeFile as r0}from"node:fs/promises";import{dirname as K0,join as l}from"node:path";import{isHubProtocolCompatible as e0}from"@cline/shared";import{resolveClineDataDir as _,resolveClineDir as d2}from"@cline/shared/storage";var g={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.
|
|
1
|
+
import{createRequire as n0}from"node:module";var s0=n0(import.meta.url);import{homedir as y2}from"node:os";import{claimHubDaemonProcess as b2}from"@cline/shared";import{setHomeDirIfUnset as h2}from"@cline/shared/storage";import{createSessionId as N2,isHubProtocolCompatible as K2,resolveClineBuildEnv as W2,resolveHubCommandTimeoutMs as G2}from"@cline/shared";import q2 from"ws";var $0="session_not_found";class v extends Error{sessionId;code="session_not_found";constructor(J,Q){super(Q??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as g1}from"node:child_process";import{closeSync as T1,mkdirSync as I1,openSync as P1,readFileSync as w1,unlinkSync as H1}from"node:fs";import{basename as k1,dirname as y1,join as b1}from"node:path";import{fileURLToPath as h1}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as m1,isHubDaemonProcess as v1,resolveClineBuildEnv as R0,withResolvedClineBuildEnv as u1}from"@cline/shared";import{createHash as d0,randomBytes as a0}from"node:crypto";import{mkdir as p,open as X0,readFile as N0,rename as o0,rm as T,writeFile as r0}from"node:fs/promises";import{dirname as K0,join as l}from"node:path";import{isHubProtocolCompatible as e0}from"@cline/shared";import{resolveClineDataDir as _,resolveClineDir as d2}from"@cline/shared/storage";var g={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.84",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var J1="CLINE_HUB_DISCOVERY_PATH",Q1="CLINE_HUB_BUILD_ID",Z1="CLINE_HUB_BUILD_EPOCH_MS",$1=30000,X1=15000,j0=100;function j1(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function z1(J){return d0("sha256").update(J).digest("hex").slice(0,12)}function V1(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function z0(J){return new Promise((Q)=>setTimeout(Q,J))}function Y1(J){return`${J}.lock`}async function N1(J){try{let Q=JSON.parse(await N0(l(J,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function u(J){await T(J,{recursive:!0,force:!0}).catch(()=>{return})}function C(){let J=process.env[Q1]?.trim();if(J)return J;return"sdk-v1-0c7290d109800148a2ee6c68832123073f3e04b020ebdfd6a55983a47b314e02".trim()||`source-${String(g.version)}`}function K1(){let J=Number(process.env[Z1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1790047513229)?1790047513229:void 0}function I(J,Q=C()){let Z=e0(J);if(!Z.compatible)return Z;let $=J.buildId?.trim();if(!$)return{compatible:!1,reason:"missing_build"};if($!==Q)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function V0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function Y0(J){let Q=J?.trim().split(/[-+]/,1)[0];if(!Q)return;let Z=Q.split(".").map(($)=>Number($));if(Z.length===0||Z.some(($)=>!Number.isInteger($)||$<0))return;return Z}function W1(J,Q){for(let Z=0;Z<Math.max(J.length,Q.length);Z++){let $=J[Z]??0,X=Q[Z]??0;if($!==X)return $<X?-1:1}return 0}function W0(J,Q){let Z=J.buildId?.trim(),$=Q.buildId?.trim();if(Z&&$&&Z===$)return 0;let X=V0(J.buildEpochMs),j=V0(Q.buildEpochMs);if(X!==void 0&&j!==void 0&&X!==j)return X<j?-1:1;let V=Y0(J.coreVersion),N=Y0(Q.coreVersion);if(V&&N){let Y=W1(V,N);if(Y!==0)return Y}if(Z&&$&&Z!==$)return Z<$?-1:1;return 0}function G0(){return{buildId:C(),buildEpochMs:K1(),coreVersion:String(g.version)}}function P(J,Q){let Z=Q?.self??G0(),$=I(J,Z.buildId??"");if($.compatible)return!0;if($.reason!=="build_mismatch"&&$.reason!=="missing_build")return!1;return W0(Z,J)<=0}function q0(J=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${z1(J)}`,Z=process.env[J1]?.trim()||l(_(),"locks","hub","owners",`${j1(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}async function O(J){try{let Q=JSON.parse(await N0(J,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function F0(J,Q){await c(J,async()=>{let Z=K0(J);await p(Z,{recursive:!0});let $=`${J}.${process.pid}.${a0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(Q,null,2)}
|
|
2
2
|
`,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,await o0($,J);let j;try{j=await X0(Z,"r"),await j.sync()}catch{}finally{await j?.close().catch(()=>{return})}}catch(j){throw await X?.close().catch(()=>{return}),await T($,{force:!0}).catch(()=>{return}),j}})}async function x(J){await c(J,async()=>{await T(J,{force:!0}).catch(()=>{return})})}async function L0(J,Q){return await c(J,async()=>{if((await O(J))?.hubId!==Q)return!1;return await T(J,{force:!0}),!0})}async function B0(J,Q,Z){let $=Y1(J);await p(K0($),{recursive:!0});let X=Date.now()+X1;while(!0){try{await p($,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let N=await N1($);if(!N){if(Date.now()>=X){await u($);continue}await z0(j0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!V1(N.pid)||Y>$1){await u($);continue}if(Date.now()>=X)throw Error(`Timed out waiting for hub ${Q} lock ${$}`);await z0(j0);continue}try{return await r0(l($,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
3
|
-
`,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?G1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function G1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as q1,CLINE_HUB_PORT as F1,resolveClineBuildEnv as L1}from"@cline/shared";var B1="CLINE_HUB_HOST",O1="CLINE_HUB_PORT",A1="CLINE_HUB_PATHNAME",U1="127.0.0.1",M1=F1,f1="/hub";function M0(J){return L1(J)==="development"?q1:M1}function C1(J={}){return(J.env??process.env)[B1]?.trim()||U1}function x1(J={}){let Z=(J.env??process.env)[O1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function _1(J={}){return(J.env??process.env)[A1]?.trim()||f1}function f0(J={},Q={}){return{host:J.host??C1(Q),port:J.port??x1(Q),pathname:J.pathname??_1(Q)}}import{join as D1}from"node:path";import{processWorkspaceInfo as Q4}from"@cline/shared";import $4 from"simple-git";var R1="shared:cline",S1="CLINE_HUB_DISCOVERY_PATH",E1="hub-production";function D(J=R1){return q0(`${J}@${C()}`)}function H(){return{ownerId:E1,discoveryPath:process.env[S1]?.trim()||D1(_(),"locks","hub","production.json")}}var p1=8000,l1=200,C0=3000,c1=100,i1=[100,250,500,1000,2000],n1="--cline-hub-daemon",s1=3,t1=60000,x0=new Map;function d1(J,Q=Date.now()){let Z=x0.get(J);if(!Z||Q-Z.windowStartedAt>t1)return x0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=s1}function a1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function o1(){try{let J=b1(_(),"logs","hub-daemon.log");return I1(y1(J),{recursive:!0}),{fd:P1(J,"a"),logPath:J}}catch{return}}function r1(){return R0()==="production"?H():D()}function R(J){return P(J)}function e1(J){try{let Q=JSON.parse(w1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{H1(`${J}.superseded`)}catch{}}function _0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function S(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function D0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await S(J))?.url)return!0;await new Promise((X)=>setTimeout(X,c1))}return!1}async function s(J,Q){if(!d1(J.url))return!1;await E(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await D0(J.url,C0);if(!Z&&J.pid&&J2(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await D0(J.url,C0)}if(Z)await x(Q).catch(()=>{return});return Z}function J2(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function Q2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await E(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await Q2(J)){if(Z)await E(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await E(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Z2(J){if(R0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await x(Q.discoveryPath).catch(()=>{return})}function $2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return h1(new URL(`./entry.${J}`,import.meta.url))}function X2(J,Q){let Z=$2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=k1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[n1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...a1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...u1(process.env),CLINE_NO_INTERACTIVE:"1",[m1]:"1"}}}function j2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function z2(J,Q={}){if(v1())return;let Z=X2(J,Q),$=o1();try{g1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)T1($.fd)}}async function V2(J,Q={}){for(let Z=0;;Z++)try{z2(J,Q);return}catch($){let X=i1[Z];if(!j2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function Y2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Z2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:e1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await S(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await x(J.discoveryPath).catch(()=>{return})}}let z=await S(j);if(z?.url){let W=_0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let i0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,i0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await V2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+p1;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await S(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await S(j);if(G?.url&&!R(G)){let L=_0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,l1))}throw Error("Timed out waiting for detached hub startup.")}async function k(J,Q={}){let Z=r1();return await O0(Z.discoveryPath,async()=>Y2(Z,J,Q))}function F2(){return W2()==="production"?H():D()}function L2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function P0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return P0(J.data);return String(J)}function B2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function S0(J){let Q=J,Z=B2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function E0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,O2="cline-hub-auth.",w0=new Map,H0=new Set,A2=3000;var a="Hub connection closed",U2=250,M2=5000,g0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function f2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?w0.get($):void 0}function C2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!C2(J))return;let Q=new URL(k0(J));return Q.search="",Q.hash="",Q.toString()}function T0(J){let Q=J0(J);return!!Q&&H0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(H0.add(Z),Q?.trim())w0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=E0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new q2(J.toString(),{headers:{...X}}):new(L2())(J.toString(),Q?[`${O2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=E0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:S0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(P0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=S0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();let j=N2("hubreq_"),V=G2(J,$?.timeoutMs),N=new Promise((K,z)=>{let F=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;z(new o(J,"hub_command_timeout",`Hub command ${J} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(B)=>{if(F)clearTimeout(F);K(B)},reject:(B)=>{if(F)clearTimeout(F);z(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:Q}})}catch(K){throw this.pendingReplies.delete(j),K}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let K=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new v(K,Y.error.message)}throw new o(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!T0(this.currentUrl)||!f2(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let J=Math.min(U2*2**this.reconnectAttempt,M2),Q=Math.round(J*(1-g0)+Math.random()*J*g0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!T0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",a);for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Q){let Z=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Q)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Q?{sessionId:Q}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(J,Q){let Z=this.subscriptionKeyForSessionId(J),$=(this.subscriptionCounts.get(Z)??0)+Q;if($<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Z,$),Q>0&&$===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??d}subscriptionSessionIdFromKey(J){return J===d?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Q=J.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve(J.envelope);return}case"event":{let Q=J.envelope.sequence;if(typeof Q==="number"){let Z=J.envelope.sessionId?.trim();for(let $ of[d,Z]){if(!$||!this.subscriptionCounts.has($))continue;let X=this.lastEventSequenceByKey.get($)??0;if(Q>X)this.lastEventSequenceByKey.set($,Q)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==J.envelope.sessionId?.trim())continue;Z.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function k0(J){let Q=new URL(J);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function A(J,Q){let Z=new Q0({url:J,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function r(J,Q){let Z=k0(J),$=await w(Z,{authToken:Q?.authToken});if(!$)return{status:"unreachable",url:Z};if(Q?.requireCurrentBuild){let X=C(),j=I($,X);if(!j.compatible&&!P($))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!K2($).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await A(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function x2(J){let Q=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Z=0,$=new Set;for(let X of Q){if(!X||typeof X!=="object")continue;let j=X.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let N=V&&typeof V==="object"?V.clientId:void 0;if(typeof N==="string"&&N.trim())$.add(N)}}return{activeSessionCount:Z,participantClientCount:$.size}}async function t(J,Q,Z){let $=new Q0({url:J,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let X=await $.command("session.list",{limit:500},void 0,{timeoutMs:A2});return x2(X.payload)}finally{await $.dispose().catch(()=>{return})}}async function _2(J,Q,Z){try{return(await t(J,Q,Z)).activeSessionCount===0}catch{return!1}}async function D2(J,Q){let Z=`${J.discoveryPath}.superseded`,$=await O(Z);if(!$?.url||!$.authToken)return;let X=await r($.url,{authToken:$.authToken});if(X.status!=="compatible")return;if(await _2(X.url,$.authToken,Q))return;return y(X.url,$.authToken)}async function R2(J={}){if(J.endpoint?.trim()){let X=await r(J.endpoint);return X.status==="compatible"?X.url:void 0}let Q=F2(),Z=await O(Q.discoveryPath);if(!Z?.url)return await D2(Q,J);let $=await r(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if($.status==="compatible")return y($.url,Z.authToken);if($.status==="protocol_mismatch")await x(Q.discoveryPath).catch(()=>{return});return}async function I0(J={}){let Q=await R2(J);if(Q&&await A(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Q;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch{return}}async function E(J,Q,Z,$){let X=new URL(J),j=Q?.trim()||e(X);if(X.protocol==="ws:")X.protocol="http:";else if(X.protocol==="wss:")X.protocol="https:";if(X.pathname="/drain",X.hash="",Z)X.searchParams.set("reason",Z);if($?.off)X.searchParams.set("off","1");return(await fetch(X,{method:"POST",headers:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b(J,Q){let Z=new URL(J),$=Q?.trim()||e(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:$?{authorization:`Bearer ${$}`}:void 0})).ok}import{spawn as S2}from"node:child_process";import{userInfo as E2}from"node:os";import{basename as g2,delimiter as m}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",b0="__CLINE_SIDECAR_PATH_END__",h0=2000,T2=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${b0}"'`,y0="CLINE_SIDECAR_SKIP_SHELL_PATH";function m0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function I2(J,Q){try{let Z=E2().shell?.trim();if(Z)return Z}catch{}return Q.SHELL?.trim()||m0(J)}function P2(J,Q){let Z=g2(J);if(Z==="csh"||Z==="tcsh")return{args:["-c",Q],argv0:`-${Z}`};return{args:["-i","-l","-c",Q]}}function w2(J){let Q=J.indexOf(Z0);if(Q===-1)return;let Z=J.indexOf(b0,Q);if(Z===-1)return;let $=J.slice(Q+Z0.length,Z).trim();return $.length>0?$:void 0}function H2(J,Q){let Z=[...J.split(m),...Q.split(m)].map(($)=>$.trim()).filter(($)=>$.length>0);return Array.from(new Set(Z)).join(m)}function k2(J,Q=h0){return new Promise((Z)=>{let $=P2(J,T2),X=S2(J,$.args,{argv0:$.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),j="",V=0,N=()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}},Y=!1,K=(F)=>{if(Y)return;Y=!0,clearTimeout(z),X.stdout?.destroy(),N(),Z(F)},z=setTimeout(()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}K(void 0)},Q);X.stdout?.on("data",(F)=>{if(Y)return;if(V+=F.length,V>65536){K(void 0);return}j+=F.toString("utf8")}),X.on("error",()=>K(void 0)),X.on("close",()=>K(w2(j)))})}async function v0(J){let Q=J?.platform??process.platform,Z=J?.env??process.env;if(Q==="win32")return{status:"skipped",reason:"windows"};if(Z[y0]?.trim())return{status:"skipped",reason:y0};let $=J?.userShell??I2(Q,Z),X=J?.fallbackShell??m0(Q),j=J?.timeoutMs??h0,V=$===X?[[$,j]]:[[$,j],[X,j/2]];for(let[N,Y]of V){let K=await k2(N,Y);if(!K)continue;let z=H2(K,Z.PATH??"");return Z.PATH=z,{status:"applied",pathEntries:z.split(m).length,shell:N}}return{status:"failed",shell:$}}var u0={readHubDiscovery:O,clearHubDiscoveryIfOwned:L0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:b2,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:v0,setHomeDirIfUnset:h2,homeDir:y2,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function p0(J,Q){let Z=J.indexOf(Q);return(Z>=0?J[Z+1]:void 0)?.trim()||void 0}function l0(J,Q){let Z=p0(J,"--discovery-path");if(!Z)throw Error("--discovery-path is required for remote Hub management");return Q.env.CLINE_HUB_DISCOVERY_PATH=Z,Z}async function m2(J=process.argv,Q=u0){Q.setHomeDirIfUnset(Q.homeDir()),await Q.ensureLoginShellPath();let Z=p0(J,"--cwd")??Q.cwd();l0(J,Q);let $=await Q.ensureDetachedHubServer(Z,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});Q.writeOutput(`${JSON.stringify({...$,cwd:Z,platform:process.platform,arch:process.arch})}
|
|
3
|
+
`,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?G1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function G1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as q1,CLINE_HUB_PORT as F1,resolveClineBuildEnv as L1}from"@cline/shared";var B1="CLINE_HUB_HOST",O1="CLINE_HUB_PORT",A1="CLINE_HUB_PATHNAME",U1="127.0.0.1",M1=F1,f1="/hub";function M0(J){return L1(J)==="development"?q1:M1}function C1(J={}){return(J.env??process.env)[B1]?.trim()||U1}function x1(J={}){let Z=(J.env??process.env)[O1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function _1(J={}){return(J.env??process.env)[A1]?.trim()||f1}function f0(J={},Q={}){return{host:J.host??C1(Q),port:J.port??x1(Q),pathname:J.pathname??_1(Q)}}import{join as D1}from"node:path";import{processWorkspaceInfo as Q4}from"@cline/shared";import $4 from"simple-git";var R1="shared:cline",S1="CLINE_HUB_DISCOVERY_PATH",E1="hub-production";function D(J=R1){return q0(`${J}@${C()}`)}function H(){return{ownerId:E1,discoveryPath:process.env[S1]?.trim()||D1(_(),"locks","hub","production.json")}}var p1=8000,l1=200,C0=3000,c1=100,i1=[100,250,500,1000,2000],n1="--cline-hub-daemon",s1=3,t1=60000,x0=new Map;function d1(J,Q=Date.now()){let Z=x0.get(J);if(!Z||Q-Z.windowStartedAt>t1)return x0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=s1}function a1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function o1(){try{let J=b1(_(),"logs","hub-daemon.log");return I1(y1(J),{recursive:!0}),{fd:P1(J,"a"),logPath:J}}catch{return}}function r1(){return R0()==="production"?H():D()}function R(J){return P(J)}function e1(J){try{let Q=JSON.parse(w1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{H1(`${J}.superseded`)}catch{}}function _0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function S(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function D0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await S(J))?.url)return!0;await new Promise((X)=>setTimeout(X,c1))}return!1}async function s(J,Q){if(!d1(J.url))return!1;await E(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await D0(J.url,C0);if(!Z&&J.pid&&J2(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await D0(J.url,C0)}if(Z)await x(Q).catch(()=>{return});return Z}function J2(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function Q2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await E(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await Q2(J)){if(Z)await E(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await E(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Z2(J){if(R0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await x(Q.discoveryPath).catch(()=>{return})}function $2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return h1(new URL(`./entry.${J}`,import.meta.url))}function X2(J,Q){let Z=$2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=k1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[n1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...a1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...u1(process.env),CLINE_NO_INTERACTIVE:"1",[m1]:"1"}}}function j2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function z2(J,Q={}){if(v1())return;let Z=X2(J,Q),$=o1();try{g1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)T1($.fd)}}async function V2(J,Q={}){for(let Z=0;;Z++)try{z2(J,Q);return}catch($){let X=i1[Z];if(!j2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function Y2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Z2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:e1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await S(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await x(J.discoveryPath).catch(()=>{return})}}let z=await S(j);if(z?.url){let W=_0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let i0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,i0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await V2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+p1;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await S(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await S(j);if(G?.url&&!R(G)){let L=_0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,l1))}throw Error("Timed out waiting for detached hub startup.")}async function k(J,Q={}){let Z=r1();return await O0(Z.discoveryPath,async()=>Y2(Z,J,Q))}function F2(){return W2()==="production"?H():D()}function L2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function P0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return P0(J.data);return String(J)}function B2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function S0(J){let Q=J,Z=B2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function E0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,O2="cline-hub-auth.",w0=new Map,H0=new Set,A2=3000;var a="Hub connection closed",U2=250,M2=5000,g0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function f2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?w0.get($):void 0}function C2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!C2(J))return;let Q=new URL(k0(J));return Q.search="",Q.hash="",Q.toString()}function T0(J){let Q=J0(J);return!!Q&&H0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(H0.add(Z),Q?.trim())w0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=E0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new q2(J.toString(),{headers:{...X}}):new(L2())(J.toString(),Q?[`${O2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=E0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:S0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(P0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=S0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();$?.beforeDispatch?.();let j=N2("hubreq_"),V=G2(J,$?.timeoutMs),N=new Promise((K,z)=>{let F=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;z(new o(J,"hub_command_timeout",`Hub command ${J} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(B)=>{if(F)clearTimeout(F);K(B)},reject:(B)=>{if(F)clearTimeout(F);z(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:Q}})}catch(K){throw this.pendingReplies.delete(j),K}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let K=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new v(K,Y.error.message)}throw new o(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!T0(this.currentUrl)||!f2(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let J=Math.min(U2*2**this.reconnectAttempt,M2),Q=Math.round(J*(1-g0)+Math.random()*J*g0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!T0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",a);for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Q){let Z=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Q)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Q?{sessionId:Q}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(J,Q){let Z=this.subscriptionKeyForSessionId(J),$=(this.subscriptionCounts.get(Z)??0)+Q;if($<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Z,$),Q>0&&$===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??d}subscriptionSessionIdFromKey(J){return J===d?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Q=J.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve(J.envelope);return}case"event":{let Q=J.envelope.sequence;if(typeof Q==="number"){let Z=J.envelope.sessionId?.trim();for(let $ of[d,Z]){if(!$||!this.subscriptionCounts.has($))continue;let X=this.lastEventSequenceByKey.get($)??0;if(Q>X)this.lastEventSequenceByKey.set($,Q)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==J.envelope.sessionId?.trim())continue;Z.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function k0(J){let Q=new URL(J);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function A(J,Q){let Z=new Q0({url:J,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function r(J,Q){let Z=k0(J),$=await w(Z,{authToken:Q?.authToken});if(!$)return{status:"unreachable",url:Z};if(Q?.requireCurrentBuild){let X=C(),j=I($,X);if(!j.compatible&&!P($))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!K2($).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await A(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function x2(J){let Q=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Z=0,$=new Set;for(let X of Q){if(!X||typeof X!=="object")continue;let j=X.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let N=V&&typeof V==="object"?V.clientId:void 0;if(typeof N==="string"&&N.trim())$.add(N)}}return{activeSessionCount:Z,participantClientCount:$.size}}async function t(J,Q,Z){let $=new Q0({url:J,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let X=await $.command("session.list",{limit:500},void 0,{timeoutMs:A2});return x2(X.payload)}finally{await $.dispose().catch(()=>{return})}}async function _2(J,Q,Z){try{return(await t(J,Q,Z)).activeSessionCount===0}catch{return!1}}async function D2(J,Q){let Z=`${J.discoveryPath}.superseded`,$=await O(Z);if(!$?.url||!$.authToken)return;let X=await r($.url,{authToken:$.authToken});if(X.status!=="compatible")return;if(await _2(X.url,$.authToken,Q))return;return y(X.url,$.authToken)}async function R2(J={}){if(J.endpoint?.trim()){let X=await r(J.endpoint);return X.status==="compatible"?X.url:void 0}let Q=F2(),Z=await O(Q.discoveryPath);if(!Z?.url)return await D2(Q,J);let $=await r(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if($.status==="compatible")return y($.url,Z.authToken);if($.status==="protocol_mismatch")await x(Q.discoveryPath).catch(()=>{return});return}async function I0(J={}){let Q=await R2(J);if(Q&&await A(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Q;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch{return}}async function E(J,Q,Z,$){let X=new URL(J),j=Q?.trim()||e(X);if(X.protocol==="ws:")X.protocol="http:";else if(X.protocol==="wss:")X.protocol="https:";if(X.pathname="/drain",X.hash="",Z)X.searchParams.set("reason",Z);if($?.off)X.searchParams.set("off","1");return(await fetch(X,{method:"POST",headers:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b(J,Q){let Z=new URL(J),$=Q?.trim()||e(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:$?{authorization:`Bearer ${$}`}:void 0})).ok}import{spawn as S2}from"node:child_process";import{userInfo as E2}from"node:os";import{basename as g2,delimiter as m}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",b0="__CLINE_SIDECAR_PATH_END__",h0=5000,T2=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${b0}"'`,y0="CLINE_SIDECAR_SKIP_SHELL_PATH";function m0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function I2(J,Q){try{let Z=E2().shell?.trim();if(Z)return Z}catch{}return Q.SHELL?.trim()||m0(J)}function P2(J,Q){let Z=g2(J);if(Z==="csh"||Z==="tcsh")return{args:["-c",Q],argv0:`-${Z}`};return{args:["-i","-l","-c",Q]}}function w2(J){let Q=J.indexOf(Z0);if(Q===-1)return;let Z=J.indexOf(b0,Q);if(Z===-1)return;let $=J.slice(Q+Z0.length,Z).trim();return $.length>0?$:void 0}function H2(J,Q){let Z=[...J.split(m),...Q.split(m)].map(($)=>$.trim()).filter(($)=>$.length>0);return Array.from(new Set(Z)).join(m)}function k2(J,Q=h0){return new Promise((Z)=>{let $=P2(J,T2),X=S2(J,$.args,{argv0:$.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),j="",V=0,N=()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}},Y=!1,K=(F)=>{if(Y)return;Y=!0,clearTimeout(z),X.stdout?.destroy(),N(),Z(F)},z=setTimeout(()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}K(void 0)},Q);X.stdout?.on("data",(F)=>{if(Y)return;if(V+=F.length,V>65536){K(void 0);return}j+=F.toString("utf8")}),X.on("error",()=>K(void 0)),X.on("close",()=>K(w2(j)))})}async function v0(J){let Q=J?.platform??process.platform,Z=J?.env??process.env;if(Q==="win32")return{status:"skipped",reason:"windows"};if(Z[y0]?.trim())return{status:"skipped",reason:y0};let $=J?.userShell??I2(Q,Z),X=J?.fallbackShell??m0(Q),j=J?.timeoutMs??h0,V=$===X?[[$,j]]:[[$,j],[X,j/2]];for(let[N,Y]of V){let K=await k2(N,Y);if(!K)continue;let z=H2(K,Z.PATH??"");return Z.PATH=z,{status:"applied",pathEntries:z.split(m).length,shell:N}}return{status:"failed",shell:$}}var u0={readHubDiscovery:O,clearHubDiscoveryIfOwned:L0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:b2,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:v0,setHomeDirIfUnset:h2,homeDir:y2,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function p0(J,Q){let Z=J.indexOf(Q);return(Z>=0?J[Z+1]:void 0)?.trim()||void 0}function l0(J,Q){let Z=p0(J,"--discovery-path");if(!Z)throw Error("--discovery-path is required for remote Hub management");return Q.env.CLINE_HUB_DISCOVERY_PATH=Z,Z}async function m2(J=process.argv,Q=u0){Q.setHomeDirIfUnset(Q.homeDir()),await Q.ensureLoginShellPath();let Z=p0(J,"--cwd")??Q.cwd();l0(J,Q);let $=await Q.ensureDetachedHubServer(Z,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});Q.writeOutput(`${JSON.stringify({...$,cwd:Z,platform:process.platform,arch:process.arch})}
|
|
4
4
|
`)}async function c0(J=process.argv,Q=u0){if(J.includes("--remote-hub-stop")){let Z=l0(J,Q),$=await Q.readHubDiscovery(Z);if($&&typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)try{Q.probeProcess($.pid)}catch(X){if(X?.code==="ESRCH")return await Q.clearHubDiscoveryIfOwned(Z,$.hubId),!0}if($&&!await Q.requestHubShutdown($.url,$.authToken))throw Error("Remote Hub shutdown failed");return!0}if(J.includes("--remote-hub-ensure"))return await m2(J,Q),!0;if(Q.claimHubDaemonProcess())return await Q.loadHubDaemon(),!0;return!1}(async()=>{if(!await c0())throw Error("A remote helper command is required")})().catch((J)=>{process.stderr.write(`${J instanceof Error?J.message:String(J)}
|
|
5
5
|
`),process.exitCode=1});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as i0}from"node:module";var n0=i0(import.meta.url);import{homedir as k2}from"node:os";import{claimHubDaemonProcess as y2}from"@cline/shared";import{setHomeDirIfUnset as b2}from"@cline/shared/storage";import{createSessionId as Y2,isHubProtocolCompatible as N2,resolveClineBuildEnv as K2,resolveHubCommandTimeoutMs as W2}from"@cline/shared";import G2 from"ws";var $0="session_not_found";class v extends Error{sessionId;code="session_not_found";constructor(J,Q){super(Q??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as S1}from"node:child_process";import{closeSync as g1,mkdirSync as T1,openSync as I1,readFileSync as P1,unlinkSync as w1}from"node:fs";import{basename as H1,dirname as k1,join as y1}from"node:path";import{fileURLToPath as b1}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as h1,isHubDaemonProcess as m1,resolveClineBuildEnv as R0,withResolvedClineBuildEnv as v1}from"@cline/shared";import{createHash as t0,randomBytes as d0}from"node:crypto";import{mkdir as p,open as X0,readFile as N0,rename as a0,rm as T,writeFile as o0}from"node:fs/promises";import{dirname as K0,join as l}from"node:path";import{isHubProtocolCompatible as r0}from"@cline/shared";import{resolveClineDataDir as _,resolveClineDir as t2}from"@cline/shared/storage";var g={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.
|
|
1
|
+
import{createRequire as i0}from"node:module";var n0=i0(import.meta.url);import{homedir as k2}from"node:os";import{claimHubDaemonProcess as y2}from"@cline/shared";import{setHomeDirIfUnset as b2}from"@cline/shared/storage";import{createSessionId as Y2,isHubProtocolCompatible as N2,resolveClineBuildEnv as K2,resolveHubCommandTimeoutMs as W2}from"@cline/shared";import G2 from"ws";var $0="session_not_found";class v extends Error{sessionId;code="session_not_found";constructor(J,Q){super(Q??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}import{spawn as S1}from"node:child_process";import{closeSync as g1,mkdirSync as T1,openSync as I1,readFileSync as P1,unlinkSync as w1}from"node:fs";import{basename as H1,dirname as k1,join as y1}from"node:path";import{fileURLToPath as b1}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as h1,isHubDaemonProcess as m1,resolveClineBuildEnv as R0,withResolvedClineBuildEnv as v1}from"@cline/shared";import{createHash as t0,randomBytes as d0}from"node:crypto";import{mkdir as p,open as X0,readFile as N0,rename as a0,rm as T,writeFile as o0}from"node:fs/promises";import{dirname as K0,join as l}from"node:path";import{isHubProtocolCompatible as r0}from"@cline/shared";import{resolveClineDataDir as _,resolveClineDir as t2}from"@cline/shared/storage";var g={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.84",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var e0="CLINE_HUB_DISCOVERY_PATH",J1="CLINE_HUB_BUILD_ID",Q1="CLINE_HUB_BUILD_EPOCH_MS",Z1=30000,$1=15000,j0=100;function X1(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function j1(J){return t0("sha256").update(J).digest("hex").slice(0,12)}function z1(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function z0(J){return new Promise((Q)=>setTimeout(Q,J))}function V1(J){return`${J}.lock`}async function Y1(J){try{let Q=JSON.parse(await N0(l(J,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function u(J){await T(J,{recursive:!0,force:!0}).catch(()=>{return})}function C(){let J=process.env[J1]?.trim();if(J)return J;return"sdk-v1-0c7290d109800148a2ee6c68832123073f3e04b020ebdfd6a55983a47b314e02".trim()||`source-${String(g.version)}`}function N1(){let J=Number(process.env[Q1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1790047513229)?1790047513229:void 0}function I(J,Q=C()){let Z=r0(J);if(!Z.compatible)return Z;let $=J.buildId?.trim();if(!$)return{compatible:!1,reason:"missing_build"};if($!==Q)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function V0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function Y0(J){let Q=J?.trim().split(/[-+]/,1)[0];if(!Q)return;let Z=Q.split(".").map(($)=>Number($));if(Z.length===0||Z.some(($)=>!Number.isInteger($)||$<0))return;return Z}function K1(J,Q){for(let Z=0;Z<Math.max(J.length,Q.length);Z++){let $=J[Z]??0,X=Q[Z]??0;if($!==X)return $<X?-1:1}return 0}function W0(J,Q){let Z=J.buildId?.trim(),$=Q.buildId?.trim();if(Z&&$&&Z===$)return 0;let X=V0(J.buildEpochMs),j=V0(Q.buildEpochMs);if(X!==void 0&&j!==void 0&&X!==j)return X<j?-1:1;let V=Y0(J.coreVersion),N=Y0(Q.coreVersion);if(V&&N){let Y=K1(V,N);if(Y!==0)return Y}if(Z&&$&&Z!==$)return Z<$?-1:1;return 0}function G0(){return{buildId:C(),buildEpochMs:N1(),coreVersion:String(g.version)}}function P(J,Q){let Z=Q?.self??G0(),$=I(J,Z.buildId??"");if($.compatible)return!0;if($.reason!=="build_mismatch"&&$.reason!=="missing_build")return!1;return W0(Z,J)<=0}function q0(J=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${j1(J)}`,Z=process.env[e0]?.trim()||l(_(),"locks","hub","owners",`${X1(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}async function O(J){try{let Q=JSON.parse(await N0(J,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function F0(J,Q){await c(J,async()=>{let Z=K0(J);await p(Z,{recursive:!0});let $=`${J}.${process.pid}.${d0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(Q,null,2)}
|
|
2
2
|
`,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,await a0($,J);let j;try{j=await X0(Z,"r"),await j.sync()}catch{}finally{await j?.close().catch(()=>{return})}}catch(j){throw await X?.close().catch(()=>{return}),await T($,{force:!0}).catch(()=>{return}),j}})}async function x(J){await c(J,async()=>{await T(J,{force:!0}).catch(()=>{return})})}async function L0(J,Q){return await c(J,async()=>{if((await O(J))?.hubId!==Q)return!1;return await T(J,{force:!0}),!0})}async function B0(J,Q,Z){let $=V1(J);await p(K0($),{recursive:!0});let X=Date.now()+$1;while(!0){try{await p($,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let N=await Y1($);if(!N){if(Date.now()>=X){await u($);continue}await z0(j0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!z1(N.pid)||Y>Z1){await u($);continue}if(Date.now()>=X)throw Error(`Timed out waiting for hub ${Q} lock ${$}`);await z0(j0);continue}try{return await o0(l($,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
3
|
-
`,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?W1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function W1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as G1,CLINE_HUB_PORT as q1,resolveClineBuildEnv as F1}from"@cline/shared";var L1="CLINE_HUB_HOST",B1="CLINE_HUB_PORT",O1="CLINE_HUB_PATHNAME",A1="127.0.0.1",U1=q1,M1="/hub";function M0(J){return F1(J)==="development"?G1:U1}function f1(J={}){return(J.env??process.env)[L1]?.trim()||A1}function C1(J={}){let Z=(J.env??process.env)[B1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function x1(J={}){return(J.env??process.env)[O1]?.trim()||M1}function f0(J={},Q={}){return{host:J.host??f1(Q),port:J.port??C1(Q),pathname:J.pathname??x1(Q)}}import{join as _1}from"node:path";import{processWorkspaceInfo as J4}from"@cline/shared";import Z4 from"simple-git";var D1="shared:cline",R1="CLINE_HUB_DISCOVERY_PATH",E1="hub-production";function D(J=D1){return q0(`${J}@${C()}`)}function H(){return{ownerId:E1,discoveryPath:process.env[R1]?.trim()||_1(_(),"locks","hub","production.json")}}var u1=8000,p1=200,C0=3000,l1=100,c1=[100,250,500,1000,2000],i1="--cline-hub-daemon",n1=3,s1=60000,x0=new Map;function t1(J,Q=Date.now()){let Z=x0.get(J);if(!Z||Q-Z.windowStartedAt>s1)return x0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=n1}function d1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function a1(){try{let J=y1(_(),"logs","hub-daemon.log");return T1(k1(J),{recursive:!0}),{fd:I1(J,"a"),logPath:J}}catch{return}}function o1(){return R0()==="production"?H():D()}function R(J){return P(J)}function r1(J){try{let Q=JSON.parse(P1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{w1(`${J}.superseded`)}catch{}}function _0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function E(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function D0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await E(J))?.url)return!0;await new Promise((X)=>setTimeout(X,l1))}return!1}async function s(J,Q){if(!t1(J.url))return!1;await S(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await D0(J.url,C0);if(!Z&&J.pid&&e1(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await D0(J.url,C0)}if(Z)await x(Q).catch(()=>{return});return Z}function e1(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function J2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await S(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await J2(J)){if(Z)await S(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await S(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Q2(J){if(R0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await x(Q.discoveryPath).catch(()=>{return})}function Z2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return b1(new URL(`./entry.${J}`,import.meta.url))}function $2(J,Q){let Z=Z2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=H1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[i1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...d1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...v1(process.env),CLINE_NO_INTERACTIVE:"1",[h1]:"1"}}}function X2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function j2(J,Q={}){if(m1())return;let Z=$2(J,Q),$=a1();try{S1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)g1($.fd)}}async function z2(J,Q={}){for(let Z=0;;Z++)try{j2(J,Q);return}catch($){let X=c1[Z];if(!X2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function V2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Q2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:r1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await E(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await x(J.discoveryPath).catch(()=>{return})}}let z=await E(j);if(z?.url){let W=_0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let c0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,c0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await z2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+u1;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await E(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await E(j);if(G?.url&&!R(G)){let L=_0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,p1))}throw Error("Timed out waiting for detached hub startup.")}async function k(J,Q={}){let Z=o1();return await O0(Z.discoveryPath,async()=>V2(Z,J,Q))}function q2(){return K2()==="production"?H():D()}function F2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function P0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return P0(J.data);return String(J)}function L2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function E0(J){let Q=J,Z=L2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function S0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,B2="cline-hub-auth.",w0=new Map,H0=new Set,O2=3000;var a="Hub connection closed",A2=250,U2=5000,g0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function M2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?w0.get($):void 0}function f2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!f2(J))return;let Q=new URL(k0(J));return Q.search="",Q.hash="",Q.toString()}function T0(J){let Q=J0(J);return!!Q&&H0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(H0.add(Z),Q?.trim())w0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=S0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new G2(J.toString(),{headers:{...X}}):new(F2())(J.toString(),Q?[`${B2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=S0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:E0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(P0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=E0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();let j=Y2("hubreq_"),V=W2(J,$?.timeoutMs),N=new Promise((K,z)=>{let F=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;z(new o(J,"hub_command_timeout",`Hub command ${J} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(B)=>{if(F)clearTimeout(F);K(B)},reject:(B)=>{if(F)clearTimeout(F);z(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:Q}})}catch(K){throw this.pendingReplies.delete(j),K}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let K=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new v(K,Y.error.message)}throw new o(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!T0(this.currentUrl)||!M2(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let J=Math.min(A2*2**this.reconnectAttempt,U2),Q=Math.round(J*(1-g0)+Math.random()*J*g0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!T0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",a);for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Q){let Z=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Q)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Q?{sessionId:Q}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(J,Q){let Z=this.subscriptionKeyForSessionId(J),$=(this.subscriptionCounts.get(Z)??0)+Q;if($<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Z,$),Q>0&&$===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??d}subscriptionSessionIdFromKey(J){return J===d?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Q=J.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve(J.envelope);return}case"event":{let Q=J.envelope.sequence;if(typeof Q==="number"){let Z=J.envelope.sessionId?.trim();for(let $ of[d,Z]){if(!$||!this.subscriptionCounts.has($))continue;let X=this.lastEventSequenceByKey.get($)??0;if(Q>X)this.lastEventSequenceByKey.set($,Q)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==J.envelope.sessionId?.trim())continue;Z.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function k0(J){let Q=new URL(J);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function A(J,Q){let Z=new Q0({url:J,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function r(J,Q){let Z=k0(J),$=await w(Z,{authToken:Q?.authToken});if(!$)return{status:"unreachable",url:Z};if(Q?.requireCurrentBuild){let X=C(),j=I($,X);if(!j.compatible&&!P($))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!N2($).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await A(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function C2(J){let Q=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Z=0,$=new Set;for(let X of Q){if(!X||typeof X!=="object")continue;let j=X.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let N=V&&typeof V==="object"?V.clientId:void 0;if(typeof N==="string"&&N.trim())$.add(N)}}return{activeSessionCount:Z,participantClientCount:$.size}}async function t(J,Q,Z){let $=new Q0({url:J,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let X=await $.command("session.list",{limit:500},void 0,{timeoutMs:O2});return C2(X.payload)}finally{await $.dispose().catch(()=>{return})}}async function x2(J,Q,Z){try{return(await t(J,Q,Z)).activeSessionCount===0}catch{return!1}}async function _2(J,Q){let Z=`${J.discoveryPath}.superseded`,$=await O(Z);if(!$?.url||!$.authToken)return;let X=await r($.url,{authToken:$.authToken});if(X.status!=="compatible")return;if(await x2(X.url,$.authToken,Q))return;return y(X.url,$.authToken)}async function D2(J={}){if(J.endpoint?.trim()){let X=await r(J.endpoint);return X.status==="compatible"?X.url:void 0}let Q=q2(),Z=await O(Q.discoveryPath);if(!Z?.url)return await _2(Q,J);let $=await r(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if($.status==="compatible")return y($.url,Z.authToken);if($.status==="protocol_mismatch")await x(Q.discoveryPath).catch(()=>{return});return}async function I0(J={}){let Q=await D2(J);if(Q&&await A(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Q;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch{return}}async function S(J,Q,Z,$){let X=new URL(J),j=Q?.trim()||e(X);if(X.protocol==="ws:")X.protocol="http:";else if(X.protocol==="wss:")X.protocol="https:";if(X.pathname="/drain",X.hash="",Z)X.searchParams.set("reason",Z);if($?.off)X.searchParams.set("off","1");return(await fetch(X,{method:"POST",headers:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b(J,Q){let Z=new URL(J),$=Q?.trim()||e(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:$?{authorization:`Bearer ${$}`}:void 0})).ok}import{spawn as R2}from"node:child_process";import{userInfo as E2}from"node:os";import{basename as S2,delimiter as m}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",b0="__CLINE_SIDECAR_PATH_END__",h0=2000,g2=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${b0}"'`,y0="CLINE_SIDECAR_SKIP_SHELL_PATH";function m0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function T2(J,Q){try{let Z=E2().shell?.trim();if(Z)return Z}catch{}return Q.SHELL?.trim()||m0(J)}function I2(J,Q){let Z=S2(J);if(Z==="csh"||Z==="tcsh")return{args:["-c",Q],argv0:`-${Z}`};return{args:["-i","-l","-c",Q]}}function P2(J){let Q=J.indexOf(Z0);if(Q===-1)return;let Z=J.indexOf(b0,Q);if(Z===-1)return;let $=J.slice(Q+Z0.length,Z).trim();return $.length>0?$:void 0}function w2(J,Q){let Z=[...J.split(m),...Q.split(m)].map(($)=>$.trim()).filter(($)=>$.length>0);return Array.from(new Set(Z)).join(m)}function H2(J,Q=h0){return new Promise((Z)=>{let $=I2(J,g2),X=R2(J,$.args,{argv0:$.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),j="",V=0,N=()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}},Y=!1,K=(F)=>{if(Y)return;Y=!0,clearTimeout(z),X.stdout?.destroy(),N(),Z(F)},z=setTimeout(()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}K(void 0)},Q);X.stdout?.on("data",(F)=>{if(Y)return;if(V+=F.length,V>65536){K(void 0);return}j+=F.toString("utf8")}),X.on("error",()=>K(void 0)),X.on("close",()=>K(P2(j)))})}async function v0(J){let Q=J?.platform??process.platform,Z=J?.env??process.env;if(Q==="win32")return{status:"skipped",reason:"windows"};if(Z[y0]?.trim())return{status:"skipped",reason:y0};let $=J?.userShell??T2(Q,Z),X=J?.fallbackShell??m0(Q),j=J?.timeoutMs??h0,V=$===X?[[$,j]]:[[$,j],[X,j/2]];for(let[N,Y]of V){let K=await H2(N,Y);if(!K)continue;let z=w2(K,Z.PATH??"");return Z.PATH=z,{status:"applied",pathEntries:z.split(m).length,shell:N}}return{status:"failed",shell:$}}var u0={readHubDiscovery:O,clearHubDiscoveryIfOwned:L0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:y2,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:v0,setHomeDirIfUnset:b2,homeDir:k2,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function p0(J,Q){let Z=J.indexOf(Q);return(Z>=0?J[Z+1]:void 0)?.trim()||void 0}function l0(J,Q){let Z=p0(J,"--discovery-path");if(!Z)throw Error("--discovery-path is required for remote Hub management");return Q.env.CLINE_HUB_DISCOVERY_PATH=Z,Z}async function h2(J=process.argv,Q=u0){Q.setHomeDirIfUnset(Q.homeDir()),await Q.ensureLoginShellPath();let Z=p0(J,"--cwd")??Q.cwd();l0(J,Q);let $=await Q.ensureDetachedHubServer(Z,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});Q.writeOutput(`${JSON.stringify({...$,cwd:Z,platform:process.platform,arch:process.arch})}
|
|
3
|
+
`,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?W1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function W1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as G1,CLINE_HUB_PORT as q1,resolveClineBuildEnv as F1}from"@cline/shared";var L1="CLINE_HUB_HOST",B1="CLINE_HUB_PORT",O1="CLINE_HUB_PATHNAME",A1="127.0.0.1",U1=q1,M1="/hub";function M0(J){return F1(J)==="development"?G1:U1}function f1(J={}){return(J.env??process.env)[L1]?.trim()||A1}function C1(J={}){let Z=(J.env??process.env)[B1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function x1(J={}){return(J.env??process.env)[O1]?.trim()||M1}function f0(J={},Q={}){return{host:J.host??f1(Q),port:J.port??C1(Q),pathname:J.pathname??x1(Q)}}import{join as _1}from"node:path";import{processWorkspaceInfo as J4}from"@cline/shared";import Z4 from"simple-git";var D1="shared:cline",R1="CLINE_HUB_DISCOVERY_PATH",E1="hub-production";function D(J=D1){return q0(`${J}@${C()}`)}function H(){return{ownerId:E1,discoveryPath:process.env[R1]?.trim()||_1(_(),"locks","hub","production.json")}}var u1=8000,p1=200,C0=3000,l1=100,c1=[100,250,500,1000,2000],i1="--cline-hub-daemon",n1=3,s1=60000,x0=new Map;function t1(J,Q=Date.now()){let Z=x0.get(J);if(!Z||Q-Z.windowStartedAt>s1)return x0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=n1}function d1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function a1(){try{let J=y1(_(),"logs","hub-daemon.log");return T1(k1(J),{recursive:!0}),{fd:I1(J,"a"),logPath:J}}catch{return}}function o1(){return R0()==="production"?H():D()}function R(J){return P(J)}function r1(J){try{let Q=JSON.parse(P1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{w1(`${J}.superseded`)}catch{}}function _0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function E(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function D0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await E(J))?.url)return!0;await new Promise((X)=>setTimeout(X,l1))}return!1}async function s(J,Q){if(!t1(J.url))return!1;await S(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await D0(J.url,C0);if(!Z&&J.pid&&e1(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await D0(J.url,C0)}if(Z)await x(Q).catch(()=>{return});return Z}function e1(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function J2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await S(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await J2(J)){if(Z)await S(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await S(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Q2(J){if(R0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await x(Q.discoveryPath).catch(()=>{return})}function Z2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return b1(new URL(`./entry.${J}`,import.meta.url))}function $2(J,Q){let Z=Z2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=H1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[i1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...d1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...v1(process.env),CLINE_NO_INTERACTIVE:"1",[h1]:"1"}}}function X2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function j2(J,Q={}){if(m1())return;let Z=$2(J,Q),$=a1();try{S1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)g1($.fd)}}async function z2(J,Q={}){for(let Z=0;;Z++)try{j2(J,Q);return}catch($){let X=c1[Z];if(!X2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function V2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Q2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:r1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await E(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await x(J.discoveryPath).catch(()=>{return})}}let z=await E(j);if(z?.url){let W=_0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let c0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,c0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await z2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+u1;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await E(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await E(j);if(G?.url&&!R(G)){let L=_0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,p1))}throw Error("Timed out waiting for detached hub startup.")}async function k(J,Q={}){let Z=o1();return await O0(Z.discoveryPath,async()=>V2(Z,J,Q))}function q2(){return K2()==="production"?H():D()}function F2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function P0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return P0(J.data);return String(J)}function L2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function E0(J){let Q=J,Z=L2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function S0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,B2="cline-hub-auth.",w0=new Map,H0=new Set,O2=3000;var a="Hub connection closed",A2=250,U2=5000,g0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function M2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?w0.get($):void 0}function f2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!f2(J))return;let Q=new URL(k0(J));return Q.search="",Q.hash="",Q.toString()}function T0(J){let Q=J0(J);return!!Q&&H0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(H0.add(Z),Q?.trim())w0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=S0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new G2(J.toString(),{headers:{...X}}):new(F2())(J.toString(),Q?[`${B2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=S0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:E0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(P0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=E0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();$?.beforeDispatch?.();let j=Y2("hubreq_"),V=W2(J,$?.timeoutMs),N=new Promise((K,z)=>{let F=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;z(new o(J,"hub_command_timeout",`Hub command ${J} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(B)=>{if(F)clearTimeout(F);K(B)},reject:(B)=>{if(F)clearTimeout(F);z(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:Q}})}catch(K){throw this.pendingReplies.delete(j),K}let Y=await N;if(!Y.ok){if(Y.error?.code===$0){let K=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new v(K,Y.error.message)}throw new o(J,Y.error?.code,Y.error?.message??`Hub command ${J} failed`)}return Y}async recoverLocalHubTransport(J){if(!T0(this.currentUrl)||!M2(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let J=Math.min(A2*2**this.reconnectAttempt,U2),Q=Math.round(J*(1-g0)+Math.random()*J*g0);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!T0(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await I0({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(J){this.currentUrl=J,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let J=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,J)this.lastCloseError=new q("hub_connection_closed",a);for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!J)return;this.sawSocketClose=!1,this.socket=void 0;try{J.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(J){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Q){let Z=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Q)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Q?{sessionId:Q}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount(J,Q){let Z=this.subscriptionKeyForSessionId(J),$=(this.subscriptionCounts.get(Z)??0)+Q;if($<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set(Z,$),Q>0&&$===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??d}subscriptionSessionIdFromKey(J){return J===d?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Q=J.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve(J.envelope);return}case"event":{let Q=J.envelope.sequence;if(typeof Q==="number"){let Z=J.envelope.sessionId?.trim();for(let $ of[d,Z]){if(!$||!this.subscriptionCounts.has($))continue;let X=this.lastEventSequenceByKey.get($)??0;if(Q>X)this.lastEventSequenceByKey.set($,Q)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==J.envelope.sessionId?.trim())continue;Z.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function k0(J){let Q=new URL(J);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function A(J,Q){let Z=new Q0({url:J,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function r(J,Q){let Z=k0(J),$=await w(Z,{authToken:Q?.authToken});if(!$)return{status:"unreachable",url:Z};if(Q?.requireCurrentBuild){let X=C(),j=I($,X);if(!j.compatible&&!P($))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!N2($).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await A(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function C2(J){let Q=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],Z=0,$=new Set;for(let X of Q){if(!X||typeof X!=="object")continue;let j=X.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let N=V&&typeof V==="object"?V.clientId:void 0;if(typeof N==="string"&&N.trim())$.add(N)}}return{activeSessionCount:Z,participantClientCount:$.size}}async function t(J,Q,Z){let $=new Q0({url:J,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let X=await $.command("session.list",{limit:500},void 0,{timeoutMs:O2});return C2(X.payload)}finally{await $.dispose().catch(()=>{return})}}async function x2(J,Q,Z){try{return(await t(J,Q,Z)).activeSessionCount===0}catch{return!1}}async function _2(J,Q){let Z=`${J.discoveryPath}.superseded`,$=await O(Z);if(!$?.url||!$.authToken)return;let X=await r($.url,{authToken:$.authToken});if(X.status!=="compatible")return;if(await x2(X.url,$.authToken,Q))return;return y(X.url,$.authToken)}async function D2(J={}){if(J.endpoint?.trim()){let X=await r(J.endpoint);return X.status==="compatible"?X.url:void 0}let Q=q2(),Z=await O(Q.discoveryPath);if(!Z?.url)return await _2(Q,J);let $=await r(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if($.status==="compatible")return y($.url,Z.authToken);if($.status==="protocol_mismatch")await x(Q.discoveryPath).catch(()=>{return});return}async function I0(J={}){let Q=await D2(J);if(Q&&await A(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Q;if(J.endpoint?.trim())return;try{return(await k(J.workspaceRoot??process.cwd())).url}catch{return}}async function S(J,Q,Z,$){let X=new URL(J),j=Q?.trim()||e(X);if(X.protocol==="ws:")X.protocol="http:";else if(X.protocol==="wss:")X.protocol="https:";if(X.pathname="/drain",X.hash="",Z)X.searchParams.set("reason",Z);if($?.off)X.searchParams.set("off","1");return(await fetch(X,{method:"POST",headers:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b(J,Q){let Z=new URL(J),$=Q?.trim()||e(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:$?{authorization:`Bearer ${$}`}:void 0})).ok}import{spawn as R2}from"node:child_process";import{userInfo as E2}from"node:os";import{basename as S2,delimiter as m}from"node:path";var Z0="__CLINE_SIDECAR_PATH_START__",b0="__CLINE_SIDECAR_PATH_END__",h0=5000,g2=`/bin/sh -c 'printf "%s%s%s" "${Z0}" "$PATH" "${b0}"'`,y0="CLINE_SIDECAR_SKIP_SHELL_PATH";function m0(J){return J==="darwin"?"/bin/zsh":"/bin/bash"}function T2(J,Q){try{let Z=E2().shell?.trim();if(Z)return Z}catch{}return Q.SHELL?.trim()||m0(J)}function I2(J,Q){let Z=S2(J);if(Z==="csh"||Z==="tcsh")return{args:["-c",Q],argv0:`-${Z}`};return{args:["-i","-l","-c",Q]}}function P2(J){let Q=J.indexOf(Z0);if(Q===-1)return;let Z=J.indexOf(b0,Q);if(Z===-1)return;let $=J.slice(Q+Z0.length,Z).trim();return $.length>0?$:void 0}function w2(J,Q){let Z=[...J.split(m),...Q.split(m)].map(($)=>$.trim()).filter(($)=>$.length>0);return Array.from(new Set(Z)).join(m)}function H2(J,Q=h0){return new Promise((Z)=>{let $=I2(J,g2),X=R2(J,$.args,{argv0:$.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),j="",V=0,N=()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}},Y=!1,K=(F)=>{if(Y)return;Y=!0,clearTimeout(z),X.stdout?.destroy(),N(),Z(F)},z=setTimeout(()=>{try{if(X.pid)process.kill(-X.pid,"SIGKILL")}catch{X.kill("SIGKILL")}K(void 0)},Q);X.stdout?.on("data",(F)=>{if(Y)return;if(V+=F.length,V>65536){K(void 0);return}j+=F.toString("utf8")}),X.on("error",()=>K(void 0)),X.on("close",()=>K(P2(j)))})}async function v0(J){let Q=J?.platform??process.platform,Z=J?.env??process.env;if(Q==="win32")return{status:"skipped",reason:"windows"};if(Z[y0]?.trim())return{status:"skipped",reason:y0};let $=J?.userShell??T2(Q,Z),X=J?.fallbackShell??m0(Q),j=J?.timeoutMs??h0,V=$===X?[[$,j]]:[[$,j],[X,j/2]];for(let[N,Y]of V){let K=await H2(N,Y);if(!K)continue;let z=w2(K,Z.PATH??"");return Z.PATH=z,{status:"applied",pathEntries:z.split(m).length,shell:N}}return{status:"failed",shell:$}}var u0={readHubDiscovery:O,clearHubDiscoveryIfOwned:L0,probeProcess:(J)=>{process.kill(J,0)},requestHubShutdown:b,ensureDetachedHubServer:k,claimHubDaemonProcess:y2,loadHubDaemon:()=>import("@cline/core/hub/daemon-entry"),ensureLoginShellPath:v0,setHomeDirIfUnset:b2,homeDir:k2,cwd:()=>process.cwd(),env:process.env,writeOutput:(J)=>process.stdout.write(J)};function p0(J,Q){let Z=J.indexOf(Q);return(Z>=0?J[Z+1]:void 0)?.trim()||void 0}function l0(J,Q){let Z=p0(J,"--discovery-path");if(!Z)throw Error("--discovery-path is required for remote Hub management");return Q.env.CLINE_HUB_DISCOVERY_PATH=Z,Z}async function h2(J=process.argv,Q=u0){Q.setHomeDirIfUnset(Q.homeDir()),await Q.ensureLoginShellPath();let Z=p0(J,"--cwd")??Q.cwd();l0(J,Q);let $=await Q.ensureDetachedHubServer(Z,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});Q.writeOutput(`${JSON.stringify({...$,cwd:Z,platform:process.platform,arch:process.arch})}
|
|
4
4
|
`)}async function b4(J=process.argv,Q=u0){if(J.includes("--remote-hub-stop")){let Z=l0(J,Q),$=await Q.readHubDiscovery(Z);if($&&typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)try{Q.probeProcess($.pid)}catch(X){if(X?.code==="ESRCH")return await Q.clearHubDiscoveryIfOwned(Z,$.hubId),!0}if($&&!await Q.requestHubShutdown($.url,$.authToken))throw Error("Remote Hub shutdown failed");return!0}if(J.includes("--remote-hub-ensure"))return await h2(J,Q),!0;if(Q.claimHubDaemonProcess())return await Q.loadHubDaemon(),!0;return!1}export{h2 as runRemoteHubEnsure,b4 as runRemoteHelperEntrypoint};
|
|
@@ -140,6 +140,8 @@ export interface PendingPromptsDeleteInput {
|
|
|
140
140
|
promptId: string;
|
|
141
141
|
}
|
|
142
142
|
export interface PendingPromptsServiceApi {
|
|
143
|
+
/** Select and steer the current queue head atomically in the runtime. */
|
|
144
|
+
steerFirst(input: PendingPromptsListInput): Promise<PendingPromptMutationResult>;
|
|
143
145
|
list(input: PendingPromptsListInput): Promise<SessionPendingPrompt[]>;
|
|
144
146
|
update(input: PendingPromptsUpdateInput): Promise<PendingPromptMutationResult>;
|
|
145
147
|
delete(input: PendingPromptsDeleteInput): Promise<PendingPromptMutationResult>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serialize refresh/read/save across managers and processes sharing credentials.
|
|
3
|
+
* SQLite uses OS file locks, released even when a holder crashes. The lock file
|
|
4
|
+
* contains no credentials and must not be removed while processes are running.
|
|
5
|
+
*/
|
|
6
|
+
export declare function withOAuthRefreshLock<T>(settingsPath: string, storageProviderId: string, run: () => Promise<T>): Promise<T>;
|
|
@@ -166,6 +166,7 @@ export declare class SessionRuntime {
|
|
|
166
166
|
* pre-swap shape.
|
|
167
167
|
*/
|
|
168
168
|
subscribeEvents(listener: SessionEventListener): () => void;
|
|
169
|
+
notifyPendingUserMessage(): void;
|
|
169
170
|
abort(reason?: unknown): void;
|
|
170
171
|
/** Shut the session down after any active run drains. */
|
|
171
172
|
shutdown(_reason?: string, _timeoutMs?: number): Promise<void>;
|
|
@@ -51,6 +51,7 @@ export declare class PendingPromptsController {
|
|
|
51
51
|
private readonly service;
|
|
52
52
|
constructor(deps: PendingPromptsControllerDeps);
|
|
53
53
|
list(sessionId: string): SessionPendingPrompt[];
|
|
54
|
+
steerFirst(sessionId: string): PendingPromptMutationResult;
|
|
54
55
|
update(input: PendingPromptsUpdateInput): PendingPromptMutationResult;
|
|
55
56
|
delete(input: PendingPromptsDeleteInput): PendingPromptMutationResult;
|
|
56
57
|
enqueue(sessionId: string, entry: {
|
|
@@ -25,11 +25,13 @@ export declare class FeatureFlagsService {
|
|
|
25
25
|
private context;
|
|
26
26
|
private cache;
|
|
27
27
|
private cacheInfo;
|
|
28
|
+
private pendingPoll?;
|
|
28
29
|
constructor(options: FeatureFlagsServiceOptions);
|
|
29
30
|
setContext(context: FeatureFlagsContext): void;
|
|
30
31
|
hydrateCache(snapshot: FeatureFlagsCacheSnapshot): void;
|
|
31
32
|
getCacheSnapshot(): FeatureFlagsCacheSnapshot;
|
|
32
33
|
poll(userId?: string | null): Promise<void>;
|
|
34
|
+
private pollFlags;
|
|
33
35
|
private hydrateFromPersistentCache;
|
|
34
36
|
private isFeatureFlagPayload;
|
|
35
37
|
private readPayloadRecord;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { FeatureFlag } from "@cline/shared";
|
|
2
|
+
/** Evaluate a boolean rollout flag for the persisted Cline account in any host.
|
|
3
|
+
* Grants are cached for one minute; only an explicit boolean flag enables access.
|
|
4
|
+
*/
|
|
5
|
+
export declare function isClineAccountFeatureEnabled(flag: FeatureFlag): Promise<boolean>;
|
|
@@ -8,8 +8,8 @@ export type GlobalCompactionStrategy = z.infer<typeof GlobalCompactionStrategySc
|
|
|
8
8
|
/** Compaction strategy plus the "off" state surfaced by the CLI settings UI. */
|
|
9
9
|
export type GlobalCompactionMode = GlobalCompactionStrategy | "off";
|
|
10
10
|
declare const GlobalPlanActModeSchema: z.ZodEnum<{
|
|
11
|
-
plan: "plan";
|
|
12
11
|
act: "act";
|
|
12
|
+
plan: "plan";
|
|
13
13
|
}>;
|
|
14
14
|
export type GlobalPlanActMode = z.infer<typeof GlobalPlanActModeSchema>;
|
|
15
15
|
export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
|
|
@@ -21,8 +21,8 @@ export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
|
|
|
21
21
|
}>>>;
|
|
22
22
|
compactionEnabled: z.ZodCatch<z.ZodOptional<z.ZodBoolean>>;
|
|
23
23
|
planActMode: z.ZodCatch<z.ZodOptional<z.ZodEnum<{
|
|
24
|
-
plan: "plan";
|
|
25
24
|
act: "act";
|
|
25
|
+
plan: "plan";
|
|
26
26
|
}>>>;
|
|
27
27
|
toolAutoApprove: z.ZodCatch<z.ZodOptional<z.ZodBoolean>>;
|
|
28
28
|
tuiTheme: z.ZodCatch<z.ZodOptional<z.ZodString>>;
|
|
@@ -51,7 +51,7 @@ export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
|
|
|
51
51
|
autoUpdateEnabled: boolean;
|
|
52
52
|
compactionStrategy?: "basic" | "agentic" | undefined;
|
|
53
53
|
compactionEnabled?: boolean | undefined;
|
|
54
|
-
planActMode?: "
|
|
54
|
+
planActMode?: "act" | "plan" | undefined;
|
|
55
55
|
toolAutoApprove?: boolean | undefined;
|
|
56
56
|
tuiTheme?: string | undefined;
|
|
57
57
|
disabledTools?: string[] | undefined;
|
|
@@ -46,6 +46,7 @@ export declare function getCachedClineRecommendedModels(options?: FetchClineReco
|
|
|
46
46
|
*/
|
|
47
47
|
export declare function peekClineRecommendedModels(): ClineRecommendedModelsData;
|
|
48
48
|
export declare function resetClineRecommendedModelsCacheForTests(): void;
|
|
49
|
+
export declare function idSlug(modelId: string): string;
|
|
49
50
|
/**
|
|
50
51
|
* Stamps recommended-feed tiers onto a provider's model list so clients can
|
|
51
52
|
* render Recommended/Free/Subscribed sections straight off `ProviderModel`
|
|
@@ -1,3 +1,15 @@
|
|
|
1
1
|
import type { AgentConfig, AgentModel, BasicLogger, ITelemetryService, ModelInfo } from "@cline/shared";
|
|
2
|
+
import type { ProviderConfig } from "./provider-settings";
|
|
2
3
|
export declare function resolveKnownModelsFromConfig(config: AgentConfig): Record<string, ModelInfo> | undefined;
|
|
4
|
+
export type ConnectionConfig = Pick<AgentConfig, "providerId" | "modelId" | "apiKey" | "baseUrl" | "headers" | "providerConfig">;
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the provider connection for a request from the live session config.
|
|
7
|
+
* Top-level fields win over the nested `providerConfig` snapshot, and the
|
|
8
|
+
* snapshot only contributes when it describes the same provider, so a token
|
|
9
|
+
* refresh or connection change written to the top level (see
|
|
10
|
+
* `syncOAuthCredentials` / `updateConnection`) applies to every request built
|
|
11
|
+
* afterwards. Every request builder (main agent, compaction summarizer) must
|
|
12
|
+
* go through this so they never disagree on credentials.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveConnectionProviderConfig(config: ConnectionConfig): ProviderConfig;
|
|
3
15
|
export declare function createAgentModelFromConfig(config: AgentConfig, logger: BasicLogger | undefined, telemetry?: ITelemetryService): AgentModel;
|