@cline/core 0.0.82 → 0.0.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/ClineCore.d.ts +9 -0
  2. package/dist/account/index.d.ts +1 -0
  3. package/dist/account/telemetry.d.ts +22 -0
  4. package/dist/cron/events/cron-event-ingress.d.ts +4 -2
  5. package/dist/cron/runner/cron-runner.d.ts +5 -2
  6. package/dist/cron/service/cron-service.d.ts +2 -1
  7. package/dist/cron/service/schedule-service.d.ts +2 -1
  8. package/dist/cron/store/sqlite-cron-store.d.ts +7 -1
  9. package/dist/extensions/agent-plugin/agent-skill.d.ts +21 -0
  10. package/dist/extensions/agent-plugin/index.d.ts +4 -0
  11. package/dist/extensions/agent-plugin/loader.d.ts +10 -0
  12. package/dist/extensions/agent-plugin/types.d.ts +67 -0
  13. package/dist/extensions/config/index.d.ts +1 -1
  14. package/dist/extensions/config/user-instruction-config-loader.d.ts +9 -0
  15. package/dist/extensions/config/user-instruction-plugin.d.ts +1 -0
  16. package/dist/extensions/config/user-instruction-service.d.ts +7 -1
  17. package/dist/extensions/context/compaction.d.ts +20 -0
  18. package/dist/extensions/index.d.ts +2 -0
  19. package/dist/extensions/mcp/client.d.ts +2 -0
  20. package/dist/extensions/mcp/oauth.d.ts +6 -0
  21. package/dist/extensions/tools/definitions.d.ts +5 -5
  22. package/dist/hooks/checkpoint-hooks.d.ts +23 -1
  23. package/dist/hub/client/index.d.ts +10 -0
  24. package/dist/hub/daemon/entry.js +434 -457
  25. package/dist/hub/daemon/index.d.ts +9 -8
  26. package/dist/hub/index.js +303 -327
  27. package/dist/hub/runtime-host/hub-runtime-host.d.ts +3 -2
  28. package/dist/hub/server/handlers/session-handlers.d.ts +5 -1
  29. package/dist/index.d.ts +10 -7
  30. package/dist/index.js +271 -249
  31. package/dist/remote/remote-environments.d.ts +155 -0
  32. package/dist/remote/remote-helper-entry.d.ts +1 -0
  33. package/dist/remote/remote-helper-entry.js +5 -0
  34. package/dist/remote/remote-helper.d.ts +29 -0
  35. package/dist/remote/remote-helper.js +4 -0
  36. package/dist/remote/shell-path.d.ts +88 -0
  37. package/dist/runtime/host/local-runtime-host.d.ts +2 -2
  38. package/dist/runtime/host/runtime-host.d.ts +11 -1
  39. package/dist/runtime/orchestration/session-runtime.d.ts +3 -0
  40. package/dist/services/global-settings.d.ts +6 -0
  41. package/dist/services/llms/provider-defaults.d.ts +1 -1
  42. package/dist/services/llms/provider-settings.d.ts +20 -18
  43. package/dist/services/local-runtime-bootstrap.d.ts +7 -0
  44. package/dist/services/providers/local-provider-registry.d.ts +3 -3
  45. package/dist/services/providers/local-provider-service.d.ts +3 -1
  46. package/dist/services/providers/provider-config-fields.d.ts +11 -0
  47. package/dist/services/session-import/claude-code.d.ts +1 -1
  48. package/dist/services/session-import/paths.d.ts +9 -0
  49. package/dist/services/telemetry/core-events.d.ts +29 -5
  50. package/dist/services/telemetry/index.d.ts +1 -0
  51. package/dist/services/telemetry/index.js +1 -1
  52. package/dist/services/telemetry/scoped-telemetry.d.ts +31 -0
  53. package/dist/services/workspace/workspace-telemetry.d.ts +5 -0
  54. package/dist/session/models/session-manifest.d.ts +1 -1
  55. package/dist/session/services/persistence-service.d.ts +3 -1
  56. package/dist/session/session-versioning-service.d.ts +8 -0
  57. package/dist/settings/types.d.ts +8 -0
  58. package/dist/tasks/agenda-task-tool.d.ts +1 -1
  59. package/dist/tasks/task-tool.d.ts +3 -3
  60. package/dist/types/chat-schema.d.ts +2 -2
  61. package/dist/types/config.d.ts +5 -0
  62. package/dist/types/session.d.ts +2 -0
  63. package/dist/types.d.ts +4 -4
  64. package/package.json +12 -4
  65. package/dist/cron/runner/resource-limiter.d.ts +0 -8
@@ -0,0 +1,155 @@
1
+ export interface RemoteEnvironmentProfile {
2
+ id: string;
3
+ name: string;
4
+ host: string;
5
+ user?: string;
6
+ port?: number;
7
+ identityFile?: string;
8
+ createdAt: string;
9
+ updatedAt: string;
10
+ }
11
+ export interface RemoteEnvironmentInput {
12
+ id?: string;
13
+ name: string;
14
+ host: string;
15
+ user?: string;
16
+ port?: number;
17
+ identityFile?: string;
18
+ }
19
+ export type RemoteEnvironmentState = "disconnected" | "testing" | "available" | "connecting" | "connected" | "error";
20
+ export interface RemoteEnvironmentStatus {
21
+ profileId: string;
22
+ state: RemoteEnvironmentState;
23
+ updatedAt: string;
24
+ message?: string;
25
+ remotePlatform?: "linux" | "darwin";
26
+ remoteArch?: "x64" | "arm64";
27
+ remoteHome?: string;
28
+ }
29
+ export interface RemoteEnvironmentConnection {
30
+ profile: RemoteEnvironmentProfile;
31
+ profileId: string;
32
+ state: "connected";
33
+ endpoint: string;
34
+ authToken: string;
35
+ workspaceRoot: string;
36
+ homeDir: string;
37
+ platform: "linux" | "darwin";
38
+ arch: "x64" | "arm64";
39
+ remoteHubUrl: string;
40
+ localPort: number;
41
+ connectedAt: string;
42
+ }
43
+ export interface RemoteCommandInput {
44
+ command: string;
45
+ args: string[];
46
+ cwd?: string;
47
+ }
48
+ export interface RemoteCommandResult {
49
+ stdout: string;
50
+ stderr: string;
51
+ exitCode: number;
52
+ }
53
+ export interface RemoteHelperTarget {
54
+ platform: "linux" | "darwin";
55
+ arch: "x64" | "arm64";
56
+ }
57
+ export interface RemoteTunnelProcess {
58
+ readonly pid?: number;
59
+ readonly exitCode: number | null;
60
+ kill(signal?: NodeJS.Signals): boolean;
61
+ once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown;
62
+ once(event: "error", listener: (error: Error) => void): unknown;
63
+ }
64
+ export interface RemoteProcessOptions {
65
+ timeoutMs: number;
66
+ inputFile?: string;
67
+ /** Combined stdout/stderr limit; defaults to 8 MiB. */
68
+ maxOutputBytes?: number;
69
+ }
70
+ export interface RemoteEnvironmentDependencies {
71
+ runProcess(executable: string, args: string[], options: RemoteProcessOptions): Promise<RemoteCommandResult>;
72
+ spawnTunnel(executable: string, args: string[]): RemoteTunnelProcess;
73
+ waitForTunnel(port: number, tunnel: RemoteTunnelProcess, timeoutMs: number): Promise<void>;
74
+ reservePort(): Promise<number>;
75
+ hashFile(path: string): Promise<string>;
76
+ resolveHelperBinary(target: RemoteHelperTarget): Promise<string | undefined>;
77
+ fileReadable(path: string): Promise<boolean>;
78
+ requestHubShutdown(url: string, authToken?: string): Promise<boolean>;
79
+ now(): Date;
80
+ randomId(): string;
81
+ }
82
+ export interface RemoteEnvironmentServiceOptions {
83
+ profilesPath?: string;
84
+ sshPath?: string;
85
+ knownHostsPath?: string;
86
+ connectTimeoutSeconds?: number;
87
+ commandTimeoutMs?: number;
88
+ uploadTimeoutMs?: number;
89
+ tunnelTimeoutMs?: number;
90
+ hubShutdownTimeoutMs?: number;
91
+ helperBinaryPath?: string;
92
+ helperBinaryDirectory?: string;
93
+ env?: NodeJS.ProcessEnv;
94
+ onStatusChange?: (status: RemoteEnvironmentStatus) => void;
95
+ onConnectionLost?: (status: RemoteEnvironmentStatus) => void;
96
+ dependencies?: Partial<RemoteEnvironmentDependencies>;
97
+ }
98
+ export declare class RemoteEnvironmentService {
99
+ private readonly profilesPath;
100
+ private readonly ownerId;
101
+ private readonly sshPath;
102
+ private readonly knownHostsPath?;
103
+ private readonly connectTimeoutSeconds;
104
+ private readonly commandTimeoutMs;
105
+ private readonly uploadTimeoutMs;
106
+ private readonly tunnelTimeoutMs;
107
+ private readonly hubShutdownTimeoutMs;
108
+ private readonly dependencies;
109
+ private readonly onStatusChange?;
110
+ private readonly onConnectionLost?;
111
+ private readonly statuses;
112
+ private readonly connections;
113
+ private activeProfileId;
114
+ private mutationTail;
115
+ constructor(options?: RemoteEnvironmentServiceOptions);
116
+ list(): Promise<RemoteEnvironmentProfile[]>;
117
+ upsert(input: RemoteEnvironmentInput): Promise<RemoteEnvironmentProfile>;
118
+ delete(id: string): Promise<boolean>;
119
+ test(id: string): Promise<RemoteEnvironmentStatus>;
120
+ connect(id: string): Promise<RemoteEnvironmentConnection>;
121
+ private connectProfile;
122
+ disconnect(id?: string): Promise<boolean>;
123
+ private disconnectProfile;
124
+ getActive(): RemoteEnvironmentConnection | undefined;
125
+ getConnection(id: string): RemoteEnvironmentConnection | undefined;
126
+ /**
127
+ * Marks an already-established tunnel as active without doing any SSH work.
128
+ * A client uses this to roll back a host switch when the
129
+ * new Hub runtime cannot be initialized.
130
+ */
131
+ activateConnection(id: string): boolean;
132
+ getStatuses(): RemoteEnvironmentStatus[];
133
+ run(id: string, input: RemoteCommandInput): Promise<RemoteCommandResult>;
134
+ dispose(): Promise<void>;
135
+ private ensureHelper;
136
+ private installHelper;
137
+ private stopManagedHub;
138
+ private inspectRemote;
139
+ private validateDirectory;
140
+ private execRemote;
141
+ private execRemoteAllowFailure;
142
+ private buildSshArgs;
143
+ private buildTunnelArgs;
144
+ private destination;
145
+ private requireProfile;
146
+ private setStatus;
147
+ private handleTunnelEnd;
148
+ private persistPendingCleanup;
149
+ private retryPendingCleanup;
150
+ private readProfiles;
151
+ private writeProfiles;
152
+ private withMutation;
153
+ }
154
+ export declare function remoteHelperBinaryFilename(target: RemoteHelperTarget): string;
155
+ export declare function runRemoteProcess(executable: string, args: string[], options: RemoteProcessOptions): Promise<RemoteCommandResult>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +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.83",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-178563106bf9b78e93790cbfa7bd6529a29b64cba33ceaac6dab6f29c364f3c2".trim()||`source-${String(g.version)}`}function K1(){let J=Number(process.env[Z1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1789451536097)?1789451536097:void 0}function I(J,Q=C()){let Z=e0(J);if(!Z.compatible)return Z;let $=J.buildId?.trim();if(!$)return{compatible:!1,reason:"missing_build"};if($!==Q)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function V0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function Y0(J){let Q=J?.trim().split(/[-+]/,1)[0];if(!Q)return;let Z=Q.split(".").map(($)=>Number($));if(Z.length===0||Z.some(($)=>!Number.isInteger($)||$<0))return;return Z}function W1(J,Q){for(let Z=0;Z<Math.max(J.length,Q.length);Z++){let $=J[Z]??0,X=Q[Z]??0;if($!==X)return $<X?-1:1}return 0}function W0(J,Q){let Z=J.buildId?.trim(),$=Q.buildId?.trim();if(Z&&$&&Z===$)return 0;let X=V0(J.buildEpochMs),j=V0(Q.buildEpochMs);if(X!==void 0&&j!==void 0&&X!==j)return X<j?-1:1;let V=Y0(J.coreVersion),N=Y0(Q.coreVersion);if(V&&N){let Y=W1(V,N);if(Y!==0)return Y}if(Z&&$&&Z!==$)return Z<$?-1:1;return 0}function G0(){return{buildId:C(),buildEpochMs:K1(),coreVersion:String(g.version)}}function P(J,Q){let Z=Q?.self??G0(),$=I(J,Z.buildId??"");if($.compatible)return!0;if($.reason!=="build_mismatch"&&$.reason!=="missing_build")return!1;return W0(Z,J)<=0}function q0(J=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${z1(J)}`,Z=process.env[J1]?.trim()||l(_(),"locks","hub","owners",`${j1(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}async function O(J){try{let Q=JSON.parse(await N0(J,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function F0(J,Q){await c(J,async()=>{let Z=K0(J);await p(Z,{recursive:!0});let $=`${J}.${process.pid}.${a0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(Q,null,2)}
2
+ `,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,await o0($,J);let j;try{j=await X0(Z,"r"),await j.sync()}catch{}finally{await j?.close().catch(()=>{return})}}catch(j){throw await X?.close().catch(()=>{return}),await T($,{force:!0}).catch(()=>{return}),j}})}async function x(J){await c(J,async()=>{await T(J,{force:!0}).catch(()=>{return})})}async function L0(J,Q){return await c(J,async()=>{if((await O(J))?.hubId!==Q)return!1;return await T(J,{force:!0}),!0})}async function B0(J,Q,Z){let $=Y1(J);await p(K0($),{recursive:!0});let X=Date.now()+X1;while(!0){try{await p($,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let N=await N1($);if(!N){if(Date.now()>=X){await u($);continue}await z0(j0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!V1(N.pid)||Y>$1){await u($);continue}if(Date.now()>=X)throw Error(`Timed out waiting for hub ${Q} lock ${$}`);await z0(j0);continue}try{return await r0(l($,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
+ `,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?G1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function G1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as q1,CLINE_HUB_PORT as F1,resolveClineBuildEnv as L1}from"@cline/shared";var B1="CLINE_HUB_HOST",O1="CLINE_HUB_PORT",A1="CLINE_HUB_PATHNAME",U1="127.0.0.1",M1=F1,f1="/hub";function M0(J){return L1(J)==="development"?q1:M1}function C1(J={}){return(J.env??process.env)[B1]?.trim()||U1}function x1(J={}){let Z=(J.env??process.env)[O1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function _1(J={}){return(J.env??process.env)[A1]?.trim()||f1}function f0(J={},Q={}){return{host:J.host??C1(Q),port:J.port??x1(Q),pathname:J.pathname??_1(Q)}}import{join as D1}from"node:path";import{processWorkspaceInfo as Q4}from"@cline/shared";import $4 from"simple-git";var R1="shared:cline",S1="CLINE_HUB_DISCOVERY_PATH",E1="hub-production";function D(J=R1){return q0(`${J}@${C()}`)}function H(){return{ownerId:E1,discoveryPath:process.env[S1]?.trim()||D1(_(),"locks","hub","production.json")}}var p1=8000,l1=200,C0=3000,c1=100,i1=[100,250,500,1000,2000],n1="--cline-hub-daemon",s1=3,t1=60000,x0=new Map;function d1(J,Q=Date.now()){let Z=x0.get(J);if(!Z||Q-Z.windowStartedAt>t1)return x0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=s1}function a1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function o1(){try{let J=b1(_(),"logs","hub-daemon.log");return I1(y1(J),{recursive:!0}),{fd:P1(J,"a"),logPath:J}}catch{return}}function r1(){return R0()==="production"?H():D()}function R(J){return P(J)}function e1(J){try{let Q=JSON.parse(w1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{H1(`${J}.superseded`)}catch{}}function _0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function S(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function D0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await S(J))?.url)return!0;await new Promise((X)=>setTimeout(X,c1))}return!1}async function s(J,Q){if(!d1(J.url))return!1;await E(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await D0(J.url,C0);if(!Z&&J.pid&&J2(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await D0(J.url,C0)}if(Z)await x(Q).catch(()=>{return});return Z}function J2(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function Q2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await E(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await Q2(J)){if(Z)await E(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await E(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Z2(J){if(R0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await x(Q.discoveryPath).catch(()=>{return})}function $2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return h1(new URL(`./entry.${J}`,import.meta.url))}function X2(J,Q){let Z=$2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=k1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[n1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...a1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...u1(process.env),CLINE_NO_INTERACTIVE:"1",[m1]:"1"}}}function j2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function z2(J,Q={}){if(v1())return;let Z=X2(J,Q),$=o1();try{g1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)T1($.fd)}}async function V2(J,Q={}){for(let Z=0;;Z++)try{z2(J,Q);return}catch($){let X=i1[Z];if(!j2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function Y2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Z2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:e1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await S(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await x(J.discoveryPath).catch(()=>{return})}}let z=await S(j);if(z?.url){let W=_0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let i0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,i0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await V2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+p1;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await S(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await S(j);if(G?.url&&!R(G)){let L=_0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,l1))}throw Error("Timed out waiting for detached hub startup.")}async function k(J,Q={}){let Z=r1();return await O0(Z.discoveryPath,async()=>Y2(Z,J,Q))}function F2(){return W2()==="production"?H():D()}function L2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function P0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return P0(J.data);return String(J)}function B2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function S0(J){let Q=J,Z=B2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function E0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,O2="cline-hub-auth.",w0=new Map,H0=new Set,A2=3000;var a="Hub connection closed",U2=250,M2=5000,g0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function f2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?w0.get($):void 0}function C2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!C2(J))return;let Q=new URL(k0(J));return Q.search="",Q.hash="",Q.toString()}function T0(J){let Q=J0(J);return!!Q&&H0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(H0.add(Z),Q?.trim())w0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=E0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new q2(J.toString(),{headers:{...X}}):new(L2())(J.toString(),Q?[`${O2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=E0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:S0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(P0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=S0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();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})}
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
+ `),process.exitCode=1});
@@ -0,0 +1,29 @@
1
+ import { claimHubDaemonProcess } from "@cline/shared";
2
+ import { setHomeDirIfUnset } from "@cline/shared/storage";
3
+ import { requestHubShutdown } from "../hub/client";
4
+ import { ensureDetachedHubServer } from "../hub/daemon";
5
+ import { clearHubDiscoveryIfOwned, readHubDiscovery } from "../hub/discovery";
6
+ import { ensureLoginShellPath } from "./shell-path";
7
+ export type RemoteHelperDependencies = {
8
+ readHubDiscovery: typeof readHubDiscovery;
9
+ clearHubDiscoveryIfOwned: typeof clearHubDiscoveryIfOwned;
10
+ probeProcess: (pid: number) => void;
11
+ requestHubShutdown: typeof requestHubShutdown;
12
+ ensureDetachedHubServer: typeof ensureDetachedHubServer;
13
+ claimHubDaemonProcess: typeof claimHubDaemonProcess;
14
+ loadHubDaemon: () => Promise<unknown>;
15
+ ensureLoginShellPath: typeof ensureLoginShellPath;
16
+ setHomeDirIfUnset: typeof setHomeDirIfUnset;
17
+ homeDir: () => string;
18
+ cwd: () => string;
19
+ env: NodeJS.ProcessEnv;
20
+ writeOutput: (output: string) => void;
21
+ };
22
+ export declare function runRemoteHubEnsure(argv?: string[], dependencies?: RemoteHelperDependencies): Promise<void>;
23
+ /**
24
+ * Handles the SSH bootstrap command and the detached-daemon sentinel. The
25
+ * standalone helper is compiled for the target host and contains no client UI
26
+ * server or command router. Client executables may also use this entrypoint
27
+ * to support the daemon sentinel.
28
+ */
29
+ export declare function runRemoteHelperEntrypoint(argv?: string[], dependencies?: RemoteHelperDependencies): Promise<boolean>;
@@ -0,0 +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.83",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-178563106bf9b78e93790cbfa7bd6529a29b64cba33ceaac6dab6f29c364f3c2".trim()||`source-${String(g.version)}`}function N1(){let J=Number(process.env[Q1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1789451536097)?1789451536097:void 0}function I(J,Q=C()){let Z=r0(J);if(!Z.compatible)return Z;let $=J.buildId?.trim();if(!$)return{compatible:!1,reason:"missing_build"};if($!==Q)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function V0(J){return typeof J==="number"&&Number.isFinite(J)&&J>0?J:void 0}function Y0(J){let Q=J?.trim().split(/[-+]/,1)[0];if(!Q)return;let Z=Q.split(".").map(($)=>Number($));if(Z.length===0||Z.some(($)=>!Number.isInteger($)||$<0))return;return Z}function K1(J,Q){for(let Z=0;Z<Math.max(J.length,Q.length);Z++){let $=J[Z]??0,X=Q[Z]??0;if($!==X)return $<X?-1:1}return 0}function W0(J,Q){let Z=J.buildId?.trim(),$=Q.buildId?.trim();if(Z&&$&&Z===$)return 0;let X=V0(J.buildEpochMs),j=V0(Q.buildEpochMs);if(X!==void 0&&j!==void 0&&X!==j)return X<j?-1:1;let V=Y0(J.coreVersion),N=Y0(Q.coreVersion);if(V&&N){let Y=K1(V,N);if(Y!==0)return Y}if(Z&&$&&Z!==$)return Z<$?-1:1;return 0}function G0(){return{buildId:C(),buildEpochMs:N1(),coreVersion:String(g.version)}}function P(J,Q){let Z=Q?.self??G0(),$=I(J,Z.buildId??"");if($.compatible)return!0;if($.reason!=="build_mismatch"&&$.reason!=="missing_build")return!1;return W0(Z,J)<=0}function q0(J=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${j1(J)}`,Z=process.env[e0]?.trim()||l(_(),"locks","hub","owners",`${X1(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}async function O(J){try{let Q=JSON.parse(await N0(J,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,buildEpochMs:typeof Q.buildEpochMs==="number"?Q.buildEpochMs:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function F0(J,Q){await c(J,async()=>{let Z=K0(J);await p(Z,{recursive:!0});let $=`${J}.${process.pid}.${d0(6).toString("hex")}.tmp`,X;try{X=await X0($,"wx",384),await X.writeFile(`${JSON.stringify(Q,null,2)}
2
+ `,{encoding:"utf8"}),await X.sync(),await X.close(),X=void 0,await a0($,J);let j;try{j=await X0(Z,"r"),await j.sync()}catch{}finally{await j?.close().catch(()=>{return})}}catch(j){throw await X?.close().catch(()=>{return}),await T($,{force:!0}).catch(()=>{return}),j}})}async function x(J){await c(J,async()=>{await T(J,{force:!0}).catch(()=>{return})})}async function L0(J,Q){return await c(J,async()=>{if((await O(J))?.hubId!==Q)return!1;return await T(J,{force:!0}),!0})}async function B0(J,Q,Z){let $=V1(J);await p(K0($),{recursive:!0});let X=Date.now()+$1;while(!0){try{await p($,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let N=await Y1($);if(!N){if(Date.now()>=X){await u($);continue}await z0(j0);continue}let Y=Date.now()-Date.parse(N.acquiredAt);if(!z1(N.pid)||Y>Z1){await u($);continue}if(Date.now()>=X)throw Error(`Timed out waiting for hub ${Q} lock ${$}`);await z0(j0);continue}try{return await o0(l($,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
+ `,"utf8"),await Z()}finally{await u($)}}}function c(J,Q){return B0(`${J}.mutation`,"discovery mutation",Q)}function O0(J,Q){return B0(J,"startup",Q)}async function w(J,Q){try{let Z=await fetch(Q?.authToken?W1(J):U0(J),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let $=await Z.json();if(typeof $.protocolVersion!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string")return;return{protocolVersion:$.protocolVersion,minClientProtocolVersion:typeof $.minClientProtocolVersion==="string"?$.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof $.maxClientProtocolVersion==="string"?$.maxClientProtocolVersion:void 0,capabilities:Array.isArray($.capabilities)?$.capabilities.filter((X)=>typeof X==="string"):void 0,coreVersion:typeof $.coreVersion==="string"?$.coreVersion:void 0,buildId:typeof $.buildId==="string"?$.buildId:void 0,buildEpochMs:typeof $.buildEpochMs==="number"?$.buildEpochMs:void 0,host:$.host,port:$.port,url:$.url,hubId:typeof $.hubId==="string"?$.hubId:void 0,authToken:typeof $.authToken==="string"?$.authToken:void 0,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:typeof $.startedAt==="string"?$.startedAt:void 0,updatedAt:typeof $.updatedAt==="string"?$.updatedAt:void 0}}catch{return}}function A0(J,Q,Z="/hub"){return new URL(`ws://${J}:${Q}${Z}`).toString()}function U0(J){let Q=new URL(J);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function W1(J){let Q=new URL(U0(J));return Q.pathname="/status",Q.toString()}import{CLINE_HUB_DEV_PORT as G1,CLINE_HUB_PORT as q1,resolveClineBuildEnv as F1}from"@cline/shared";var L1="CLINE_HUB_HOST",B1="CLINE_HUB_PORT",O1="CLINE_HUB_PATHNAME",A1="127.0.0.1",U1=q1,M1="/hub";function M0(J){return F1(J)==="development"?G1:U1}function f1(J={}){return(J.env??process.env)[L1]?.trim()||A1}function C1(J={}){let Z=(J.env??process.env)[B1]?.trim();if(!Z)return M0(J);let $=Number.parseInt(Z,10);if(!Number.isInteger($)||$<1||$>65535)return M0(J);return $}function x1(J={}){return(J.env??process.env)[O1]?.trim()||M1}function f0(J={},Q={}){return{host:J.host??f1(Q),port:J.port??C1(Q),pathname:J.pathname??x1(Q)}}import{join as _1}from"node:path";import{processWorkspaceInfo as J4}from"@cline/shared";import Z4 from"simple-git";var D1="shared:cline",R1="CLINE_HUB_DISCOVERY_PATH",E1="hub-production";function D(J=D1){return q0(`${J}@${C()}`)}function H(){return{ownerId:E1,discoveryPath:process.env[R1]?.trim()||_1(_(),"locks","hub","production.json")}}var u1=8000,p1=200,C0=3000,l1=100,c1=[100,250,500,1000,2000],i1="--cline-hub-daemon",n1=3,s1=60000,x0=new Map;function t1(J,Q=Date.now()){let Z=x0.get(J);if(!Z||Q-Z.windowStartedAt>s1)return x0.set(J,{count:1,windowStartedAt:Q}),!0;return Z.count+=1,Z.count<=n1}function d1(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function a1(){try{let J=y1(_(),"logs","hub-daemon.log");return T1(k1(J),{recursive:!0}),{fd:I1(J,"a"),logPath:J}}catch{return}}function o1(){return R0()==="production"?H():D()}function R(J){return P(J)}function r1(J){try{let Q=JSON.parse(P1(`${J}.superseded`,"utf8"));return{url:typeof Q.url==="string"?Q.url:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0}}catch{return}}function i(J){try{w1(`${J}.superseded`)}catch{}}function _0(J,Q,Z){if(!Q||Q.url!==Z)return J;return{...J,authToken:J.authToken??Q.authToken,pid:J.pid??Q.pid}}async function E(J,Q){try{return await w(J,{authToken:Q})}catch{return}}async function D0(J,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await E(J))?.url)return!0;await new Promise((X)=>setTimeout(X,l1))}return!1}async function s(J,Q){if(!t1(J.url))return!1;await S(J.url,J.authToken,"retired by newer install").catch(()=>!1),await b(J.url,J.authToken).catch(()=>!1);let Z=await D0(J.url,C0);if(!Z&&J.pid&&e1(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}Z=await D0(J.url,C0)}if(Z)await x(Q).catch(()=>{return});return Z}function e1(J){try{return process.kill(J,0),!0}catch(Q){return Q?.code==="EPERM"}}async function J2(J){try{return(await t(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function n(J,Q){if(R(J))return"reusable";let Z=await S(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await J2(J)){if(Z)await S(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let $=await s(J,Q);if(!$&&Z)await S(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return $?"retired":"failed"}async function Q2(J){if(R0()!=="production")return;let Q=D();if(Q.discoveryPath===J.discoveryPath)return;let Z=await O(Q.discoveryPath);if(Z?.url)await s(Z,Q.discoveryPath);else await x(Q.discoveryPath).catch(()=>{return})}function Z2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return b1(new URL(`./entry.${J}`,import.meta.url))}function $2(J,Q){let Z=Z2(),$=process.execPath?.trim();if(!$)throw Error("unable to resolve runtime executable for hub daemon");let X=H1($).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),V=X&&Z.toLowerCase().endsWith(".ts"),N=j?[i1]:[...V?["--conditions=development"]:[],Z];return{launcher:$,args:[...N,"--cwd",J,...d1(Q),...Q.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...v1(process.env),CLINE_NO_INTERACTIVE:"1",[h1]:"1"}}}function X2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let Z="message"in J?J.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function j2(J,Q={}){if(m1())return;let Z=$2(J,Q),$=a1();try{S1(Z.launcher,Z.args,{detached:!0,stdio:$?["ignore",$.fd,$.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if($)g1($.fd)}}async function z2(J,Q={}){for(let Z=0;;Z++)try{j2(J,Q);return}catch($){let X=c1[Z];if(!X2($)||X===void 0)throw $;await new Promise((j)=>setTimeout(j,X))}}async function V2(J,Q,Z={}){let $=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),X=f0(Z),j=A0(X.host,X.port,X.pathname),V=(W)=>{if(!$)y(W.url,W.authToken);return W};await Q2(J).catch(()=>{return});let N=await O(J.discoveryPath),Y=N?.url?void 0:r1(J.discoveryPath),K=!1;if(N?.url){let W=N.authToken;if(!W)K=!0,await s(N,J.discoveryPath);else{let G=await E(N.url,W);if(G?.url&&R(G)&&await A(G.url,{authToken:W}))return i(J.discoveryPath),V({url:G.url,authToken:W});if(G?.url){if(await n({...G,authToken:W},J.discoveryPath)==="deferred_busy"&&await A(G.url,{authToken:W}))return V({url:G.url,authToken:W})}else await x(J.discoveryPath).catch(()=>{return})}}let z=await E(j);if(z?.url){let W=_0(z,N??Y,j);if(R(z)){let L=[z.authToken,N?.authToken,Y?.authToken].filter((f)=>typeof f==="string"&&f.trim().length>0);for(let f of L){if(!await A(z.url,{authToken:f}))continue;let c0={hubId:z.hubId??`repaired-${z.port}`,protocolVersion:z.protocolVersion,minClientProtocolVersion:z.minClientProtocolVersion,maxClientProtocolVersion:z.maxClientProtocolVersion,capabilities:z.capabilities,coreVersion:z.coreVersion,buildId:z.buildId,authToken:f,host:z.host,port:z.port,url:z.url,pid:z.pid??N?.pid??Y?.pid,startedAt:z.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await F0(J.discoveryPath,c0)}catch{}return i(J.discoveryPath),V({url:z.url,authToken:f})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let G=await n(W,J.discoveryPath);if(G==="deferred_busy"){for(let L of[W.authToken,N?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await A(z.url,{authToken:L}))return V({url:z.url,authToken:L});if(Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(G==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=Z.allowPortFallback===!0&&X.port!==0?{...X,port:0}:X;await z2(Q,{...B,manageConnectors:Z.manageConnectors});let U=Date.now()+u1;while(Date.now()<U){let W=await O(J.discoveryPath);if(W?.url&&W.authToken){let L=await E(W.url,W.authToken);if(L?.url&&R(L)&&await A(L.url,{authToken:W.authToken}))return i(J.discoveryPath),V({url:L.url,authToken:W.authToken})}let G=await E(j);if(G?.url&&!R(G)){let L=_0(G,W??Y,j),M=await n(L,J.discoveryPath);if(M==="deferred_busy"&&W?.authToken&&await A(G.url,{authToken:W.authToken}))return V({url:G.url,authToken:W.authToken});if(M==="failed"&&Z.allowPortFallback!==!0&&X.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,p1))}throw Error("Timed out waiting for detached hub startup.")}async function k(J,Q={}){let Z=o1();return await O0(Z.discoveryPath,async()=>V2(Z,J,Q))}function q2(){return K2()==="production"?H():D()}function F2(){let J=globalThis.WebSocket;if(!J)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return J}function P0(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString();if(J instanceof ArrayBuffer)return Buffer.from(J).toString();if(Array.isArray(J))return Buffer.concat(J.map((Q)=>Buffer.from(Q))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return P0(J.data);return String(J)}function L2(J){if(typeof J==="string")return J;if(J instanceof Uint8Array)return Buffer.from(J).toString("utf8");if(J instanceof ArrayBuffer)return Buffer.from(J).toString("utf8");return""}function E0(J){let Q=J,Z=L2(Q.reason);return new q("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:a,{closeCode:Q.code,closeReason:Z||void 0})}function S0(J,Q){if(J instanceof q)return J;if(J instanceof Error)return new q("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new q("hub_connect_failed",J.error.message);let Z=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if(Z)return new q("hub_connect_failed",Z);let $=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new q("hub_connect_failed",$?`Failed to connect to hub at ${Q.toString()} (${$} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var d="*",h=8000,B2="cline-hub-auth.",w0=new Map,H0=new Set,O2=3000;var a="Hub connection closed",A2=250,U2=5000,g0=0.5;class q extends Error{code;details;constructor(J,Q,Z){super(Q);this.code=J;this.details=Z;this.name="HubTransportError"}}function M2(J){return J instanceof q}class o extends Error{command;code;constructor(J,Q,Z){super(Z);this.command=J;this.code=Q;this.name="HubCommandError"}}function e(J,Q={}){let Z=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),Z)return Z;if(Q.skipRegistry)return;let $=J0(J.toString());return $?w0.get($):void 0}function f2(J){try{let Z=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function J0(J){if(!f2(J))return;let Q=new URL(k0(J));return Q.search="",Q.hash="",Q.toString()}function T0(J){let Q=J0(J);return!!Q&&H0.has(Q)}function y(J,Q){let Z=J0(J);if(Z){if(H0.add(Z),Q?.trim())w0.set(Z,Q)}return J}class Q0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new q("hub_connection_closed",a);sawSocketClose=!1;registered=!1;capabilities;constructor(J){this.options=J;if(J.authToken?.trim()&&J.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=J.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=J.url,this.capabilities=[...J.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(J){if(this.capabilities=J.map((Q)=>({...Q})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let J=new URL(this.currentUrl),Q=this.options.authToken?.trim()||e(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Q&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,$=this.openSocket(J,Q,Z),X;this.connectPromise=$.then(async(V)=>{if(X=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let N of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(N));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(X&&this.socket===X){this.lastCloseError=S0(V,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{X.close()}catch{}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}throw V}}async openSocket(J,Q,Z){let $=this.options.resolveConnectionHeaders,X;if($){let Y;try{X=await Promise.race([Promise.resolve().then(()=>$()),new Promise((K,z)=>{Y=setTimeout(()=>{z(new q("hub_connect_timeout",`Timed out resolving hub connection headers after ${h}ms`))},h)})])}catch(K){let z=K instanceof q?K:new q("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=z;throw z}finally{clearTimeout(Y)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(X&&Object.keys(X).some((Y)=>Y.toLowerCase()==="sec-websocket-protocol")){let Y=new q("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=Y;throw Y}let j=X?new G2(J.toString(),{headers:{...X}}):new(F2())(J.toString(),Q?[`${B2}${Q}`]:void 0);this.socket=j;let V=!1,N=new Promise((Y,K)=>{let z=!1,F=setTimeout(()=>{if(z)return;z=!0,V=!0;let B=new q("hub_connect_timeout",`Timed out connecting to hub after ${h}ms`);if(this.socket===j)this.lastCloseError=B,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}K(B)},h);j.addEventListener("open",()=>{if(z)return;z=!0,clearTimeout(F),Y()}),j.addEventListener("error",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=S0(B,J);if(this.socket===j)this.lastCloseError=U,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(U)}),j.addEventListener("close",(B)=>{if(z)return;z=!0,clearTimeout(F);let U=V?this.lastCloseError:E0(B);if(this.socket===j){if(!V)this.lastCloseError=U,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(U)})});return j.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(P0(Y)))}),j.addEventListener("close",(Y)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=E0(Y),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await N,j}subscribe(J,Q){let Z=Q?.sessionId?.trim()||void 0,$={listener:J,sessionId:Z};return this.listeners.add($),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete($))return;this.adjustSubscriptionCount(Z,-1)}}async command(J,Q,Z,$){let X=0,j=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Q,Z,$)}catch(V){if(!j||X>=1||!await this.recoverLocalHubTransport(V))throw V;X+=1}}async commandOnce(J,Q,Z,$,X=!0){if(X)await this.connect();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})}
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};
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Login-shell PATH resolution for the desktop sidecar.
3
+ *
4
+ * When the Tauri app is launched from Finder/the Dock on macOS, it inherits
5
+ * launchd's minimal PATH (/usr/bin:/bin:/usr/sbin:/sbin) instead of the
6
+ * user's shell PATH. The sidecar — and every process it spawns for the agent
7
+ * (bash tool, MCP servers) — then can't find tools like `gh` that live in
8
+ * /opt/homebrew/bin or other shell-profile-added directories, even though
9
+ * the same task works from the CLI in a terminal.
10
+ *
11
+ * At startup we ask the user's login shell for its PATH and merge it into
12
+ * process.env.PATH, so child processes see the same PATH a terminal would.
13
+ */
14
+ export declare function defaultShellFor(platform: NodeJS.Platform): string;
15
+ /**
16
+ * The user's configured login shell. The account database is authoritative:
17
+ * a GUI-launched process has no parent shell, so $SHELL may be unset there.
18
+ * userInfo() reads getpwuid(), which on macOS goes through DirectoryServices
19
+ * — the same source `dscl . -read /Users/$USER UserShell` reports — and on
20
+ * Linux resolves via NSS (/etc/passwd et al.). $SHELL and the platform
21
+ * default are fallbacks for environments with no passwd entry.
22
+ */
23
+ export declare function loginShellFor(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string;
24
+ export interface ShellInvocation {
25
+ args: string[];
26
+ /**
27
+ * argv[0] the shell should see. A leading dash is the historical "you
28
+ * are a login shell" signal, used where -l can't be passed as a flag.
29
+ */
30
+ argv0?: string;
31
+ }
32
+ /**
33
+ * How to invoke a shell so it sources its profiles and runs a command.
34
+ * csh/tcsh accept -l only as the sole flag, so they're marked login via the
35
+ * argv[0] dash convention instead (sources ~/.login on top of the always-read
36
+ * ~/.cshrc or ~/.tcshrc); everything else gets login (-l, ~/.zprofile —
37
+ * Homebrew's shellenv) plus interactive (-i, ~/.zshrc — nvm-style version
38
+ * managers) as separate flags.
39
+ */
40
+ export declare function shellInvocation(shell: string, command: string): ShellInvocation;
41
+ /**
42
+ * Extract the PATH value printed between the sentinel markers, ignoring any
43
+ * noise a shell profile writes to stdout around it.
44
+ */
45
+ export declare function extractMarkedPath(output: string): string | undefined;
46
+ /**
47
+ * Merge the login shell's PATH with the current one: shell entries first (so
48
+ * profile-managed dirs like /opt/homebrew/bin win), then any current entries
49
+ * the shell PATH doesn't already contain (so explicitly-injected dirs from
50
+ * the launching environment aren't lost). Duplicates are dropped.
51
+ */
52
+ export declare function mergePaths(shellPath: string, currentPath: string): string;
53
+ /**
54
+ * Run the user's shell with its profiles sourced and capture its PATH.
55
+ * Resolves to undefined on any failure (missing shell, timeout, profile
56
+ * error) — callers should treat that as "keep the current PATH".
57
+ */
58
+ export declare function resolveLoginShellPath(shell: string, timeoutMs?: number): Promise<string | undefined>;
59
+ /**
60
+ * Resolve the login shell's PATH and merge it into process.env.PATH. The
61
+ * shell comes from the account database (see loginShellFor); if it can't
62
+ * produce a PATH (exotic shell, broken profile), retry once with the
63
+ * platform default shell before giving up.
64
+ *
65
+ * No-op on Windows (the GUI PATH comes from the registry there) and when
66
+ * CLINE_SIDECAR_SKIP_SHELL_PATH is set. Failures are reported via the
67
+ * returned status but never block startup. The result never contains the
68
+ * resolved PATH itself so it is safe to log verbatim.
69
+ */
70
+ export declare function ensureLoginShellPath(options?: {
71
+ platform?: NodeJS.Platform;
72
+ env?: NodeJS.ProcessEnv;
73
+ timeoutMs?: number;
74
+ /** Test seam: overrides passwd/$SHELL discovery of the user's shell. */
75
+ userShell?: string;
76
+ /** Test seam: overrides the platform-default fallback shell. */
77
+ fallbackShell?: string;
78
+ }): Promise<{
79
+ status: "applied";
80
+ pathEntries: number;
81
+ shell: string;
82
+ } | {
83
+ status: "skipped";
84
+ reason: string;
85
+ } | {
86
+ status: "failed";
87
+ shell: string;
88
+ }>;
@@ -11,7 +11,7 @@ import { RuntimeOAuthTokenManager } from "../orchestration/runtime-oauth-token-m
11
11
  import type { RuntimeBuilder } from "../orchestration/session-runtime";
12
12
  import { SessionRuntime } from "../orchestration/session-runtime-orchestrator";
13
13
  import { type SessionBackend } from "./local/session-record";
14
- import type { PendingPromptsServiceApi, RestoreSessionInput, RestoreSessionResult, RuntimeHost, RuntimeHostSubscribeOptions, SendSessionInput, SessionConnectionUpdate, SessionUsageSummary, StartSessionInput, StartSessionResult } from "./runtime-host";
14
+ import type { ListSessionsOptions, PendingPromptsServiceApi, RestoreSessionInput, RestoreSessionResult, RuntimeHost, RuntimeHostSubscribeOptions, SendSessionInput, SessionConnectionUpdate, SessionUsageSummary, StartSessionInput, StartSessionResult } from "./runtime-host";
15
15
  export interface LocalRuntimeHostOptions {
16
16
  distinctId?: string;
17
17
  sessionService: SessionBackend;
@@ -67,7 +67,7 @@ export declare class LocalRuntimeHost implements RuntimeHost {
67
67
  stopSession(sessionId: string): Promise<void>;
68
68
  dispose(reason?: string): Promise<void>;
69
69
  getSession(sessionId: string): Promise<SessionRecord | undefined>;
70
- listSessions(limit?: number): Promise<SessionRecord[]>;
70
+ listSessions(limit?: number, options?: ListSessionsOptions): Promise<SessionRecord[]>;
71
71
  deleteSession(sessionId: string): Promise<boolean>;
72
72
  updateSession(sessionId: string, updates: {
73
73
  prompt?: string | null;
@@ -180,6 +180,10 @@ export interface RestoreSessionResult {
180
180
  messages?: LlmsProviders.MessageWithMetadata[];
181
181
  checkpoint: CheckpointEntry;
182
182
  }
183
+ export interface ListSessionsOptions {
184
+ /** Only root sessions: excludes subagent and team-task child rows. */
185
+ rootOnly?: boolean;
186
+ }
183
187
  /**
184
188
  * RuntimeHost is the transport/runtime boundary for core session execution.
185
189
  * Callers must normalize broad local config into `RuntimeSessionConfig`
@@ -194,7 +198,7 @@ export interface RuntimeHost {
194
198
  stopSession(sessionId: string): Promise<void>;
195
199
  dispose(reason?: string): Promise<void>;
196
200
  getSession(sessionId: string): Promise<SessionRecord | undefined>;
197
- listSessions(limit?: number): Promise<SessionRecord[]>;
201
+ listSessions(limit?: number, options?: ListSessionsOptions): Promise<SessionRecord[]>;
198
202
  deleteSession(sessionId: string): Promise<boolean>;
199
203
  updateSession(sessionId: string, updates: {
200
204
  prompt?: string | null;
@@ -220,6 +224,12 @@ export interface RuntimeHost {
220
224
  readLiveSessionMessages?(sessionId: string): Promise<LlmsProviders.MessageWithMetadata[]>;
221
225
  dispatchHookEvent(payload: HookEventPayload): Promise<void>;
222
226
  subscribe(listener: (event: CoreSessionEvent) => void, options?: RuntimeHostSubscribeOptions): () => void;
227
+ /**
228
+ * Whether this host currently holds a live-event subscription for the
229
+ * session. Optional: only hosts that subscribe to sessions individually
230
+ * (e.g. hub clients) have anything to report.
231
+ */
232
+ hasSessionSubscription?(sessionId: string): boolean;
223
233
  }
224
234
  export type RuntimeHostMode = "auto" | "local" | "hub" | "remote";
225
235
  export {};
@@ -1,4 +1,5 @@
1
1
  import type { AgentConfig, AgentEvent, AgentHooks, AgentResult, AgentTool, BasicLogger, ITelemetryService, ModelTool, RuntimeConfigExtensionKind, ToolApprovalRequest, ToolApprovalResult } from "@cline/shared";
2
+ import type { AgentPluginPackageMcpServer, AgentPluginPackageSkill } from "../../extensions/agent-plugin";
2
3
  import type { UserInstructionConfigService } from "../../extensions/config";
3
4
  import type { RunCommandExecutionController, ToolExecutors } from "../../extensions/tools";
4
5
  import type { AgentTeamsRuntime, DelegatedAgentConfigProvider, SubAgentEndContext, SubAgentStartContext, TeamEvent } from "../../extensions/tools/team";
@@ -47,6 +48,8 @@ export interface RuntimeBuilderInput {
47
48
  onTeamRestored?: () => void;
48
49
  userInstructionService?: UserInstructionConfigService;
49
50
  pluginSkillDirectories?: ReadonlyArray<string>;
51
+ agentPluginSkills?: ReadonlyArray<AgentPluginPackageSkill>;
52
+ agentPluginMcpServers?: ReadonlyArray<AgentPluginPackageMcpServer>;
50
53
  configExtensions?: RuntimeConfigExtensionKind[];
51
54
  toolExecutors?: Partial<ToolExecutors>;
52
55
  runCommandExecutionController?: RunCommandExecutionController;
@@ -33,6 +33,7 @@ export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
33
33
  enabled: z.ZodBoolean;
34
34
  }, z.core.$strip>>>;
35
35
  disabledPlugins: z.ZodOptional<z.ZodPipe<z.ZodPreprocess<z.ZodOptional<z.ZodArray<z.ZodString>>, unknown>, z.ZodTransform<string[] | undefined, string[] | undefined>>>;
36
+ disabledAgentPlugins: z.ZodOptional<z.ZodPipe<z.ZodPreprocess<z.ZodOptional<z.ZodArray<z.ZodString>>, unknown>, z.ZodTransform<string[] | undefined, string[] | undefined>>>;
36
37
  }, z.core.$strip>, z.ZodTransform<{
37
38
  telemetryOptOut: boolean;
38
39
  autoUpdateEnabled: boolean;
@@ -44,6 +45,7 @@ export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
44
45
  disabledTools?: string[];
45
46
  tools?: ModelToolSettings;
46
47
  disabledPlugins?: string[];
48
+ disabledAgentPlugins?: string[];
47
49
  }, {
48
50
  telemetryOptOut: boolean;
49
51
  autoUpdateEnabled: boolean;
@@ -57,6 +59,7 @@ export declare const GlobalSettingsSchema: z.ZodPipe<z.ZodObject<{
57
59
  enabled: boolean;
58
60
  }>> | undefined;
59
61
  disabledPlugins?: string[] | undefined;
62
+ disabledAgentPlugins?: string[] | undefined;
60
63
  }>>;
61
64
  export type GlobalSettings = z.infer<typeof GlobalSettingsSchema>;
62
65
  export interface WriteGlobalSettingsOptions {
@@ -92,6 +95,7 @@ export declare function setTuiThemeGlobally(tuiTheme: string): void;
92
95
  export declare function setToolAutoApproveGlobally(toolAutoApprove: boolean): void;
93
96
  export declare function resolveDisabledToolNames(disabledToolNames?: ReadonlyArray<string>): Set<string>;
94
97
  export declare function resolveDisabledPluginPaths(disabledPluginPaths?: ReadonlyArray<string>): Set<string>;
98
+ export declare function resolveDisabledAgentPluginNames(disabledPluginNames?: ReadonlyArray<string>): Set<string>;
95
99
  export declare function isToolDisabledGlobally(toolName: string): boolean;
96
100
  export declare function resolveModelToolSettings(): ModelToolSettings;
97
101
  export declare function isModelToolEnabledGlobally(name: ConfigurableModelToolName): boolean;
@@ -101,6 +105,8 @@ export declare function setDisabledTools(toolNames: ReadonlyArray<string>, disab
101
105
  export declare function setToolDisabledGlobally(toolName: string, disabled: boolean): boolean;
102
106
  export declare function isPluginDisabledGlobally(pluginPath: string): boolean;
103
107
  export declare function setDisabledPlugin(pluginPath: string, disabledValue: boolean): void;
108
+ export declare function isAgentPluginDisabledGlobally(pluginName: string): boolean;
109
+ export declare function setDisabledAgentPlugin(pluginName: string, disabledValue: boolean): void;
104
110
  export declare function filterDisabledPluginPaths(pluginPaths: ReadonlyArray<string>, disabledPluginPaths?: ReadonlyArray<string>): string[];
105
111
  export declare function filterDisabledTools<T extends Pick<AgentTool, "name">>(tools: ReadonlyArray<T>, disabledToolNames?: ReadonlyArray<string>): T[];
106
112
  export declare function filterExtensionToolRegistrations(extensions: AgentConfig["extensions"], disabledToolNames?: ReadonlyArray<string>): AgentConfig["extensions"];
@@ -28,7 +28,7 @@ export declare const DEFAULT_MODELS_CATALOG_URL = "https://models.dev/api.json";
28
28
  */
29
29
  export declare function isPrivateModelCatalogProvider(providerId: string): boolean;
30
30
  export declare function clearPublicModelsCatalogCache(): void;
31
- export declare function getLiveModelsCatalog(options?: Pick<ModelCatalogConfig, "url" | "cacheTtlMs">): Promise<Record<string, Record<string, ModelInfo>>>;
31
+ export declare function getLiveModelsCatalog(options?: Pick<ModelCatalogConfig, "url" | "cacheTtlMs" | "includeClineCloudModels">): Promise<Record<string, Record<string, ModelInfo>>>;
32
32
  export declare function clearLiveModelsCatalogCache(url?: string): void;
33
33
  export declare function clearPrivateModelsCatalogCache(): void;
34
34
  export declare const OPENAI_COMPATIBLE_PROVIDERS: Record<string, ProviderDefaults>;