@cline/core 0.0.85-nightly.1790216958 → 0.0.86
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloud/index.js +9 -9
- package/dist/hub/client/index.d.ts +5 -0
- package/dist/hub/daemon/entry.js +152 -152
- package/dist/hub/index.js +174 -174
- package/dist/index.d.ts +2 -0
- package/dist/index.js +208 -207
- package/dist/remote/remote-helper-entry.js +4 -4
- package/dist/remote/remote-helper.js +4 -4
- package/dist/services/plugin-commands.d.ts +28 -0
- package/dist/services/telemetry/core-events.d.ts +1 -0
- package/dist/services/telemetry/index.js +1 -1
- package/package.json +4 -4
package/dist/cloud/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{randomUUID as
|
|
2
|
-
`)[0]??"").trim().slice(0,72)}class L extends Error{code;detail;connectUrl;status;constructor(J,Z,$,X){super(`${k1}${JSON.stringify({code:J,message:Z,connectUrl:$})}`);this.code=J;this.detail=Z;this.connectUrl=$;this.status=X;this.name="CloudSessionError"}}function Y0(J){let Z=J.length;while(Z>0&&J[Z-1]==="/")Z--;return J.slice(0,Z)}function h1(J){return`${C0}${J}`.slice(0,255)}function R0(J){return J?.startsWith(C0)===!0}function Q0(J){switch(J){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return J;default:return}}function X0(J){let Z=C1(J.replace(/^workos:/,""));return typeof Z?.sub==="string"&&Z.sub.trim()?Z.sub.trim():void 0}function w0(J){return new Promise((Z,$)=>{if(J.aborted){$(J.reason);return}let X=()=>{clearTimeout(Y),$(J.reason)},Y=setTimeout(()=>{J.removeEventListener("abort",X),Z()},b1);J.addEventListener("abort",X,{once:!0})})}function g1(J,Z){if(J&&typeof J==="object"){let $=J.error;if(typeof $==="string"&&$.trim())return $.trim()}return Z}function T0(J,Z,$,X){let Y=g1(Z,`Cloud session request failed (${J})`);if(J===401)return new L("authentication_required",Y);if(J===404)return new L("session_not_found",Y);if(J===410)return new L("session_expired",Y);if(J===412)return new L("github_not_connected",Y,X??`${Y0($)}/dashboard/integrations`);if(J===403&&Y.trim().toLowerCase()==="forbidden")return new L("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,J);return new L("request_failed",Y,void 0,J)}class y1{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;constructor(J){this.options=J;this.apiBaseUrl=Y0(J.apiBaseUrl),this.appBaseUrl=Y0(J.appBaseUrl),this.fetchImpl=J.fetch??fetch,this.createTimeoutMs=J.createTimeoutMs??E1}async request(J,Z={},$,X){let Y=!1;while(!0){let Q=typeof X==="string"?X:X?.token??await this.options.getAuthToken();if(!Q?.trim())throw new L("authentication_required","Sign in to Cline before starting a cloud session.");let j=await this.fetchImpl(`${this.apiBaseUrl}${J}`,{...Z,signal:Z.signal??AbortSignal.timeout($0),headers:{Accept:"application/json",Authorization:`Bearer ${Q.trim()}`,...Z.body?{"Content-Type":"application/json"}:{},...Z.headers}}),V=j.status===204?void 0:await j.json().catch(()=>{return});if(!j.ok){if(j.status===401&&typeof X==="object"&&!Y&&await this.refreshCreationAuth(X)){Y=!0;continue}throw T0(j.status,V,this.appBaseUrl,$)}return V?.data}}async refreshCreationAuth(J){if(!J.subject)return!1;let Z=(await this.options.getAuthToken())?.trim();if(!Z||Z===J.token||X0(Z)!==J.subject)return!1;return J.token=Z,!0}async list(J){return await this.listWithToken(J)}async listWithToken(J,Z,$=!1){let X=J?.trim()?`?organizationId=${encodeURIComponent(J.trim())}`:"";return(await this.request(`/api/v1/session${X}`,{},void 0,Z)??[]).flatMap((Q)=>{if(!Q||typeof Q!=="object"||typeof Q.id!=="string")return[];return[{...Q,title:!$&&R0(Q.title)?void 0:Q.title,repoContext:Q.repoContext&&typeof Q.repoContext==="object"?Q.repoContext:{},metadata:{...Q.metadata&&typeof Q.metadata==="object"?Q.metadata:{},...!$&&R0(Q.title)?{createRequestTitle:Q.title}:{}}}]})}async listRepositories(J){let Z=J?.trim(),$=Z?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,X=Z?`/api/v1/organizations/${encodeURIComponent(Z)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let Y=await this.request(X)??[];return{connected:!0,connectUrl:$,repositories:Y.flatMap((Q)=>{let j=Number(Q.id),V=String(Q.html_url??Q.clone_url??"").trim();if(!Number.isSafeInteger(j)||j<=0||!V)return[];let G=String(Q.name??"").trim();return[{id:j,name:G,fullName:String(Q.full_name??(G||V)).trim(),url:V,defaultBranch:String(Q.default_branch??"").trim()}]})}}catch(Y){if(Y instanceof L&&Y.code==="session_not_found")return{connected:!1,connectUrl:$,repositories:[]};throw Y}}async listBranches(J,Z,$={}){if(!Number.isSafeInteger(J)||J<=0)throw new L("request_failed","Select a GitHub repository before loading branches.");let X=Z?.trim(),Y=X?`/api/v1/organizations/${encodeURIComponent(X)}/integrations/github/repositories/${J}/branches`:`/api/v1/integrations/github/repositories/${J}/branches`,Q=new URLSearchParams,j=$.query?.trim(),V=$.cursor?.trim();if(j)Q.set("query",j);if(V)Q.set("cursor",V);let G=Q.size>0?`${Y}?${Q}`:Y;try{let N=await this.request(G),K=Array.isArray(N)?N:Array.isArray(N?.items)?N.items:[],W=j?.toLowerCase();return{available:!0,branches:K.flatMap((q)=>{let z=String(q.name??"").trim();return z&&(!Array.isArray(N)||!W||z.toLowerCase().includes(W))?[z]:[]}),nextToken:Array.isArray(N)?"":String(N?.nextToken??"").trim()}}catch(N){if(N instanceof L&&N.code==="session_not_found")return{available:!1,branches:[]};throw N}}async status(J,Z={}){return await this.request(`/api/v1/session/${encodeURIComponent(J)}/status`,{signal:Z.signal},void 0,Z.authToken)}async create(J){let Z=(await this.options.getAuthToken())?.trim();if(!Z)throw new L("authentication_required","Sign in to Cline before starting a cloud session.");let $={token:Z,subject:X0(Z)},X=h1(J.requestId?.trim()||T1()),Y=new AbortController,Q=setTimeout(()=>Y.abort(),this.createTimeoutMs);try{let j=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:J.modelId,repoUrl:J.repoUrl,title:X,...J.branch?.trim()?{branch:J.branch.trim()}:{},...J.organizationId?.trim()?{organizationId:J.organizationId.trim()}:{}}),signal:Y.signal},J.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,$),V=j?.sessionId?.trim();if(!V)throw new L("request_failed","The cloud session service returned no session id.");return{sessionId:V,status:j.status?.trim()||"provisioning",sandboxUrl:j.sandboxUrl?.trim()??"",cleanupAuthToken:$.token}}catch(j){if(Y.signal.aborted||!(j instanceof L)||j instanceof L&&j.code==="request_failed"&&(j.status===void 0||j.status>=500)){let G=J.branch?.trim(),N=(await this.listWithToken(J.organizationId,$,!0).catch(()=>[])).filter((W)=>W.title===X&&W.repoContext.repoUrl===J.repoUrl&&W.metadata.modelId===J.modelId&&(!G||W.repoContext.branch===G));if(N.length>1)throw new L("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let K=N[0];if(K)return{sessionId:K.id,status:K.status,sandboxUrl:K.sandboxUrl,cleanupAuthToken:$.token}}throw j}finally{clearTimeout(Q)}}async waitUntilReady(J,Z,$){Z=AbortSignal.any([Z,AbortSignal.timeout(this.createTimeoutMs)]);let X=await this.options.getAuthToken(),Y=X?{token:X,subject:X0(X)}:void 0;while(!Z.aborted){let Q;try{Q=await this.request(`/api/v1/session/${encodeURIComponent(J)}/status`,{signal:AbortSignal.any([Z,AbortSignal.timeout($0)])},void 0,Y)}catch(V){if(Z.aborted)throw V;if(V instanceof L&&V.code!=="request_failed")throw V;await w0(Z);continue}let j=Q?.status?.trim().toLowerCase();if($?.({phase:Q0(Q?.phase)}),j==="ready"||j==="active")return;if(j==="failed")throw new L("session_failed",Q?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(j!=="provisioning")throw new L("request_failed","The cloud session service returned an unexpected provisioning status.");await w0(Z)}throw Z.reason}async delete(J,Z){await this.deleteWithAuth(J,Z)}async deleteWithAuth(J,Z){await this.request(`/api/v1/session/${encodeURIComponent(J)}`,{method:"DELETE"},void 0,Z)}async updateTitle(J,Z){return await this.request(`/api/v1/session/${encodeURIComponent(J)}`,{method:"PATCH",body:JSON.stringify({title:Z})})}async history(J){let Z=await this.options.getAuthToken();if(!Z?.trim())throw new L("authentication_required","Sign in to Cline to load this session's history.");let $=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(J)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${Z.trim()}`},signal:AbortSignal.timeout($0)});if($.status===404)return null;let X=await $.json().catch(()=>{return});if(!$.ok)throw T0($.status,X,this.appBaseUrl);if(!X||typeof X!=="object"||!("version"in X)||X.version!==1||!("messages"in X)||!Array.isArray(X.messages))throw new L("request_failed","Invalid archived session history");return X.messages}}import{randomUUID as w5}from"node:crypto";import{createSessionId as o2,isHubProtocolCompatible as e2,resolveClineBuildEnv as J5,resolveHubCommandTimeoutMs as Z5}from"@cline/shared";import $5 from"ws";var b0="session_not_found";class u extends Error{sessionId;code="session_not_found";constructor(J,Z){super(Z??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}function k0(J){return J instanceof u||typeof J==="object"&&J!==null&&"code"in J&&J.code==="session_not_found"}import{spawn as D2}from"node:child_process";import{closeSync as M2,mkdirSync as _2,openSync as f2,readFileSync as U2,unlinkSync as H2}from"node:fs";import{basename as O2,dirname as x2,join as P2}from"node:path";import{fileURLToPath as R2}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as w2,isHubDaemonProcess as T2,resolveClineBuildEnv as $1,withResolvedClineBuildEnv as C2}from"@cline/shared";import{createHash as m1,randomBytes as S1}from"node:crypto";import{mkdir as j0,open as h0,readFile as S0,rename as I1,rm as G0,writeFile as p1}from"node:fs/promises";import{dirname as I0,join as N0}from"node:path";import{isHubProtocolCompatible as l1}from"@cline/shared";import{resolveClineDataDir as g,resolveClineDir as t5}from"@cline/shared/storage";var c={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.85-nightly.1790216958",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var u1="CLINE_HUB_DISCOVERY_PATH",c1="CLINE_HUB_BUILD_ID",a1="CLINE_HUB_BUILD_EPOCH_MS",d1=30000,i1=15000,g0=100;function t1(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function r1(J){return m1("sha256").update(J).digest("hex").slice(0,12)}function n1(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(Z){return Z instanceof Error&&"code"in Z?String(Z.code)==="EPERM":!1}}function y0(J){return new Promise((Z)=>setTimeout(Z,J))}function s1(J){return`${J}.lock`}async function o1(J){try{let Z=JSON.parse(await S0(N0(J,"owner.json"),"utf8"));if(typeof Z.pid!=="number"||typeof Z.acquiredAt!=="string")return;return{pid:Z.pid,acquiredAt:Z.acquiredAt}}catch{return}}async function V0(J){await G0(J,{recursive:!0,force:!0}).catch(()=>{return})}function b(){let J=process.env[c1]?.trim();if(J)return J;return"sdk-v1-021410dc1229d9cdaba773c13d4fe387ab11193a9f1c0a87478237d255215bd8".trim()||`source-${String(c.version)}`}function e1(){let J=Number(process.env[a1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1790216983283)?1790216983283:void 0}function a(J,Z=b()){let $=l1(J);if(!$.compatible)return $;let X=J.buildId?.trim();if(!X)return{compatible:!1,reason:"missing_build"};if(X!==Z)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 m0(J){let Z=J?.trim().split(/[-+]/,1)[0];if(!Z)return;let $=Z.split(".").map((X)=>Number(X));if($.length===0||$.some((X)=>!Number.isInteger(X)||X<0))return;return $}function J2(J,Z){for(let $=0;$<Math.max(J.length,Z.length);$++){let X=J[$]??0,Y=Z[$]??0;if(X!==Y)return X<Y?-1:1}return 0}function p0(J,Z){let $=J.buildId?.trim(),X=Z.buildId?.trim();if($&&X&&$===X)return 0;let Y=v0(J.buildEpochMs),Q=v0(Z.buildEpochMs);if(Y!==void 0&&Q!==void 0&&Y!==Q)return Y<Q?-1:1;let j=m0(J.coreVersion),V=m0(Z.coreVersion);if(j&&V){let G=J2(j,V);if(G!==0)return G}if($&&X&&$!==X)return $<X?-1:1;return 0}function l0(){return{buildId:b(),buildEpochMs:e1(),coreVersion:String(c.version)}}function d(J,Z){let $=Z?.self??l0(),X=a(J,$.buildId??"");if(X.compatible)return!0;if(X.reason!=="build_mismatch"&&X.reason!=="missing_build")return!1;return p0($,J)<=0}function u0(J=process.argv[1]?.trim()||process.cwd()){let Z=`hub-${r1(J)}`,$=process.env[u1]?.trim()||N0(g(),"locks","hub","owners",`${t1(Z)}.json`);return{ownerId:Z,discoveryPath:$}}async function C(J){try{let Z=JSON.parse(await S0(J,"utf8"));if(typeof Z.hubId!=="string"||typeof Z.protocolVersion!=="string"||typeof Z.authToken!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string"||typeof Z.startedAt!=="string"||typeof Z.updatedAt!=="string")return;return{hubId:Z.hubId,protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter(($)=>typeof $==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,buildEpochMs:typeof Z.buildEpochMs==="number"?Z.buildEpochMs:void 0,authToken:Z.authToken,host:Z.host,port:Z.port,url:Z.url,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:Z.startedAt,updatedAt:Z.updatedAt}}catch{return}}async function c0(J,Z){await d0(J,async()=>{let $=I0(J);await j0($,{recursive:!0});let X=`${J}.${process.pid}.${S1(6).toString("hex")}.tmp`,Y;try{Y=await h0(X,"wx",384),await Y.writeFile(`${JSON.stringify(Z,null,2)}
|
|
3
|
-
`,{encoding:"utf8"}),await Y.sync(),await Y.close(),Y=void 0,await
|
|
4
|
-
`,"utf8"),await $()}finally{await V0(X)}}}function d0(J,Z){return a0(`${J}.mutation`,"discovery mutation",Z)}function i0(J,Z){return a0(J,"startup",Z)}async function i(J,Z){try{let $=await fetch(Z?.authToken?Z2(J):r0(J),{headers:Z?.authToken?{authorization:`Bearer ${Z.authToken}`}:void 0});if(!$.ok)return;let X=await $.json();if(typeof X.protocolVersion!=="string"||typeof X.host!=="string"||typeof X.port!=="number"||typeof X.url!=="string")return;return{protocolVersion:X.protocolVersion,minClientProtocolVersion:typeof X.minClientProtocolVersion==="string"?X.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof X.maxClientProtocolVersion==="string"?X.maxClientProtocolVersion:void 0,capabilities:Array.isArray(X.capabilities)?X.capabilities.filter((Y)=>typeof Y==="string"):void 0,coreVersion:typeof X.coreVersion==="string"?X.coreVersion:void 0,buildId:typeof X.buildId==="string"?X.buildId:void 0,buildEpochMs:typeof X.buildEpochMs==="number"?X.buildEpochMs:void 0,host:X.host,port:X.port,url:X.url,hubId:typeof X.hubId==="string"?X.hubId:void 0,authToken:typeof X.authToken==="string"?X.authToken:void 0,pid:typeof X.pid==="number"?X.pid:void 0,startedAt:typeof X.startedAt==="string"?X.startedAt:void 0,updatedAt:typeof X.updatedAt==="string"?X.updatedAt:void 0}}catch{return}}function t0(J,Z,$="/hub"){return new URL(`ws://${J}:${Z}${$}`).toString()}function r0(J){let Z=new URL(J);return Z.protocol=Z.protocol==="wss:"?"https:":"http:",Z.pathname="/health",Z.search="",Z.toString()}function Z2(J){let Z=new URL(r0(J));return Z.pathname="/status",Z.toString()}import{CLINE_HUB_DEV_PORT as $2,CLINE_HUB_PORT as X2,resolveClineBuildEnv as Y2}from"@cline/shared";var Q2="CLINE_HUB_HOST",V2="CLINE_HUB_PORT",j2="CLINE_HUB_PATHNAME",G2="127.0.0.1",N2=X2,K2="/hub";function n0(J){return Y2(J)==="development"?$2:N2}function W2(J={}){return(J.env??process.env)[Q2]?.trim()||G2}function F2(J={}){let $=(J.env??process.env)[V2]?.trim();if(!$)return n0(J);let X=Number.parseInt($,10);if(!Number.isInteger(X)||X<1||X>65535)return n0(J);return X}function z2(J={}){return(J.env??process.env)[j2]?.trim()||K2}function s0(J={},Z={}){return{host:J.host??W2(Z),port:J.port??F2(Z),pathname:J.pathname??z2(Z)}}import{join as L2}from"node:path";import{processWorkspaceInfo as J6}from"@cline/shared";import $6 from"simple-git";var q2="shared:cline",B2="CLINE_HUB_DISCOVERY_PATH",A2="hub-production";function y(J=q2){return u0(`${J}@${b()}`)}function t(){return{ownerId:A2,discoveryPath:process.env[B2]?.trim()||L2(g(),"locks","hub","production.json")}}var E2=8000,b2=200,o0=3000,k2=100,h2=[100,250,500,1000,2000],g2="--cline-hub-daemon",y2=3,v2=60000,e0=new Map;function m2(J,Z=Date.now()){let $=e0.get(J);if(!$||Z-$.windowStartedAt>v2)return e0.set(J,{count:1,windowStartedAt:Z}),!0;return $.count+=1,$.count<=y2}function S2(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function I2(){try{let J=P2(g(),"logs","hub-daemon.log");return _2(x2(J),{recursive:!0}),{fd:f2(J,"a"),logPath:J}}catch{return}}function p2(){return $1()==="production"?t():y()}function v(J){return d(J)}function l2(J){try{let Z=JSON.parse(U2(`${J}.superseded`,"utf8"));return{url:typeof Z.url==="string"?Z.url:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0}}catch{return}}function K0(J){try{H2(`${J}.superseded`)}catch{}}function J1(J,Z,$){if(!Z||Z.url!==$)return J;return{...J,authToken:J.authToken??Z.authToken,pid:J.pid??Z.pid}}async function m(J,Z){try{return await i(J,{authToken:Z})}catch{return}}async function Z1(J,Z){let $=Date.now()+Z;while(Date.now()<$){if(!(await m(J))?.url)return!0;await new Promise((Y)=>setTimeout(Y,k2))}return!1}async function F0(J,Z){if(!m2(J.url))return!1;await S(J.url,J.authToken,"retired by newer install").catch(()=>!1),await Y1(J.url,J.authToken).catch(()=>!1);let $=await Z1(J.url,o0);if(!$&&J.pid&&u2(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}$=await Z1(J.url,o0)}if($)await k(Z).catch(()=>{return});return $}function u2(J){try{return process.kill(J,0),!0}catch(Z){return Z?.code==="EPERM"}}async function c2(J){try{return(await z0(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function W0(J,Z){if(v(J))return"reusable";let $=await S(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await c2(J)){if($)await S(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let X=await F0(J,Z);if(!X&&$)await S(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return X?"retired":"failed"}async function a2(J){if($1()!=="production")return;let Z=y();if(Z.discoveryPath===J.discoveryPath)return;let $=await C(Z.discoveryPath);if($?.url)await F0($,Z.discoveryPath);else await k(Z.discoveryPath).catch(()=>{return})}function d2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return R2(new URL(`./entry.${J}`,import.meta.url))}function i2(J,Z){let $=d2(),X=process.execPath?.trim();if(!X)throw Error("unable to resolve runtime executable for hub daemon");let Y=O2(X).toLowerCase().includes("bun"),Q=$.startsWith("/$bunfs/"),j=Y&&$.toLowerCase().endsWith(".ts"),V=Q?[g2]:[...j?["--conditions=development"]:[],$];return{launcher:X,args:[...V,"--cwd",J,...S2(Z),...Z.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...C2(process.env),CLINE_NO_INTERACTIVE:"1",[w2]:"1"}}}function t2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let $="message"in J?J.message:void 0;return typeof $==="string"&&$.includes("ETXTBSY")}function r2(J,Z={}){if(T2())return;let $=i2(J,Z),X=I2();try{D2($.launcher,$.args,{detached:!0,stdio:X?["ignore",X.fd,X.fd]:"ignore",env:$.env,cwd:$.cwd,windowsHide:!0}).unref()}finally{if(X)M2(X.fd)}}async function n2(J,Z={}){for(let $=0;;$++)try{r2(J,Z);return}catch(X){let Y=h2[$];if(!t2(X)||Y===void 0)throw X;await new Promise((Q)=>setTimeout(Q,Y))}}async function s2(J,Z,$={}){let X=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Y=s0($),Q=t0(Y.host,Y.port,Y.pathname),j=(F)=>{if(!X)r(F.url,F.authToken);return F};await a2(J).catch(()=>{return});let V=await C(J.discoveryPath),G=V?.url?void 0:l2(J.discoveryPath),N=!1;if(V?.url){let F=V.authToken;if(!F)N=!0,await F0(V,J.discoveryPath);else{let A=await m(V.url,F);if(A?.url&&v(A)&&await w(A.url,{authToken:F}))return K0(J.discoveryPath),j({url:A.url,authToken:F});if(A?.url){if(await W0({...A,authToken:F},J.discoveryPath)==="deferred_busy"&&await w(A.url,{authToken:F}))return j({url:A.url,authToken:F})}else await k(J.discoveryPath).catch(()=>{return})}}let K=await m(Q);if(K?.url){let F=J1(K,V??G,Q);if(v(K)){let B=[K.authToken,V?.authToken,G?.authToken].filter((_)=>typeof _==="string"&&_.trim().length>0);for(let _ of B){if(!await w(K.url,{authToken:_}))continue;let x={hubId:K.hubId??`repaired-${K.port}`,protocolVersion:K.protocolVersion,minClientProtocolVersion:K.minClientProtocolVersion,maxClientProtocolVersion:K.maxClientProtocolVersion,capabilities:K.capabilities,coreVersion:K.coreVersion,buildId:K.buildId,authToken:_,host:K.host,port:K.port,url:K.url,pid:K.pid??V?.pid??G?.pid,startedAt:K.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await c0(J.discoveryPath,x)}catch{}return K0(J.discoveryPath),j({url:K.url,authToken:_})}throw Error(`A compatible Cline Hub is already running at ${Q}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${N?" 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 A=await W0(F,J.discoveryPath);if(A==="deferred_busy"){for(let B of[F.authToken,V?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await w(K.url,{authToken:B}))return j({url:K.url,authToken:B});if($.allowPortFallback!==!0&&Y.port!==0)throw Error(`An older Cline Hub is running at ${Q} 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(A==="failed"&&$.allowPortFallback!==!0&&Y.port!==0)throw Error(`An incompatible Cline Hub is already running at ${Q} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let q=$.allowPortFallback===!0&&Y.port!==0?{...Y,port:0}:Y;await n2(Z,{...q,manageConnectors:$.manageConnectors});let z=Date.now()+E2;while(Date.now()<z){let F=await C(J.discoveryPath);if(F?.url&&F.authToken){let B=await m(F.url,F.authToken);if(B?.url&&v(B)&&await w(B.url,{authToken:F.authToken}))return K0(J.discoveryPath),j({url:B.url,authToken:F.authToken})}let A=await m(Q);if(A?.url&&!v(A)){let B=J1(A,F??G,Q),M=await W0(B,J.discoveryPath);if(M==="deferred_busy"&&F?.authToken&&await w(A.url,{authToken:F.authToken}))return j({url:A.url,authToken:F.authToken});if(M==="failed"&&$.allowPortFallback!==!0&&Y.port!==0)throw Error(`An incompatible Cline Hub is still running at ${Q} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((B)=>setTimeout(B,b2))}throw Error("Timed out waiting for detached hub startup.")}async function X1(J,Z={}){let $=p2();return await i0($.discoveryPath,async()=>s2($,J,Z))}function X5(){return J5()==="production"?t():y()}function Y5(){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 K1(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((Z)=>Buffer.from(Z))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return K1(J.data);return String(J)}function Q5(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 Q1(J){let Z=J,$=Q5(Z.reason);return new U("hub_connection_closed",Z.code||$?`Hub connection closed (code=${Z.code??0}${$?`, reason=${$}`:""})`:q0,{closeCode:Z.code,closeReason:$||void 0})}function V1(J,Z){if(J instanceof U)return J;if(J instanceof Error)return new U("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new U("hub_connect_failed",J.error.message);let $=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if($)return new U("hub_connect_failed",$);let X=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new U("hub_connect_failed",X?`Failed to connect to hub at ${Z.toString()} (${X} event before socket open).`:`Failed to connect to hub at ${Z.toString()}.`)}var L0="*",n=8000,V5="cline-hub-auth.",W1=new Map,F1=new Set,j5=3000;var q0="Hub connection closed",G5=250,N5=5000,j1=0.5;class U extends Error{code;details;constructor(J,Z,$){super(Z);this.code=J;this.details=$;this.name="HubTransportError"}}function K5(J){return J instanceof U}class B0 extends Error{command;code;constructor(J,Z,$){super($);this.command=J;this.code=Z;this.name="HubCommandError"}}function D0(J,Z={}){let $=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),$)return $;if(Z.skipRegistry)return;let X=M0(J.toString());return X?W1.get(X):void 0}function W5(J){try{let $=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return $==="localhost"||$==="127.0.0.1"||$==="::1"}catch{return!1}}function M0(J){if(!W5(J))return;let Z=new URL(z1(J));return Z.search="",Z.hash="",Z.toString()}function G1(J){let Z=M0(J);return!!Z&&F1.has(Z)}function r(J,Z){let $=M0(J);if($){if(F1.add($),Z?.trim())W1.set($,Z)}return J}class I{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 U("hub_connection_closed",q0);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((Z)=>({...Z})),!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),Z=this.options.authToken?.trim()||D0(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Z&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let $=++this.connectGeneration,X=this.openSocket(J,Z,$),Y;this.connectPromise=X.then(async(j)=>{if(Y=j,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),$!==this.connectGeneration||this.closedByClient){try{j.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let V of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(V));this.reconnectAttempt=0});let Q=this.connectPromise;try{await Q}catch(j){if(this.connectPromise===Q)this.connectPromise=void 0;if(Y&&this.socket===Y){this.lastCloseError=V1(j,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{Y.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw j}}async openSocket(J,Z,$){let X=this.options.resolveConnectionHeaders,Y;if(X){let G;try{Y=await Promise.race([Promise.resolve().then(()=>X()),new Promise((N,K)=>{G=setTimeout(()=>{K(new U("hub_connect_timeout",`Timed out resolving hub connection headers after ${n}ms`))},n)})])}catch(N){let K=N instanceof U?N:new U("hub_connect_failed",N instanceof Error?N.message:String(N));if($===this.connectGeneration)this.lastCloseError=K;throw K}finally{clearTimeout(G)}}if($!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(Y&&Object.keys(Y).some((G)=>G.toLowerCase()==="sec-websocket-protocol")){let G=new U("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if($===this.connectGeneration)this.lastCloseError=G;throw G}let Q=Y?new $5(J.toString(),{headers:{...Y}}):new(Y5())(J.toString(),Z?[`${V5}${Z}`]:void 0);this.socket=Q;let j=!1,V=new Promise((G,N)=>{let K=!1,W=setTimeout(()=>{if(K)return;K=!0,j=!0;let q=new U("hub_connect_timeout",`Timed out connecting to hub after ${n}ms`);if(this.socket===Q)this.lastCloseError=q,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}N(q)},n);Q.addEventListener("open",()=>{if(K)return;K=!0,clearTimeout(W),G()}),Q.addEventListener("error",(q)=>{if(K)return;K=!0,clearTimeout(W);let z=V1(q,J);if(this.socket===Q)this.lastCloseError=z,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;N(z)}),Q.addEventListener("close",(q)=>{if(K)return;K=!0,clearTimeout(W);let z=j?this.lastCloseError:Q1(q);if(this.socket===Q){if(!j)this.lastCloseError=z,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}N(z)})});return Q.addEventListener("message",(G)=>{this.handleFrame(JSON.parse(K1(G)))}),Q.addEventListener("close",(G)=>{if(this.socket!==Q)return;if(!j)this.lastCloseError=Q1(G),this.sawSocketClose=!0;this.registered=!1;for(let N of this.pendingReplies.values())N.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await V,Q}subscribe(J,Z){let $=Z?.sessionId?.trim()||void 0,X={listener:J,sessionId:$};return this.listeners.add(X),this.adjustSubscriptionCount($,1),()=>{if(!this.listeners.delete(X))return;this.adjustSubscriptionCount($,-1)}}async command(J,Z,$,X){let Y=0,Q=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Z,$,X)}catch(j){if(!Q||Y>=1||!await this.recoverLocalHubTransport(j))throw j;Y+=1}}async commandOnce(J,Z,$,X,Y=!0){if(Y)await this.connect();X?.beforeDispatch?.();let Q=o2("hubreq_");X?.onDispatch?.(Q);let j=Z5(J,X?.timeoutMs),V=new Promise((N,K)=>{let W=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Q))return;K(new B0(J,"hub_command_timeout",`Hub command ${J} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${Q}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(Q,{resolve:(q)=>{if(W)clearTimeout(W);N(q)},reject:(q)=>{if(W)clearTimeout(W);K(q)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:Q,clientId:this.clientId,sessionId:$,timeoutMs:j,payload:Z}})}catch(N){throw this.pendingReplies.delete(Q),N}let G=await V;if(!G.ok){if(G.error?.code===b0){let N=$??(typeof Z?.sessionId==="string"?Z.sessionId:void 0);throw new u(N,G.error.message)}throw new B0(J,G.error?.code,G.error?.message??`Hub command ${J} failed`)}return G}async recoverLocalHubTransport(J){if(!G1(this.currentUrl)||!K5(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Z=await N1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Z)return!1;return this.currentUrl=Z,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(G5*2**this.reconnectAttempt,N5),Z=Math.round(J*(1-j1)+Math.random()*J*j1);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Z)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!G1(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await N1({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 U("hub_connection_closed",q0);for(let Z of this.pendingReplies.values())Z.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 U("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Z){let $=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Z)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Z?{sessionId:Z}:{},...$!==void 0?{sinceSequence:$}:{}})}adjustSubscriptionCount(J,Z){let $=this.subscriptionKeyForSessionId(J),X=(this.subscriptionCounts.get($)??0)+Z;if(X<=0){if(this.subscriptionCounts.delete($),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Z<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set($,X),Z>0&&X===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??L0}subscriptionSessionIdFromKey(J){return J===L0?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Z=J.envelope.requestId;if(!Z)return;let $=this.pendingReplies.get(Z);if(!$)return;this.pendingReplies.delete(Z),$.resolve(J.envelope);return}case"event":{let Z=J.envelope.sequence;if(typeof Z==="number"){let $=J.envelope.sessionId?.trim();for(let X of[L0,$]){if(!X||!this.subscriptionCounts.has(X))continue;let Y=this.lastEventSequenceByKey.get(X)??0;if(Z>Y)this.lastEventSequenceByKey.set(X,Z)}}for(let $ of this.listeners){if($.sessionId&&$.sessionId!==J.envelope.sessionId?.trim())continue;$.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function z1(J){let Z=new URL(J);if(Z.protocol==="http:")Z.protocol="ws:";else if(Z.protocol==="https:")Z.protocol="wss:";return Z.toString()}async function w(J,Z){let $=new I({url:J,authToken:Z?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{return await $.connect(),!0}catch{return!1}finally{$.close()}}async function A0(J,Z){let $=z1(J),X=await i($,{authToken:Z?.authToken});if(!X)return{status:"unreachable",url:$};if(Z?.requireCurrentBuild){let Y=b(),Q=a(X,Y);if(!Q.compatible&&!d(X))return{status:Q.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:$}}else if(!e2(X).compatible)return{status:"protocol_mismatch",url:$};if(Z?.verifyConnection===!0&&!await w($,{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,authToken:Z.authToken}))return{status:"unreachable",url:$};return{status:"compatible",url:$}}function F5(J){let Z=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],$=0,X=new Set;for(let Y of Z){if(!Y||typeof Y!=="object")continue;let Q=Y.participants;if(!Array.isArray(Q)||Q.length===0)continue;$+=1;for(let j of Q){let V=j&&typeof j==="object"?j.clientId:void 0;if(typeof V==="string"&&V.trim())X.add(V)}}return{activeSessionCount:$,participantClientCount:X.size}}async function z0(J,Z,$){let X=new I({url:J,authToken:Z,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{let Y=await X.command("session.list",{limit:500},void 0,{timeoutMs:j5});return F5(Y.payload)}finally{await X.dispose().catch(()=>{return})}}async function z5(J,Z,$){try{return(await z0(J,Z,$)).activeSessionCount===0}catch{return!1}}async function L5(J,Z){let $=`${J.discoveryPath}.superseded`,X=await C($);if(!X?.url||!X.authToken)return;let Y=await A0(X.url,{authToken:X.authToken});if(Y.status!=="compatible")return;if(await z5(Y.url,X.authToken,Z))return;return r(Y.url,X.authToken)}async function q5(J={}){if(J.endpoint?.trim()){let Y=await A0(J.endpoint);return Y.status==="compatible"?Y.url:void 0}let Z=X5(),$=await C(Z.discoveryPath);if(!$?.url)return await L5(Z,J);let X=await A0($.url,{authToken:$.authToken,requireCurrentBuild:!0});if(X.status==="compatible")return r(X.url,$.authToken);if(X.status==="protocol_mismatch")await k(Z.discoveryPath).catch(()=>{return});return}async function N1(J={}){let Z=await q5(J);if(Z&&await w(Z,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Z;if(J.endpoint?.trim())return;try{return(await X1(J.workspaceRoot??process.cwd())).url}catch{return}}async function S(J,Z,$,X){let Y=new URL(J),Q=Z?.trim()||D0(Y);if(Y.protocol==="ws:")Y.protocol="http:";else if(Y.protocol==="wss:")Y.protocol="https:";if(Y.pathname="/drain",Y.hash="",$)Y.searchParams.set("reason",$);if(X?.off)Y.searchParams.set("off","1");return(await fetch(Y,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function Y1(J,Z){let $=new URL(J),X=Z?.trim()||D0($);if($.protocol==="ws:")$.protocol="http:";else if($.protocol==="wss:")$.protocol="https:";return $.pathname="/shutdown",$.hash="",(await fetch($,{method:"POST",headers:X?{authorization:`Bearer ${X}`}:void 0})).ok}import{formatDisplayUserInput as L1}from"@cline/shared";var B5=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function A5(J){switch(J){case"user":case"assistant":case"tool":case"system":case"status":case"error":return J;default:return"assistant"}}function D5(J){return J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}function M5(J){let Z=J?.userRunSpan;return typeof Z==="number"&&Number.isInteger(Z)&&Z>=0?Z:void 0}function _5(J){if(typeof J.content==="string")return{hasAttachment:!1,text:J.content};if(!Array.isArray(J.content))return{hasAttachment:!1,text:"unknown"};let Z=!1,$=!1,X=[];for(let Y of J.content){if(!Y||typeof Y!=="object"||Array.isArray(Y))continue;let Q=Y;if(Q.type==="text"&&typeof Q.text==="string")X.push(Q.text);else if(Q.type==="tool_result"||Q.type==="tool-result")$=!0;else if(Q.type==="file"||Q.type==="image")Z=!0}return{hasAttachment:Z&&!$,text:X.join(`
|
|
5
|
-
`)}}function
|
|
1
|
+
import{randomUUID as C1}from"node:crypto";import{decodeJwtPayload as E1}from"@cline/shared";var b1=610000,k1=3000,$0=15000,h1="CLOUD_SESSION_ERROR:",C0="__cline_create_request__:";function E0(J){return(J.trim().split(`
|
|
2
|
+
`)[0]??"").trim().slice(0,72)}class L extends Error{code;detail;connectUrl;status;constructor(J,Z,$,X){super(`${h1}${JSON.stringify({code:J,message:Z,connectUrl:$})}`);this.code=J;this.detail=Z;this.connectUrl=$;this.status=X;this.name="CloudSessionError"}}function Y0(J){let Z=J.length;while(Z>0&&J[Z-1]==="/")Z--;return J.slice(0,Z)}function g1(J){return`${C0}${J}`.slice(0,255)}function R0(J){return J?.startsWith(C0)===!0}function Q0(J){switch(J){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return J;default:return}}function X0(J){let Z=E1(J.replace(/^workos:/,""));return typeof Z?.sub==="string"&&Z.sub.trim()?Z.sub.trim():void 0}function w0(J){return new Promise((Z,$)=>{if(J.aborted){$(J.reason);return}let X=()=>{clearTimeout(Y),$(J.reason)},Y=setTimeout(()=>{J.removeEventListener("abort",X),Z()},k1);J.addEventListener("abort",X,{once:!0})})}function y1(J,Z){if(J&&typeof J==="object"){let $=J.error;if(typeof $==="string"&&$.trim())return $.trim()}return Z}function T0(J,Z,$,X){let Y=y1(Z,`Cloud session request failed (${J})`);if(J===401)return new L("authentication_required",Y);if(J===404)return new L("session_not_found",Y);if(J===410)return new L("session_expired",Y);if(J===412)return new L("github_not_connected",Y,X??`${Y0($)}/dashboard/integrations`);if(J===403&&Y.trim().toLowerCase()==="forbidden")return new L("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,J);return new L("request_failed",Y,void 0,J)}class v1{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;constructor(J){this.options=J;this.apiBaseUrl=Y0(J.apiBaseUrl),this.appBaseUrl=Y0(J.appBaseUrl),this.fetchImpl=J.fetch??fetch,this.createTimeoutMs=J.createTimeoutMs??b1}async request(J,Z={},$,X){let Y=!1;while(!0){let Q=typeof X==="string"?X:X?.token??await this.options.getAuthToken();if(!Q?.trim())throw new L("authentication_required","Sign in to Cline before starting a cloud session.");let j=await this.fetchImpl(`${this.apiBaseUrl}${J}`,{...Z,signal:Z.signal??AbortSignal.timeout($0),headers:{Accept:"application/json",Authorization:`Bearer ${Q.trim()}`,...Z.body?{"Content-Type":"application/json"}:{},...Z.headers}}),V=j.status===204?void 0:await j.json().catch(()=>{return});if(!j.ok){if(j.status===401&&typeof X==="object"&&!Y&&await this.refreshCreationAuth(X)){Y=!0;continue}throw T0(j.status,V,this.appBaseUrl,$)}return V?.data}}async refreshCreationAuth(J){if(!J.subject)return!1;let Z=(await this.options.getAuthToken())?.trim();if(!Z||Z===J.token||X0(Z)!==J.subject)return!1;return J.token=Z,!0}async list(J){return await this.listWithToken(J)}async listWithToken(J,Z,$=!1){let X=J?.trim()?`?organizationId=${encodeURIComponent(J.trim())}`:"";return(await this.request(`/api/v1/session${X}`,{},void 0,Z)??[]).flatMap((Q)=>{if(!Q||typeof Q!=="object"||typeof Q.id!=="string")return[];return[{...Q,title:!$&&R0(Q.title)?void 0:Q.title,repoContext:Q.repoContext&&typeof Q.repoContext==="object"?Q.repoContext:{},metadata:{...Q.metadata&&typeof Q.metadata==="object"?Q.metadata:{},...!$&&R0(Q.title)?{createRequestTitle:Q.title}:{}}}]})}async listRepositories(J){let Z=J?.trim(),$=Z?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,X=Z?`/api/v1/organizations/${encodeURIComponent(Z)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let Y=await this.request(X)??[];return{connected:!0,connectUrl:$,repositories:Y.flatMap((Q)=>{let j=Number(Q.id),V=String(Q.html_url??Q.clone_url??"").trim();if(!Number.isSafeInteger(j)||j<=0||!V)return[];let G=String(Q.name??"").trim();return[{id:j,name:G,fullName:String(Q.full_name??(G||V)).trim(),url:V,defaultBranch:String(Q.default_branch??"").trim()}]})}}catch(Y){if(Y instanceof L&&Y.code==="session_not_found")return{connected:!1,connectUrl:$,repositories:[]};throw Y}}async listBranches(J,Z,$={}){if(!Number.isSafeInteger(J)||J<=0)throw new L("request_failed","Select a GitHub repository before loading branches.");let X=Z?.trim(),Y=X?`/api/v1/organizations/${encodeURIComponent(X)}/integrations/github/repositories/${J}/branches`:`/api/v1/integrations/github/repositories/${J}/branches`,Q=new URLSearchParams,j=$.query?.trim(),V=$.cursor?.trim();if(j)Q.set("query",j);if(V)Q.set("cursor",V);let G=Q.size>0?`${Y}?${Q}`:Y;try{let N=await this.request(G),K=Array.isArray(N)?N:Array.isArray(N?.items)?N.items:[],W=j?.toLowerCase();return{available:!0,branches:K.flatMap((q)=>{let z=String(q.name??"").trim();return z&&(!Array.isArray(N)||!W||z.toLowerCase().includes(W))?[z]:[]}),nextToken:Array.isArray(N)?"":String(N?.nextToken??"").trim()}}catch(N){if(N instanceof L&&N.code==="session_not_found")return{available:!1,branches:[]};throw N}}async status(J,Z={}){return await this.request(`/api/v1/session/${encodeURIComponent(J)}/status`,{signal:Z.signal},void 0,Z.authToken)}async create(J){let Z=(await this.options.getAuthToken())?.trim();if(!Z)throw new L("authentication_required","Sign in to Cline before starting a cloud session.");let $={token:Z,subject:X0(Z)},X=g1(J.requestId?.trim()||C1()),Y=new AbortController,Q=setTimeout(()=>Y.abort(),this.createTimeoutMs);try{let j=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:J.modelId,repoUrl:J.repoUrl,title:X,...J.branch?.trim()?{branch:J.branch.trim()}:{},...J.organizationId?.trim()?{organizationId:J.organizationId.trim()}:{}}),signal:Y.signal},J.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,$),V=j?.sessionId?.trim();if(!V)throw new L("request_failed","The cloud session service returned no session id.");return{sessionId:V,status:j.status?.trim()||"provisioning",sandboxUrl:j.sandboxUrl?.trim()??"",cleanupAuthToken:$.token}}catch(j){if(Y.signal.aborted||!(j instanceof L)||j instanceof L&&j.code==="request_failed"&&(j.status===void 0||j.status>=500)){let G=J.branch?.trim(),N=(await this.listWithToken(J.organizationId,$,!0).catch(()=>[])).filter((W)=>W.title===X&&W.repoContext.repoUrl===J.repoUrl&&W.metadata.modelId===J.modelId&&(!G||W.repoContext.branch===G));if(N.length>1)throw new L("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let K=N[0];if(K)return{sessionId:K.id,status:K.status,sandboxUrl:K.sandboxUrl,cleanupAuthToken:$.token}}throw j}finally{clearTimeout(Q)}}async waitUntilReady(J,Z,$){Z=AbortSignal.any([Z,AbortSignal.timeout(this.createTimeoutMs)]);let X=await this.options.getAuthToken(),Y=X?{token:X,subject:X0(X)}:void 0;while(!Z.aborted){let Q;try{Q=await this.request(`/api/v1/session/${encodeURIComponent(J)}/status`,{signal:AbortSignal.any([Z,AbortSignal.timeout($0)])},void 0,Y)}catch(V){if(Z.aborted)throw V;if(V instanceof L&&V.code!=="request_failed")throw V;await w0(Z);continue}let j=Q?.status?.trim().toLowerCase();if($?.({phase:Q0(Q?.phase)}),j==="ready"||j==="active")return;if(j==="failed")throw new L("session_failed",Q?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(j!=="provisioning")throw new L("request_failed","The cloud session service returned an unexpected provisioning status.");await w0(Z)}throw Z.reason}async delete(J,Z){await this.deleteWithAuth(J,Z)}async deleteWithAuth(J,Z){await this.request(`/api/v1/session/${encodeURIComponent(J)}`,{method:"DELETE"},void 0,Z)}async updateTitle(J,Z){return await this.request(`/api/v1/session/${encodeURIComponent(J)}`,{method:"PATCH",body:JSON.stringify({title:Z})})}async history(J){let Z=await this.options.getAuthToken();if(!Z?.trim())throw new L("authentication_required","Sign in to Cline to load this session's history.");let $=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(J)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${Z.trim()}`},signal:AbortSignal.timeout($0)});if($.status===404)return null;let X=await $.json().catch(()=>{return});if(!$.ok)throw T0($.status,X,this.appBaseUrl);if(!X||typeof X!=="object"||!("version"in X)||X.version!==1||!("messages"in X)||!Array.isArray(X.messages))throw new L("request_failed","Invalid archived session history");return X.messages}}import{randomUUID as w6}from"node:crypto";import{createSessionId as o2,isHubProtocolCompatible as e2,resolveClineBuildEnv as J6,resolveHubCommandTimeoutMs as Z6}from"@cline/shared";import $6 from"ws";var b0="session_not_found";class u extends Error{sessionId;code="session_not_found";constructor(J,Z){super(Z??(J?`session not found: ${J}`:"session not found"));this.sessionId=J;this.name="SessionNotFoundError"}}function k0(J){return J instanceof u||typeof J==="object"&&J!==null&&"code"in J&&J.code==="session_not_found"}import{spawn as M2}from"node:child_process";import{closeSync as _2,mkdirSync as f2,openSync as U2,readFileSync as H2,unlinkSync as O2}from"node:fs";import{basename as x2,dirname as P2,join as R2}from"node:path";import{fileURLToPath as w2}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as T2,isHubDaemonProcess as C2,resolveClineBuildEnv as X1,withResolvedClineBuildEnv as E2}from"@cline/shared";import{createHash as S1,randomBytes as I1}from"node:crypto";import{mkdir as j0,open as h0,readFile as S0,rename as p1,rm as G0,writeFile as l1}from"node:fs/promises";import{dirname as I0,join as N0}from"node:path";import{isHubProtocolCompatible as u1}from"@cline/shared";import{resolveClineDataDir as g,resolveClineDir as t6}from"@cline/shared/storage";var c={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.86",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var c1="CLINE_HUB_DISCOVERY_PATH",a1="CLINE_HUB_BUILD_ID",d1="CLINE_HUB_BUILD_EPOCH_MS",i1=30000,t1=15000,g0=100;function r1(J){return J.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function n1(J){return S1("sha256").update(J).digest("hex").slice(0,12)}function s1(J){if(!Number.isInteger(J)||!J||J<=0)return!1;try{return process.kill(J,0),!0}catch(Z){return Z instanceof Error&&"code"in Z?String(Z.code)==="EPERM":!1}}function y0(J){return new Promise((Z)=>setTimeout(Z,J))}function o1(J){return`${J}.lock`}async function e1(J){try{let Z=JSON.parse(await S0(N0(J,"owner.json"),"utf8"));if(typeof Z.pid!=="number"||typeof Z.acquiredAt!=="string")return;return{pid:Z.pid,acquiredAt:Z.acquiredAt}}catch{return}}async function V0(J){await G0(J,{recursive:!0,force:!0}).catch(()=>{return})}function b(){let J=process.env[a1]?.trim();if(J)return J;return"sdk-v1-0576301606d0c4c3dc8977d928d8eb0e21124cc056aad08ebb46ec27efc2c890".trim()||`source-${String(c.version)}`}function J2(){let J=Number(process.env[d1]);if(Number.isFinite(J)&&J>0)return J;return Number.isFinite(1790228567447)?1790228567447:void 0}function a(J,Z=b()){let $=u1(J);if(!$.compatible)return $;let X=J.buildId?.trim();if(!X)return{compatible:!1,reason:"missing_build"};if(X!==Z)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 m0(J){let Z=J?.trim().split(/[-+]/,1)[0];if(!Z)return;let $=Z.split(".").map((X)=>Number(X));if($.length===0||$.some((X)=>!Number.isInteger(X)||X<0))return;return $}function Z2(J,Z){for(let $=0;$<Math.max(J.length,Z.length);$++){let X=J[$]??0,Y=Z[$]??0;if(X!==Y)return X<Y?-1:1}return 0}function p0(J,Z){let $=J.buildId?.trim(),X=Z.buildId?.trim();if($&&X&&$===X)return 0;let Y=v0(J.buildEpochMs),Q=v0(Z.buildEpochMs);if(Y!==void 0&&Q!==void 0&&Y!==Q)return Y<Q?-1:1;let j=m0(J.coreVersion),V=m0(Z.coreVersion);if(j&&V){let G=Z2(j,V);if(G!==0)return G}if($&&X&&$!==X)return $<X?-1:1;return 0}function l0(){return{buildId:b(),buildEpochMs:J2(),coreVersion:String(c.version)}}function d(J,Z){let $=Z?.self??l0(),X=a(J,$.buildId??"");if(X.compatible)return!0;if(X.reason!=="build_mismatch"&&X.reason!=="missing_build")return!1;return p0($,J)<=0}function u0(J=process.argv[1]?.trim()||process.cwd()){let Z=`hub-${n1(J)}`,$=process.env[c1]?.trim()||N0(g(),"locks","hub","owners",`${r1(Z)}.json`);return{ownerId:Z,discoveryPath:$}}async function C(J){try{let Z=JSON.parse(await S0(J,"utf8"));if(typeof Z.hubId!=="string"||typeof Z.protocolVersion!=="string"||typeof Z.authToken!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string"||typeof Z.startedAt!=="string"||typeof Z.updatedAt!=="string")return;return{hubId:Z.hubId,protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter(($)=>typeof $==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,buildEpochMs:typeof Z.buildEpochMs==="number"?Z.buildEpochMs:void 0,authToken:Z.authToken,host:Z.host,port:Z.port,url:Z.url,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:Z.startedAt,updatedAt:Z.updatedAt}}catch{return}}async function c0(J,Z){await d0(J,async()=>{let $=I0(J);await j0($,{recursive:!0});let X=`${J}.${process.pid}.${I1(6).toString("hex")}.tmp`,Y;try{Y=await h0(X,"wx",384),await Y.writeFile(`${JSON.stringify(Z,null,2)}
|
|
3
|
+
`,{encoding:"utf8"}),await Y.sync(),await Y.close(),Y=void 0,await p1(X,J);let Q;try{Q=await h0($,"r"),await Q.sync()}catch{}finally{await Q?.close().catch(()=>{return})}}catch(Q){throw await Y?.close().catch(()=>{return}),await G0(X,{force:!0}).catch(()=>{return}),Q}})}async function k(J){await d0(J,async()=>{await G0(J,{force:!0}).catch(()=>{return})})}async function a0(J,Z,$){let X=o1(J);await j0(I0(X),{recursive:!0});let Y=Date.now()+t1;while(!0){try{await j0(X,{recursive:!1})}catch(Q){if((Q instanceof Error&&"code"in Q?String(Q.code):"")!=="EEXIST")throw Q;let V=await e1(X);if(!V){if(Date.now()>=Y){await V0(X);continue}await y0(g0);continue}let G=Date.now()-Date.parse(V.acquiredAt);if(!s1(V.pid)||G>i1){await V0(X);continue}if(Date.now()>=Y)throw Error(`Timed out waiting for hub ${Z} lock ${X}`);await y0(g0);continue}try{return await l1(N0(X,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
4
|
+
`,"utf8"),await $()}finally{await V0(X)}}}function d0(J,Z){return a0(`${J}.mutation`,"discovery mutation",Z)}function i0(J,Z){return a0(J,"startup",Z)}async function i(J,Z){try{let $=await fetch(Z?.authToken?$2(J):r0(J),{headers:Z?.authToken?{authorization:`Bearer ${Z.authToken}`}:void 0});if(!$.ok)return;let X=await $.json();if(typeof X.protocolVersion!=="string"||typeof X.host!=="string"||typeof X.port!=="number"||typeof X.url!=="string")return;return{protocolVersion:X.protocolVersion,minClientProtocolVersion:typeof X.minClientProtocolVersion==="string"?X.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof X.maxClientProtocolVersion==="string"?X.maxClientProtocolVersion:void 0,capabilities:Array.isArray(X.capabilities)?X.capabilities.filter((Y)=>typeof Y==="string"):void 0,coreVersion:typeof X.coreVersion==="string"?X.coreVersion:void 0,buildId:typeof X.buildId==="string"?X.buildId:void 0,buildEpochMs:typeof X.buildEpochMs==="number"?X.buildEpochMs:void 0,host:X.host,port:X.port,url:X.url,hubId:typeof X.hubId==="string"?X.hubId:void 0,authToken:typeof X.authToken==="string"?X.authToken:void 0,pid:typeof X.pid==="number"?X.pid:void 0,startedAt:typeof X.startedAt==="string"?X.startedAt:void 0,updatedAt:typeof X.updatedAt==="string"?X.updatedAt:void 0}}catch{return}}function t0(J,Z,$="/hub"){return new URL(`ws://${J}:${Z}${$}`).toString()}function r0(J){let Z=new URL(J);return Z.protocol=Z.protocol==="wss:"?"https:":"http:",Z.pathname="/health",Z.search="",Z.toString()}function $2(J){let Z=new URL(r0(J));return Z.pathname="/status",Z.toString()}import{CLINE_HUB_DEV_PORT as X2,CLINE_HUB_PORT as Y2,resolveClineBuildEnv as Q2}from"@cline/shared";var V2="CLINE_HUB_HOST",j2="CLINE_HUB_PORT",G2="CLINE_HUB_PATHNAME",N2="127.0.0.1",K2=Y2,W2="/hub";function n0(J){return Q2(J)==="development"?X2:K2}function F2(J={}){return(J.env??process.env)[V2]?.trim()||N2}function z2(J={}){let $=(J.env??process.env)[j2]?.trim();if(!$)return n0(J);let X=Number.parseInt($,10);if(!Number.isInteger(X)||X<1||X>65535)return n0(J);return X}function L2(J={}){return(J.env??process.env)[G2]?.trim()||W2}function s0(J={},Z={}){return{host:J.host??F2(Z),port:J.port??z2(Z),pathname:J.pathname??L2(Z)}}import{join as q2}from"node:path";import{processWorkspaceInfo as J4}from"@cline/shared";import $4 from"simple-git";var B2="shared:cline",A2="CLINE_HUB_DISCOVERY_PATH",D2="hub-production";function y(J=B2){return u0(`${J}@${b()}`)}function t(){return{ownerId:D2,discoveryPath:process.env[A2]?.trim()||q2(g(),"locks","hub","production.json")}}var o0=15000,b2=200,e0=3000,k2=100,h2=[100,250,500,1000,2000],g2="--cline-hub-daemon",y2=3,v2=60000,J1=new Map;function m2(J,Z=Date.now()){let $=J1.get(J);if(!$||Z-$.windowStartedAt>v2)return J1.set(J,{count:1,windowStartedAt:Z}),!0;return $.count+=1,$.count<=y2}function S2(J){return[...J.host?["--host",J.host]:[],...typeof J.port==="number"?["--port",String(J.port)]:[],...J.pathname?["--pathname",J.pathname]:[]]}function I2(){try{let J=R2(g(),"logs","hub-daemon.log");return f2(P2(J),{recursive:!0}),{fd:U2(J,"a"),logPath:J}}catch{return}}function p2(){return X1()==="production"?t():y()}function v(J){return d(J)}function l2(J){try{let Z=JSON.parse(H2(`${J}.superseded`,"utf8"));return{url:typeof Z.url==="string"?Z.url:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0}}catch{return}}function K0(J){try{O2(`${J}.superseded`)}catch{}}function Z1(J,Z,$){if(!Z||Z.url!==$)return J;return{...J,authToken:J.authToken??Z.authToken,pid:J.pid??Z.pid}}async function m(J,Z){try{return await i(J,{authToken:Z})}catch{return}}async function $1(J,Z){let $=Date.now()+Z;while(Date.now()<$){if(!(await m(J))?.url)return!0;await new Promise((Y)=>setTimeout(Y,k2))}return!1}async function F0(J,Z){if(!m2(J.url))return!1;await S(J.url,J.authToken,"retired by newer install").catch(()=>!1),await Q1(J.url,J.authToken).catch(()=>!1);let $=await $1(J.url,e0);if(!$&&J.pid&&u2(J.pid)){try{process.kill(J.pid,"SIGTERM")}catch{}$=await $1(J.url,e0)}if($)await k(Z).catch(()=>{return});return $}function u2(J){try{return process.kill(J,0),!0}catch(Z){return Z?.code==="EPERM"}}async function c2(J){try{return(await z0(J.url,J.authToken)).activeSessionCount>0}catch{return!1}}async function W0(J,Z){if(v(J))return"reusable";let $=await S(J.url,J.authToken,"retired by newer install").catch(()=>!1);if(await c2(J)){if($)await S(J.url,J.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let X=await F0(J,Z);if(!X&&$)await S(J.url,J.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return X?"retired":"failed"}async function a2(J){if(X1()!=="production")return;let Z=y();if(Z.discoveryPath===J.discoveryPath)return;let $=await C(Z.discoveryPath);if($?.url)await F0($,Z.discoveryPath);else await k(Z.discoveryPath).catch(()=>{return})}function d2(){let J=import.meta.url.endsWith(".ts")?"ts":"js";return w2(new URL(`./entry.${J}`,import.meta.url))}function i2(J,Z){let $=d2(),X=process.execPath?.trim();if(!X)throw Error("unable to resolve runtime executable for hub daemon");let Y=x2(X).toLowerCase().includes("bun"),Q=$.startsWith("/$bunfs/"),j=Y&&$.toLowerCase().endsWith(".ts"),V=Q?[g2]:[...j?["--conditions=development"]:[],$];return{launcher:X,args:[...V,"--cwd",J,...S2(Z),...Z.manageConnectors===!1?["--no-connectors"]:[]],cwd:J,env:{...E2(process.env),CLINE_NO_INTERACTIVE:"1",[T2]:"1"}}}function t2(J){if(!J||typeof J!=="object")return!1;if(("code"in J?J.code:void 0)==="ETXTBSY")return!0;let $="message"in J?J.message:void 0;return typeof $==="string"&&$.includes("ETXTBSY")}function r2(J,Z={}){if(C2())return;let $=i2(J,Z),X=I2();try{M2($.launcher,$.args,{detached:!0,stdio:X?["ignore",X.fd,X.fd]:"ignore",env:$.env,cwd:$.cwd,windowsHide:!0}).unref()}finally{if(X)_2(X.fd)}}async function n2(J,Z={}){for(let $=0;;$++)try{r2(J,Z);return}catch(X){let Y=h2[$];if(!t2(X)||Y===void 0)throw X;await new Promise((Q)=>setTimeout(Q,Y))}}async function s2(J,Z,$={}){let X=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Y=s0($),Q=t0(Y.host,Y.port,Y.pathname),j=(F)=>{if(!X)r(F.url,F.authToken);return F};await a2(J).catch(()=>{return});let V=await C(J.discoveryPath),G=V?.url?void 0:l2(J.discoveryPath),N=!1;if(V?.url){let F=V.authToken;if(!F)N=!0,await F0(V,J.discoveryPath);else{let A=await m(V.url,F);if(A?.url&&v(A)&&await w(A.url,{authToken:F}))return K0(J.discoveryPath),j({url:A.url,authToken:F});if(A?.url){if(await W0({...A,authToken:F},J.discoveryPath)==="deferred_busy"&&await w(A.url,{authToken:F}))return j({url:A.url,authToken:F})}else await k(J.discoveryPath).catch(()=>{return})}}let K=await m(Q);if(K?.url){let F=Z1(K,V??G,Q);if(v(K)){let B=[K.authToken,V?.authToken,G?.authToken].filter((_)=>typeof _==="string"&&_.trim().length>0);for(let _ of B){if(!await w(K.url,{authToken:_}))continue;let x={hubId:K.hubId??`repaired-${K.port}`,protocolVersion:K.protocolVersion,minClientProtocolVersion:K.minClientProtocolVersion,maxClientProtocolVersion:K.maxClientProtocolVersion,capabilities:K.capabilities,coreVersion:K.coreVersion,buildId:K.buildId,authToken:_,host:K.host,port:K.port,url:K.url,pid:K.pid??V?.pid??G?.pid,startedAt:K.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await c0(J.discoveryPath,x)}catch{}return K0(J.discoveryPath),j({url:K.url,authToken:_})}throw Error(`A compatible Cline Hub is already running at ${Q}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${N?" 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 A=await W0(F,J.discoveryPath);if(A==="deferred_busy"){for(let B of[F.authToken,V?.authToken].filter((M)=>typeof M==="string"&&M.trim().length>0))if(await w(K.url,{authToken:B}))return j({url:K.url,authToken:B});if($.allowPortFallback!==!0&&Y.port!==0)throw Error(`An older Cline Hub is running at ${Q} 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(A==="failed"&&$.allowPortFallback!==!0&&Y.port!==0)throw Error(`An incompatible Cline Hub is already running at ${Q} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let q=$.allowPortFallback===!0&&Y.port!==0?{...Y,port:0}:Y;await n2(Z,{...q,manageConnectors:$.manageConnectors});let z=Date.now()+o0;while(Date.now()<z){let F=await C(J.discoveryPath);if(F?.url&&F.authToken){let B=await m(F.url,F.authToken);if(B?.url&&v(B)&&await w(B.url,{authToken:F.authToken}))return K0(J.discoveryPath),j({url:B.url,authToken:F.authToken})}let A=await m(Q);if(A?.url&&!v(A)){let B=Z1(A,F??G,Q),M=await W0(B,J.discoveryPath);if(M==="deferred_busy"&&F?.authToken&&await w(A.url,{authToken:F.authToken}))return j({url:A.url,authToken:F.authToken});if(M==="failed"&&$.allowPortFallback!==!0&&Y.port!==0)throw Error(`An incompatible Cline Hub is still running at ${Q} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((B)=>setTimeout(B,b2))}throw Error(`Timed out after ${o0}ms waiting for detached hub startup.`)}async function Y1(J,Z={}){let $=p2();return await i0($.discoveryPath,async()=>s2($,J,Z))}function X6(){return J6()==="production"?t():y()}function Y6(){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 W1(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((Z)=>Buffer.from(Z))).toString();if(J&&typeof J==="object"&&"data"in J&&typeof J.data<"u")return W1(J.data);return String(J)}function Q6(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 V1(J){let Z=J,$=Q6(Z.reason);return new U("hub_connection_closed",Z.code||$?`Hub connection closed (code=${Z.code??0}${$?`, reason=${$}`:""})`:q0,{closeCode:Z.code,closeReason:$||void 0})}function j1(J,Z){if(J instanceof U)return J;if(J instanceof Error)return new U("hub_connect_failed",J.message);if(J&&typeof J==="object"&&"error"in J&&J.error instanceof Error)return new U("hub_connect_failed",J.error.message);let $=J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"?J.message.trim():"";if($)return new U("hub_connect_failed",$);let X=J&&typeof J==="object"&&"type"in J&&typeof J.type==="string"?J.type.trim():"";return new U("hub_connect_failed",X?`Failed to connect to hub at ${Z.toString()} (${X} event before socket open).`:`Failed to connect to hub at ${Z.toString()}.`)}var L0="*",n=8000,V6="cline-hub-auth.",F1=new Map,z1=new Set,j6=3000;var q0="Hub connection closed",G6=250,N6=5000,G1=0.5;class U extends Error{code;details;constructor(J,Z,$){super(Z);this.code=J;this.details=$;this.name="HubTransportError"}}function K6(J){return J instanceof U}class B0 extends Error{command;code;constructor(J,Z,$){super($);this.command=J;this.code=Z;this.name="HubCommandError"}}function D0(J,Z={}){let $=J.searchParams.get("authToken")?.trim();if(J.searchParams.delete("authToken"),$)return $;if(Z.skipRegistry)return;let X=M0(J.toString());return X?F1.get(X):void 0}function W6(J){try{let $=new URL(J).hostname.toLowerCase().replace(/^\[|\]$/g,"");return $==="localhost"||$==="127.0.0.1"||$==="::1"}catch{return!1}}function M0(J){if(!W6(J))return;let Z=new URL(L1(J));return Z.search="",Z.hash="",Z.toString()}function N1(J){let Z=M0(J);return!!Z&&z1.has(Z)}function r(J,Z){let $=M0(J);if($){if(z1.add($),Z?.trim())F1.set($,Z)}return J}class I{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 U("hub_connection_closed",q0);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((Z)=>({...Z})),!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),Z=this.options.authToken?.trim()||D0(J,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(J.hash="",Z&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let $=++this.connectGeneration,X=this.openSocket(J,Z,$),Y;this.connectPromise=X.then(async(j)=>{if(Y=j,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),$!==this.connectGeneration||this.closedByClient){try{j.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let V of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(V));this.reconnectAttempt=0});let Q=this.connectPromise;try{await Q}catch(j){if(this.connectPromise===Q)this.connectPromise=void 0;if(Y&&this.socket===Y){this.lastCloseError=j1(j,J),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{Y.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw j}}async openSocket(J,Z,$){let X=this.options.resolveConnectionHeaders,Y;if(X){let G;try{Y=await Promise.race([Promise.resolve().then(()=>X()),new Promise((N,K)=>{G=setTimeout(()=>{K(new U("hub_connect_timeout",`Timed out resolving hub connection headers after ${n}ms`))},n)})])}catch(N){let K=N instanceof U?N:new U("hub_connect_failed",N instanceof Error?N.message:String(N));if($===this.connectGeneration)this.lastCloseError=K;throw K}finally{clearTimeout(G)}}if($!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(Y&&Object.keys(Y).some((G)=>G.toLowerCase()==="sec-websocket-protocol")){let G=new U("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if($===this.connectGeneration)this.lastCloseError=G;throw G}let Q=Y?new $6(J.toString(),{headers:{...Y}}):new(Y6())(J.toString(),Z?[`${V6}${Z}`]:void 0);this.socket=Q;let j=!1,V=new Promise((G,N)=>{let K=!1,W=setTimeout(()=>{if(K)return;K=!0,j=!0;let q=new U("hub_connect_timeout",`Timed out connecting to hub after ${n}ms`);if(this.socket===Q)this.lastCloseError=q,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}N(q)},n);Q.addEventListener("open",()=>{if(K)return;K=!0,clearTimeout(W),G()}),Q.addEventListener("error",(q)=>{if(K)return;K=!0,clearTimeout(W);let z=j1(q,J);if(this.socket===Q)this.lastCloseError=z,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;N(z)}),Q.addEventListener("close",(q)=>{if(K)return;K=!0,clearTimeout(W);let z=j?this.lastCloseError:V1(q);if(this.socket===Q){if(!j)this.lastCloseError=z,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}N(z)})});return Q.addEventListener("message",(G)=>{this.handleFrame(JSON.parse(W1(G)))}),Q.addEventListener("close",(G)=>{if(this.socket!==Q)return;if(!j)this.lastCloseError=V1(G),this.sawSocketClose=!0;this.registered=!1;for(let N of this.pendingReplies.values())N.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await V,Q}subscribe(J,Z){let $=Z?.sessionId?.trim()||void 0,X={listener:J,sessionId:$};return this.listeners.add(X),this.adjustSubscriptionCount($,1),()=>{if(!this.listeners.delete(X))return;this.adjustSubscriptionCount($,-1)}}async command(J,Z,$,X){let Y=0,Q=J!=="client.register"&&J!=="client.unregister";while(!0)try{return await this.commandOnce(J,Z,$,X)}catch(j){if(!Q||Y>=1||!await this.recoverLocalHubTransport(j))throw j;Y+=1}}async commandOnce(J,Z,$,X,Y=!0){if(Y)await this.connect();X?.beforeDispatch?.();let Q=o2("hubreq_");X?.onDispatch?.(Q);let j=Z6(J,X?.timeoutMs),V=new Promise((N,K)=>{let W=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Q))return;K(new B0(J,"hub_command_timeout",`Hub command ${J} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${Q}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(Q,{resolve:(q)=>{if(W)clearTimeout(W);N(q)},reject:(q)=>{if(W)clearTimeout(W);K(q)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:J,requestId:Q,clientId:this.clientId,sessionId:$,timeoutMs:j,payload:Z}})}catch(N){throw this.pendingReplies.delete(Q),N}let G=await V;if(!G.ok){if(G.error?.code===b0){let N=$??(typeof Z?.sessionId==="string"?Z.sessionId:void 0);throw new u(N,G.error.message)}throw new B0(J,G.error?.code,G.error?.message??`Hub command ${J} failed`)}return G}async recoverLocalHubTransport(J){if(!N1(this.currentUrl)||!K6(J))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Z=await K1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Z)return!1;return this.currentUrl=Z,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(G6*2**this.reconnectAttempt,N6),Z=Math.round(J*(1-G1)+Math.random()*J*G1);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Z)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!N1(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let J=await K1({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 U("hub_connection_closed",q0);for(let Z of this.pendingReplies.values())Z.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 U("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(J))}sendSubscriptionFrame(J,Z){let $=J==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(Z)):void 0;this.sendFrame({kind:J,clientId:this.clientId,...Z?{sessionId:Z}:{},...$!==void 0?{sinceSequence:$}:{}})}adjustSubscriptionCount(J,Z){let $=this.subscriptionKeyForSessionId(J),X=(this.subscriptionCounts.get($)??0)+Z;if(X<=0){if(this.subscriptionCounts.delete($),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Z<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",J);return}if(this.subscriptionCounts.set($,X),Z>0&&X===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",J)}subscriptionKeyForSessionId(J){return J??L0}subscriptionSessionIdFromKey(J){return J===L0?void 0:J}handleFrame(J){switch(J.kind){case"reply":{let Z=J.envelope.requestId;if(!Z)return;let $=this.pendingReplies.get(Z);if(!$)return;this.pendingReplies.delete(Z),$.resolve(J.envelope);return}case"event":{let Z=J.envelope.sequence;if(typeof Z==="number"){let $=J.envelope.sessionId?.trim();for(let X of[L0,$]){if(!X||!this.subscriptionCounts.has(X))continue;let Y=this.lastEventSequenceByKey.get(X)??0;if(Z>Y)this.lastEventSequenceByKey.set(X,Z)}}for(let $ of this.listeners){if($.sessionId&&$.sessionId!==J.envelope.sessionId?.trim())continue;$.listener(J.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function L1(J){let Z=new URL(J);if(Z.protocol==="http:")Z.protocol="ws:";else if(Z.protocol==="https:")Z.protocol="wss:";return Z.toString()}async function w(J,Z){let $=new I({url:J,authToken:Z?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{return await $.connect(),!0}catch{return!1}finally{$.close()}}async function A0(J,Z){let $=L1(J),X=await i($,{authToken:Z?.authToken});if(!X)return{status:"unreachable",url:$};if(Z?.requireCurrentBuild){let Y=b(),Q=a(X,Y);if(!Q.compatible&&!d(X))return{status:Q.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:$}}else if(!e2(X).compatible)return{status:"protocol_mismatch",url:$};if(Z?.verifyConnection===!0&&!await w($,{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,authToken:Z.authToken}))return{status:"unreachable",url:$};return{status:"compatible",url:$}}function F6(J){let Z=J&&typeof J==="object"&&Array.isArray(J.sessions)?J.sessions:[],$=0,X=new Set;for(let Y of Z){if(!Y||typeof Y!=="object")continue;let Q=Y.participants;if(!Array.isArray(Q)||Q.length===0)continue;$+=1;for(let j of Q){let V=j&&typeof j==="object"?j.clientId:void 0;if(typeof V==="string"&&V.trim())X.add(V)}}return{activeSessionCount:$,participantClientCount:X.size}}async function z0(J,Z,$){let X=new I({url:J,authToken:Z,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{let Y=await X.command("session.list",{limit:500},void 0,{timeoutMs:j6});return F6(Y.payload)}finally{await X.dispose().catch(()=>{return})}}async function z6(J,Z,$){try{return(await z0(J,Z,$)).activeSessionCount===0}catch{return!1}}async function L6(J,Z){let $=`${J.discoveryPath}.superseded`,X=await C($);if(!X?.url||!X.authToken)return;let Y=await A0(X.url,{authToken:X.authToken});if(Y.status!=="compatible")return;if(await z6(Y.url,X.authToken,Z))return;return r(Y.url,X.authToken)}async function q6(J={}){if(J.endpoint?.trim()){let Y=await A0(J.endpoint);return Y.status==="compatible"?Y.url:void 0}let Z=X6(),$=await C(Z.discoveryPath);if(!$?.url)return await L6(Z,J);let X=await A0($.url,{authToken:$.authToken,requireCurrentBuild:!0});if(X.status==="compatible")return r(X.url,$.authToken);if(X.status==="protocol_mismatch")await k(Z.discoveryPath).catch(()=>{return});return}async function K1(J={}){let Z=await q6(J);if(Z&&await w(Z,{workspaceRoot:J.workspaceRoot,cwd:J.cwd}))return Z;if(J.endpoint?.trim())return;try{return(await Y1(J.workspaceRoot??process.cwd())).url}catch($){J.onStartupError?.($);return}}async function S(J,Z,$,X){let Y=new URL(J),Q=Z?.trim()||D0(Y);if(Y.protocol==="ws:")Y.protocol="http:";else if(Y.protocol==="wss:")Y.protocol="https:";if(Y.pathname="/drain",Y.hash="",$)Y.searchParams.set("reason",$);if(X?.off)Y.searchParams.set("off","1");return(await fetch(Y,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function Q1(J,Z){let $=new URL(J),X=Z?.trim()||D0($);if($.protocol==="ws:")$.protocol="http:";else if($.protocol==="wss:")$.protocol="https:";return $.pathname="/shutdown",$.hash="",(await fetch($,{method:"POST",headers:X?{authorization:`Bearer ${X}`}:void 0})).ok}import{formatDisplayUserInput as q1}from"@cline/shared";var B6=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function A6(J){switch(J){case"user":case"assistant":case"tool":case"system":case"status":case"error":return J;default:return"assistant"}}function D6(J){return J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}function M6(J){let Z=J?.userRunSpan;return typeof Z==="number"&&Number.isInteger(Z)&&Z>=0?Z:void 0}function _6(J){if(typeof J.content==="string")return{hasAttachment:!1,text:J.content};if(!Array.isArray(J.content))return{hasAttachment:!1,text:"unknown"};let Z=!1,$=!1,X=[];for(let Y of J.content){if(!Y||typeof Y!=="object"||Array.isArray(Y))continue;let Q=Y;if(Q.type==="text"&&typeof Q.text==="string")X.push(Q.text);else if(Q.type==="tool_result"||Q.type==="tool-result")$=!0;else if(Q.type==="file"||Q.type==="image")Z=!0}return{hasAttachment:Z&&!$,text:X.join(`
|
|
5
|
+
`)}}function f6(J){let Z=q1(J);return Z.startsWith("[TASK RESUMPTION]")||Z==="The user approved switching to act mode. Continue with the approved plan now."}function U6(J){if(A6(J.role)!=="user")return 0;let Z=D6(J),$=typeof Z?.kind==="string"?Z.kind:void 0,X=M6(Z);if($==="compaction"||$==="compaction_summary")return X??1;if(X!==void 0)return X;if($&&B6.has($))return 0;let Y=_6(J);if(!Y.hasAttachment&&!q1(Y.text))return 0;if(!Y.hasAttachment&&f6(Y.text))return 0;return 1}function B1(J){return U6(J)>0}function _1(J){return Array.isArray(J?.sessions)?J.sessions.filter((Z)=>Boolean(Z)&&typeof Z==="object"&&!Array.isArray(Z)):[]}function _0(J){let Z=J.updatedAt;return typeof Z==="number"?Z:Date.parse(String(Z??""))||0}function f0(J){let Z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;return String(Z?.model??J?.model??"").trim()}function f1(J){let Z=J.metadata&&typeof J.metadata==="object"?J.metadata:void 0;return!String(Z?.parentSessionId??J.parentSessionId??"").trim()}function U1(J,Z="text"){if(!J||typeof J!=="object"||Array.isArray(J))return"";let $=J.content;if(typeof $==="string")return Z==="text"?$.trim():"";if(!Array.isArray($))return"";return $.map((X)=>X&&typeof X==="object"&&!Array.isArray(X)?Z==="thinking"&&X.type==="redacted_thinking"?"[redacted]":String(X[Z]??""):"").join("").trim()}function s(J){let Z=J.trim(),$=Z.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return($?$[1]:Z).trim()}function p(J,Z,$){let X=s($);return J.filter((Y)=>Boolean(Y)&&typeof Y==="object"&&!Array.isArray(Y)&&String(Y.role??"").toLowerCase()==="user"&&(X!==""||B1(Y))&&s(U1(Y))===X).length+Z.filter((Y)=>s(Y.prompt)===X).length}function U0(J){return J.flatMap((Z)=>{if(Z.event!=="session.pending_prompt_submitted")return[];let $=Z.payload?.prompt&&typeof Z.payload.prompt==="object"&&!Array.isArray(Z.payload.prompt)?Z.payload.prompt:void 0,X=String($?.id??"").trim();if(!X)return[];return[{id:X,prompt:String($?.prompt??""),steer:$?.delivery==="steer",attachmentCount:typeof $?.attachmentCount==="number"?$.attachmentCount:0,userImages:Array.isArray($?.userImages)?$.userImages.filter((Y)=>typeof Y==="string"):void 0}]})}var H6=new Set(["run.completed","run.aborted","run.failed"]),O6=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function A1(J,Z){return J.filter(($)=>Boolean($)&&typeof $==="object"&&!Array.isArray($)&&String($.role??"").toLowerCase()==="assistant").map(($)=>U1($,Z)).filter(Boolean)}function D1(J,Z,$="text"){let X=new Map;for(let Y of A1(Z,$))X.set(Y,(X.get(Y)??0)+1);return A1(J,$).filter((Y)=>{let Q=X.get(Y)??0;if(Q===0)return!0;if(Q===1)X.delete(Y);else X.set(Y,Q-1);return!1})}function o(J,Z,$=new Set){if(!J||typeof J!=="object")return $;if(Array.isArray(J)){for(let Q of J)o(Q,Z,$);return $}let X=J,Y=Z==="tool_use"?X.id:X.tool_use_id;if(X.type===Z&&typeof Y==="string")$.add(Y);for(let Q of Object.values(X))o(Q,Z,$);return $}function M1(J,Z="assistant"){let $="",X="";for(let Y of J)if(Y.event===`${Z}.delta`)X+=Z==="reasoning"&&Y.payload?.redacted&&!Y.payload?.text?"[redacted]":typeof Y.payload?.text==="string"?Y.payload.text:"";else if(Y.event===`${Z}.finished`){let Q=Y.payload?.[Z==="assistant"?"text":"reasoning"],j=typeof Q==="string"&&Q?Q:X;if(j)$=j;X=""}return($||X).trim()}function H1(J,Z,$={}){let X=$.queueSnapshotApplied!==!1,Y=D1(Z,$.baselineMessages??[]),Q=D1(Z,$.baselineMessages??[],"thinking"),j=o(Z,"tool_use"),V=o(Z,"tool_result"),G=new Set(J.slice(0,$.messagesSnapshotEventCutoff??J.length)),N=new Set,K=new Map;for(let B of J.slice(0,$.messagesSnapshotEventCutoff??J.length)){let M=U0([B])[0];if(!M)continue;let _=s(M.prompt),x=K.get(_)??Math.max(0,p(Z,[],_)-p($.baselineMessages??[],[],_));if(K.set(_,Math.max(0,x-1)),x>0)N.add(B)}let q=[...X?J.slice($.queueSnapshotEventCutoff??J.length):J].reverse().find((B)=>B.event==="session.pending_prompts"),z=[],F=[],A=(B)=>{if(F.length===0)return;let M=F.filter((P)=>G.has(P)),_=(P)=>{if(!B)return-1;let f=[...M].reverse().findIndex((T1)=>T1.event===`${P}.finished`),h=f<0?-1:M.length-1-f;return h>=0||F.at(-1)?.event==="run.aborted"?h:M.length-1},x=_("assistant"),T=_("reasoning"),D=M1(M.slice(0,x+1)),H=D?Y.findIndex((P)=>P.endsWith(D)):-1,E=H>=0;if(E)Y.splice(H,1);let l=M1(M.slice(0,T+1),"reasoning"),Z0=l?Q.findIndex((P)=>P.endsWith(l)):-1;if(Z0>=0)Q.splice(Z0,1);for(let[P,f]of F.entries()){if(N.has(f)){z.push({...f,payload:{...f.payload,transcriptReflected:!0}});continue}if(G.has(f)&&O6.has(f.event)&&(f.event.startsWith("reasoning.")?Z0>=0&&P<=T:E&&P<=x))continue;if(f.event==="session.pending_prompts"&&f!==q)continue;if(G.has(f)&&f.event.startsWith("tool.")){let h=String(f.payload?.toolCallId??"").trim();if(V.has(h)||f.event==="tool.started"&&j.has(h))continue}z.push(f)}F=[]};for(let B of J)if(F.push(B),H6.has(B.event))A(!0);return A(!1),z}import{formatDisplayUserInput as x6}from"@cline/shared";function e(J){let Z=structuredClone(J),$=(X)=>{if(!X||typeof X!=="object"||Object.isFrozen(X))return;for(let Y of Object.values(X))$(Y);Object.freeze(X)};return $(Z),Z}function J0(J){let Z=J?.trim();return Z?x6(Z).slice(0,120):void 0}function H0(J){if(typeof J==="string")return J;if(Array.isArray(J)){let Z=[];for(let $ of J){if(typeof $==="string"){if($.trim())Z.push($);continue}if(!$||typeof $!=="object")continue;let X=$,Y=typeof X.type==="string"?X.type:"",Q=Y==="text"?String(X.text??""):Y==="thinking"?String(X.thinking??""):Y==="tool_use"?`[tool] ${String(X.name??"tool_call")}`:Y==="tool_result"?`[tool_result]
|
|
6
6
|
${H0(X.content)}`:Y==="image"?"[image]":Y==="redacted_thinking"?"[redacted_thinking]":typeof X.text==="string"?X.text:"";if(Q.trim())Z.push(Q)}return Z.join(`
|
|
7
|
-
`)}if(J&&typeof J==="object"){let Z=J;if(typeof Z.text==="string")return Z.text}return""}function
|
|
8
|
-
`)[0]?.trim().slice(0,70)||void 0}function
|
|
9
|
-
`)[0]?.trim().slice(0,70)||void 0}return}function O0(J){let Z=J.metadata&&typeof J.metadata==="object"?J0(J.metadata.title):void 0;if(Z)return Z.slice(0,70);let $=P5(J.prompt);if($)return $;let X=J.messages?R5(J.messages):void 0;if(X)return X;return`Session ${J.sessionId.slice(-6)}`}function H1(J,Z,$,X){let Y=Z.payload??{},Q=()=>{let V=$.get(X);if(V===void 0||!J.messages[V]||J.messages[V]?.role!=="assistant")V=J.messages.length,J.messages.push({role:"assistant",content:[]}),$.set(X,V);let G=J.messages[V];if(!Array.isArray(G.content))G.content=[];return G.content},j=(V,G,N)=>{let K=Q(),W=K.at(-1);if(W?.type===V)W[G]=`${W[G]??""}${N}`;else K.push({type:V,[G]:N})};switch(Z.event){case"assistant.delta":if(typeof Y.text==="string")j("text","text",Y.text);return;case"reasoning.delta":if(typeof Y.text==="string"&&Y.text)j("thinking","thinking",Y.text);else if(Y.redacted===!0)Q().push({type:"redacted_thinking",data:""});return;case"assistant.finished":$.delete(X);return;case"assistant.media":if(Y.media)Q().push({type:"media",media:structuredClone(Y.media)});return;case"tool.started":{let V=String(Y.toolCallId??"");if(V&&!J.messages.some((G)=>Array.isArray(G.content)&&G.content.some((N)=>N.type==="tool_use"&&N.id===V)))Q().push({type:"tool_use",id:V,name:String(Y.toolName??"tool"),input:structuredClone(Y.input??{})});return}case"tool.finished":{let V=String(Y.toolCallId??"");if(V&&!J.messages.some((G)=>Array.isArray(G.content)&&G.content.some((N)=>N.type==="tool_result"&&N.tool_use_id===V)))J.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:V,content:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output??""),is_error:Boolean(Y.error)}]}),$.delete(X);return}case"usage.updated":J.usage=structuredClone(Y.totals??Y.delta??{});return;case"session.pending_prompts":{let V=Array.isArray(Y.prompts)?Y.prompts:[];J.promptsInQueue=V.map((G)=>({id:String(G.id??""),prompt:String(G.prompt??""),steer:G.delivery==="steer",attachmentCount:typeof G.attachmentCount==="number"?G.attachmentCount:0,userImages:Array.isArray(G.userImages)?G.userImages.filter((N)=>typeof N==="string"):void 0})).filter((G)=>G.id&&(G.prompt||G.attachmentCount));return}case"session.pending_prompt_submitted":{let V=Y.prompt,G=String(V?.id??"");if(!G||J.lastQueuedPromptStartId===G)return;if(J.lastQueuedPromptStartId=G,J.promptsInQueue=J.promptsInQueue.filter((N)=>N.id!==G),Y.transcriptReflected!==!0)J.messages.push({role:"user",content:[{type:"text",text:String(V?.prompt??"")}]});J.busy=!0,J.status="running",J.endedAt=void 0,$.delete(X);return}case"run.started":case"session.attached":case"session.updated":{if(typeof Z.sequence==="number"&&J.lastHubStatusSequence!==void 0&&Z.sequence<J.lastHubStatusSequence)return;if(typeof Z.sequence==="number")J.lastHubStatusSequence=Z.sequence;let V=Y.session,G=typeof V?.status==="string"?V.status:Z.event==="run.started"?"running":J.status,N=G==="pending"?"running":G;if(Z.event==="session.updated"&&N==="running"&&J.endedAt!==void 0&&!J.busy)return;let K=J.busy;if(J.status=N,J.busy=N==="running",Z.event==="run.started"){if(!K)$.delete(X);J.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof Z.sequence==="number"&&J.lastHubStatusSequence!==void 0&&Z.sequence<J.lastHubStatusSequence)return;if(typeof Z.sequence==="number")J.lastHubStatusSequence=Z.sequence;J.status=typeof Y.reason==="string"?Y.reason:Z.event==="run.failed"?"error":Z.event==="run.aborted"?"aborted":"completed",J.busy=!1,J.endedAt=Date.now(),$.delete(X);return}}}function O1(J){return J instanceof Error&&J.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String(J.code))}function x1(J,Z){return J instanceof Error&&J.name==="HubCommandError"&&J.code==="hub_command_timeout"&&(!Z||J.command===Z)}var O="/workspace",T5=30000,C5=2000,E5=2000,b5="IMPORTANT: GitHub authentication is handled automatically by the infrastructure. An egress proxy transparently injects credentials into all GitHub traffic. You do NOT need to set up, configure, or manage any tokens, API keys, or credentials, and you must never run `gh auth login` or attempt to authenticate manually. "+"The GitHub CLI (`gh`) is installed and already authenticated — prefer it for GitHub work "+"(`gh pr create`, `gh pr diff`, `gh issue list`, `gh api`, ...). `git` push and pull are authenticated the same way. "+"Simply run the commands normally — credentials are injected transparently.";class R1 extends L{constructor(){super("request_failed","The connection was interrupted and Cline could not confirm whether this message was queued. Check the cloud session before resending it.");this.name="CloudQueueUnconfirmedError"}}function R(J){let Z=J.expiredAt?Date.parse(J.expiredAt):Number.NaN;return Number.isFinite(Z)&&Z<=Date.now()}function k5(J){return J.trim().startsWith("ses-")}function h5(J,Z){let $=new URL(`/api/v1/session/${encodeURIComponent(Z)}`,J);return $.protocol=$.protocol==="https:"?"wss:":"ws:",$.toString()}function x0(J){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:J.metadata.modelId??"",modelId:J.metadata.modelId??"",repoUrl:J.repoContext.repoUrl??"",branch:J.repoContext.branch??"",cwd:O,workspaceRoot:O},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse(J.createdAt)||Date.now(),endedAt:R(J)&&J.expiredAt?Date.parse(J.expiredAt):void 0,status:J.status,attachedViaHub:!0}}function P0(J,Z,$){return{sessionId:J.id,origin:"cloud",executionTarget:"cloud",status:Z,provider:"cline",model:J.metadata.modelId??"",repoUrl:J.repoContext.repoUrl??"",branch:J.repoContext.branch??"",cwd:O,workspaceRoot:O,...$?.trim()?{prompt:$.trim()}:{},metadata:{origin:"cloud",repoUrl:J.repoContext.repoUrl??"",git:{url:J.repoContext.repoUrl??"",branch:J.repoContext.branch??""}}}}function P1(J){return{sessionId:J.id,origin:"cloud",executionTarget:"cloud",status:J.status,provider:"cline",model:J.metadata.modelId??"",cwd:O,workspaceRoot:O,repoUrl:J.repoContext.repoUrl??"",branch:J.repoContext.branch??"",startedAt:J.createdAt,...J.lastActivityAt?{lastActivityAt:J.lastActivityAt}:{},endedAt:R(J)?J.expiredAt??void 0:J.status==="failed"?J.lastActivityAt??J.createdAt:void 0,updatedAt:J.updatedAt,...J.title?.trim()?{title:J.title.trim()}:{},metadata:{...J.title?.trim()?{title:J.title.trim()}:{},origin:"cloud",...J.metadata.provisioningPhase?{provisioningPhase:J.metadata.provisioningPhase}:{},repoUrl:J.repoContext.repoUrl??"",git:{url:J.repoContext.repoUrl??"",branch:J.repoContext.branch??""}}}}function g5(J){if(typeof J!=="string")return J;try{return JSON.parse(J)}catch{return J}}function y5(J,Z){let $=[...J??[]],X=new Set($.map((Y)=>Y.id));for(let Y of Z)if(!X.has(Y.id))$.push(Y);return $}class v5{options;sessionGenerations=new Map;sessions=new Map;approvals=new Map;listeners=new Set;detachedSessions=new Set;restoredOptions=new Map;authoritativeMessages=new Map;streamingMessages=new Map;disposed=!1;connections=new Map;connectionPromises=new Map;knownSessions=new Map;unlistedSessions=new Map;pendingInitialTasks;lastListedSessions=[];discoveryRefresh;createRequests=new Map;provisioningControllers=new Map;sendAbortTokens=new Map;titleWrites=new Map;deletingSessions=new Set;createHubClient;constructor(J){this.options=J;this.pendingInitialTasks=J.pendingInitialTasks??new Map,this.createHubClient=J.createHubClient??((Z)=>new I(Z))}restoreCreationOptions(J,Z){if(this.restoredOptions.set(J,structuredClone(Z)),this.pendingInitialTasks.has(J))this.pendingInitialTasks.set(J,{...this.pendingInitialTasks.get(J),...structuredClone(Z)});let $=this.sessions.get(J);if($)Object.assign($.config,structuredClone(Z))}seedSessionState(J,Z){if(!this.sessions.has(J))this.sessions.set(J,structuredClone(Z))}stateFromRecord(J){let Z=x0(J);return Object.assign(Z.config,this.pendingInitialTasks.get(J.id),this.restoredOptions.get(J.id)),Z}getSnapshot(J){let Z=this.knownSessions.get(J),$=this.sessions.get(J)??(Z?this.stateFromRecord(Z):void 0);if(!$)return;let X=this.connections.get(J);return e({...$,sessionId:J,record:Z,approvals:Array.from(this.approvals.values()).filter((Y)=>Y.item.sessionId===J).map((Y)=>Y.item),connectionState:this.detachedSessions.has(J)||this.disposed?"detached":X?.reconnectResolution||X?.rehydrationPromise?"reconnecting":X?X.connected?"connected":X.reconnecting?"reconnecting":"connecting":this.connectionPromises.has(J)?"connecting":"detached",transcriptKnown:X?.transcriptKnown??Boolean(Z&&R(Z))})}subscribe(J,Z){let $=(X)=>{if(!Z||X.sessionId===Z)J(X)};return this.listeners.add($),()=>{this.listeners.delete($)}}publish(J){let Z=J.type==="snapshot"?Object.freeze(J):e(J);for(let $ of this.listeners)try{$(Z)}catch(X){this.options.logger?.error?.("Cloud session subscriber failed",{error:X})}}publishSnapshot(J,Z=!1,$){this.cancelScheduledSnapshot(J);let X=this.getSnapshot(J);if(X)this.publish({type:"snapshot",sessionId:J,snapshot:X,replace:Z,cause:$});else this.publish({type:"removed",sessionId:J})}snapshotTimers=new Map;cancelScheduledSnapshot(J){clearTimeout(this.snapshotTimers.get(J)),this.snapshotTimers.delete(J)}scheduleSnapshot(J){if(this.disposed||this.detachedSessions.has(J)||this.snapshotTimers.has(J))return;let Z=setTimeout(()=>this.publishSnapshot(J),100);Z.unref?.(),this.snapshotTimers.set(J,Z)}notify(J,Z){let $=String(Z.sessionId??"");if(J==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:$,message:String(Z.message??"Cloud synchronization failed")});else this.publishSnapshot($,J==="cloud_session_rehydrated",J==="chat_session_status"?"status":J==="chat_session_ended"?"ended":J==="tool_approval_state"?"approvals":void 0)}applyLiveEvent(J,Z){let $=this.sessions.get(J);if($)H1($,Z,this.streamingMessages,J)}async respondApproval(J,Z,$){this.assertSessionActive(J);let X=this.approvals.get(`${J}:${Z}`);if(!X){if(!this.connections.has(J))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new L("request_failed","This approval was already resolved or is no longer available.")}await X.resolve($)}async detach(J){this.detachedSessions.add(J),this.sessionGenerations.set(J,(this.sessionGenerations.get(J)??0)+1),this.connectionPromises.delete(J),this.sendAbortTokens.set(J,Symbol()),this.abortProvisioningControllers(J,Error("Cloud viewer detached")),await this.disposeConnection(J),this.publishSnapshot(J)}isCloudSession(J){return k5(J)||this.knownSessions.has(J)||this.connections.has(J)||this.sessions.get(J)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord(J){let Z=this.knownSessions.get(J);return Z?P1(Z):void 0}async getCrossScopeDiscoveryRecord(J){let Z=this.getCachedDiscoveryRecord(J);if(!Z)return;try{let X=(await this.options.api.status(J)).status?.trim();return X?{...Z,status:X}:Z}catch($){if($ instanceof L&&($.code==="session_not_found"||$.code==="session_expired")){this.knownSessions.delete(J),this.unlistedSessions.delete(J),this.pendingInitialTasks.delete(J);return}return Z}}async list(){if(this.disposed)throw Error("Cloud session controller was disposed");let J=await this.resolveActiveOrganizationId(),Z=(await this.options.api.list(J)).map((X)=>this.preserveConnectedRuntimeModel(X));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=Z;for(let X of Z)this.knownSessions.set(X.id,X),this.unlistedSessions.delete(X.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(X)=>this.getCrossScopeDiscoveryRecord(X)));let $=await Promise.all(Z.map(async(X)=>{if(X.status!=="provisioning")return X;let Y=await this.options.api.status(X.id).catch(()=>{return}),Q=Y?.status?.trim();if(!Q)return X;return{...X,status:Q,metadata:{...X.metadata,...Q0(Y?.phase)?{provisioningPhase:Y?.phase}:{},...Y?.statusReason?.trim()?{statusReason:Y.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let X of $){this.knownSessions.set(X.id,X);let Y=this.sessions.get(X.id);if(Y?.status==="provisioning"&&X.status!=="provisioning")Y.status=X.status;let Q=this.connections.get(X.id);if(Q)Q.remote=X;let j=R(X);if(j||X.status==="failed"){if(Y)Y.busy=!1,Y.status=j?"expired":"failed",Y.endedAt=j?Date.parse(X.expiredAt??"")||Date.now():Math.max(Y.endedAt??0,Date.parse(X.lastActivityAt??X.createdAt)||0)||void 0;if(Q)this.disposeConnection(X.id).catch(()=>{return})}}this.lastListedSessions=$;for(let X of $)if(this.sessions.has(X.id))this.publishSnapshot(X.id);return e($)}preserveConnectedRuntimeModel(J){let Z=this.connections.get(J.id)?.remote.metadata.modelId?.trim();if(!Z||Z===J.metadata.modelId)return J;return{...J,metadata:{...J.metadata,modelId:Z}}}async resolveActiveOrganizationId(J){return await this.options.getActiveOrganizationId?.(J)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listBranches(J,Z={}){return await this.options.api.listBranches(J,await this.resolveActiveOrganizationId(),Z)}async listForDiscovery(J={}){let Z=this.discoveryRefresh??this.list().finally(()=>{if(this.discoveryRefresh===Z)this.discoveryRefresh=void 0});this.discoveryRefresh=Z;let $=this.lastListedSessions;if(J.timeoutMs===void 0)$=await Z;else{let Q,j=await Promise.race([Z.then((V)=>({value:V}),(V)=>{if(!(V instanceof L&&V.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:V});return{value:this.lastListedSessions}}),new Promise((V)=>{Q=setTimeout(()=>V({value:this.lastListedSessions}),Math.max(0,J.timeoutMs??0))})]);if(Q)clearTimeout(Q);$=j.value}return[...new Map([...this.unlistedSessions.values(),...$].map((Q)=>[Q.id,Q])).values()].map((Q)=>{let j=P1(Q),V=this.sessions.get(Q.id);if(!V)return j;let G=V.title?.trim()||Q.title?.trim();return{...j,status:V.status,prompt:V.prompt,endedAt:V.endedAt!==void 0?new Date(V.endedAt).toISOString():j.endedAt,metadata:{...j.metadata??{},title:O0({sessionId:Q.id,metadata:G?{title:G}:void 0,prompt:V.prompt,messages:V.messages})}}})}async create(J){let Z=J.requestId?.trim();if(!Z)return await this.createOnce(J);let $=this.createRequests.get(Z);if($)return await $;let X=this.createOnce(J).finally(()=>{if(this.createRequests.get(Z)===X)this.createRequests.delete(Z)});return this.createRequests.set(Z,X),await X}trackProvisioningController(J,Z){let $=this.provisioningControllers.get(J);if(!$)$=new Set,this.provisioningControllers.set(J,$);return $.add(Z),()=>{if($.delete(Z),$.size===0)this.provisioningControllers.delete(J)}}abortProvisioningControllers(J,Z){let $=this.provisioningControllers.get(J);if(!$?.size)return!1;for(let X of $)X.abort(Z);return!0}async createOnce(J){if(this.disposed)throw Error("Cloud session manager was disposed");let Z=J.organizationId??await this.resolveActiveOrganizationId({fresh:!0}),$=await this.options.api.create({...J,organizationId:Z});if(!$?.sessionId?.trim())throw new L("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose($.sessionId,$.cleanupAuthToken);throw Error("Cline account changed while the cloud session was starting")}let X={id:$.sessionId,status:$.status,sandboxUrl:$.sandboxUrl,repoContext:{repoUrl:J.repoUrl,...J.branch?.trim()?{branch:J.branch.trim()}:{}},metadata:{modelId:J.modelId},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.knownSessions.set(X.id,X),this.unlistedSessions.set(X.id,X);let{autoApproveTools:Y,thinking:Q,reasoningEffort:j}=J;this.pendingInitialTasks.set(X.id,{autoApproveTools:Y,thinking:Q,reasoningEffort:j});let V=this.stateFromRecord(X);return V.prompt=J.initialPrompt?.trim()||void 0,this.sessions.set(X.id,V),this.notify("chat_session_status",{sessionId:X.id,status:V.status}),{sessionId:X.id,origin:"cloud",executionTarget:"cloud",status:X.status,provider:"cline",model:J.modelId,repoUrl:J.repoUrl,branch:J.branch??"",cwd:O,workspaceRoot:O,...V.prompt?{prompt:V.prompt}:{}}}async deleteProvisionedSessionAfterDispose(J,Z){this.knownSessions.delete(J),this.unlistedSessions.delete(J),this.pendingInitialTasks.delete(J),this.sessions.delete(J),await this.options.api.delete(J,Z).catch(($)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:J,error:$})})}async attach(J,Z){let $=this.sessionGenerations.get(J)??0;if(this.detachedSessions.delete(J),Z)this.restoreCreationOptions(J,Z);let X=await this.ensureKnownSession(J);if(this.assertSessionActive(J),$!==(this.sessionGenerations.get(J)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has(J))this.sessions.set(J,this.stateFromRecord(X));if(X.status==="provisioning"||X.status==="failed")return P0(X,X.status,this.sessions.get(J)?.prompt);if(R(X))return await this.disposeConnection(J),await this.attachExpired(X);let Y;try{Y=await this.ensureConnection(J)}catch(V){let G=await this.refreshKnownSession(J);if(G&&R(G))return await this.disposeConnection(J),await this.attachExpired(G);throw V}await this.ensureAttached(Y);let Q=Y.remote,j=this.sessions.get(J);return P0(Q,j?.status??Q.status,j?.prompt)}async send(J,Z,$,X,Y){let Q=this.sendAbortTokens.get(J),j=this.knownSessions.get(J);if(j&&R(j))throw new L("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let V=await this.ensureConnection(J,{createInner:!0}),G=()=>this.disposed||V.disposed||this.deletingSessions.has(J)||this.sendAbortTokens.get(J)!==Q,N=()=>{if(G())throw Error("Cloud session prompt cancelled")};if(N(),await V.reconnectResolution,N(),await this.ensureAttached(V),await V.reconnectResolution,N(),!V.transcriptKnown)await this.rehydrateAfterTransportDrop(J,V);N(),await this.updateModel(V,X),await V.reconnectResolution,N();let K=V.innerSessionId;if(!K)throw Error("Cloud Hub session was not initialized");let W=this.sessions.get(J),q=$??(W?.busy?"queue":void 0),z=p(W?.messages??[],W?.promptsInQueue??[],Z),F=q!=="queue"&&q!=="steer",A=W&&q!=="queue"?{role:"user",content:[{type:"text",text:Z}]}:void 0;if(W&&A)W.messages=[...W.messages,A];let B=()=>{if(W&&A)W.messages=W.messages.filter((D)=>D!==A),this.publishSnapshot(J)};if(W&&F){let D=W.status!=="running";if(W.busy=!0,W.status="running",W.prompt||=Z,D)this.publishSnapshot(J,!1,"status")}let M=this.knownSessions.get(J);if(M&&!M.title?.trim()&&!this.titleWrites.has(J)){let D=E0(Z);if(D){if(M.title=D,W)W.title=D;let H=this.options.api.updateTitle?.(J,D).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get(J)===H)this.titleWrites.delete(J)});if(H)this.titleWrites.set(J,H)}}let _=new Set,x=!1,T=()=>{if(x||G())return;x=!0,this.publish({type:"prompt_accepted",sessionId:J,prompt:Z,delivery:q})};try{let D=await V.client.command("session.send_input",{prompt:Z,delivery:q,...Y?.length?{attachments:{userImages:Y}}:{}},K,{timeoutMs:q==="queue"?T5:null,onDispatch:(E)=>{_.add(E),V.pendingInputs??=new Map,V.pendingInputs.set(E,{clientId:V.client.getClientId(),ownsBusyState:F,accept:T})},beforeDispatch:()=>{if(N(),V.innerSessionId!==K)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.")}});T();let H=q==="queue"||q!=="steer"&&D.payload?.result===void 0;if(H)B();return{sessionId:J,ok:!0,...H?{queued:!0}:{},result:D.payload?.result}}catch(D){if(G())throw B(),D;if(O1(D)||x1(D,"session.send_input")){let H;try{H=await this.rehydrateAfterTransportDrop(J,V)}catch(l){if(N(),B(),W&&F)W.busy=!1,W.status="error";if(q==="queue")throw new R1;throw l}if(N(),q==="queue"||q==="steer")throw new L("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(p(H.messages,y5(H.prompts,H.submittedPrompts),Z)<=z)throw new L("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:J,ok:!0,...q==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:H.status}}if(B(),W&&F)W.busy=!1,W.status="error";throw this.publishSnapshot(J),D}finally{for(let D of _)V.pendingInputs?.delete(D)}}async updateModel(J,Z){let $=Z?.trim();if(!$||J.remote.metadata.modelId===$)return;let X=J.innerSessionId;if(!X)throw Error("Cloud Hub session was not initialized");await J.client.command("session.update_connection",{sessionId:X,updates:{modelId:$}},X,{beforeDispatch:()=>{if(this.assertSessionActive(J.remote.id,J),J.innerSessionId!==X)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive(J.remote.id,J),this.applyModel(J,$)}applyModel(J,Z){J.remote.metadata.modelId=Z;let $=this.sessions.get(J.remote.id);if($)$.config.model=Z,$.config.modelId=Z}async rehydrateAfterTransportDrop(J,Z){if(this.assertSessionActive(J,Z),Z.rehydrationPromise)return Z.rehydrationRerunRequested=!0,await Z.rehydrationPromise;let $=(async()=>{let X;do Z.rehydrationRerunRequested=!1,X=await this.performTransportRehydration(J,Z),this.assertSessionActive(J,Z);while(Z.rehydrationRerunRequested&&!this.disposed);return X})().finally(()=>{if(Z.rehydrationPromise===$)Z.rehydrationPromise=void 0,this.publishSnapshot(J)});return Z.rehydrationPromise=$,await $}async performTransportRehydration(J,Z){this.assertSessionActive(J,Z);let $=Z.innerSessionId;if(!$)throw Error("Cloud Hub session was not initialized");Z.bufferingEvents=!0,Z.bufferedEvents=[],Z.bufferedEventsDropped=0;try{await this.ensureAttached(Z),this.assertSessionActive(J,Z);let X=await Z.client.command("session.get",{includeSnapshot:!0},$);this.assertSessionActive(J,Z);let Y=X.payload?.session&&typeof X.payload.session==="object"&&!Array.isArray(X.payload.session)?X.payload.session:void 0;this.applySessionModel(Z,Y);let Q=this.sessions.get(J),j=this.authoritativeMessages.get(J)??[],V=String(Y?.status??Q?.status??"running").trim(),G=V==="pending"?"running":V;if(G==="running"&&!Z.transcriptKnown&&!Z.pendingInputs?.size)Z.externalRun??={progressHydrated:!0};let N=()=>Z.client.command("session.messages",{sessionId:$},$),K=await N().catch((D)=>{if(!x1(D,"session.messages"))throw D;return this.assertSessionActive(J,Z),N()});if(this.assertSessionActive(J,Z),!Array.isArray(K.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let W=K.payload.messages,q=Z.bufferedEventsDropped+Z.bufferedEvents.length,z=await Z.client.command("session.pending_prompts",{sessionId:$},$).catch(()=>{return});this.assertSessionActive(J,Z);let F=Z.bufferedEventsDropped+Z.bufferedEvents.length;if(Q){let D=Q.status!==G;if(this.authoritativeMessages.set(J,structuredClone(W)),Q.messages=structuredClone(W),this.streamingMessages.delete(J),Q.status=G,Q.busy=G==="running",D)if(G==="completed"||G==="failed"||G==="aborted")Q.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:J,reason:G==="failed"?"error":G});else this.notify("chat_session_status",{sessionId:J,status:G})}let A=z!==void 0&&z.ok!==!1&&Array.isArray(z.payload?.prompts),B=A?this.applyQueueSnapshot(J,z):void 0;Z.transcriptKnown=!0;let M=W;this.assertSessionActive(J,Z),this.notify("cloud_session_rehydrated",{sessionId:J,status:G,transcriptKnown:!0,messages:M}),this.assertSessionActive(J,Z);let _=Z.bufferedEvents,x=U0(_),T=U1(_,W,{queueSnapshotApplied:A,queueSnapshotEventCutoff:Math.max(0,F-Z.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,q-Z.bufferedEventsDropped),baselineMessages:j});Z.bufferedEvents=[],Z.bufferingEvents=!1,Z.syncFailureNotified=!1;for(let D of T)this.forwardEvent(J,Z,D);return{status:G,messages:W,prompts:B,submittedPrompts:x}}catch(X){let Y=Z.bufferedEvents;Z.bufferedEvents=[],Z.bufferingEvents=!1,this.assertSessionActive(J,Z);for(let Q of Y)this.forwardEvent(J,Z,Q);if(!Z.syncFailureNotified)Z.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:J,message:X instanceof Error?X.message:String(X)});throw X}}async abort(J){if(this.sendAbortTokens.set(J,Symbol()),this.abortProvisioningControllers(J,Error("Cloud session prompt cancelled")))return{sessionId:J,ok:!0};let Z=await this.ensureConnection(J),$=()=>{if(this.disposed||Z.disposed)throw Error("Cloud session connection was disposed")};if($(),await Z.client.connect(),await Z.reconnectResolution,$(),await this.resolveInnerSession(J,Z),Z.innerSessionId){await this.ensureAttached(Z),await Z.reconnectResolution,$();let Y=Z.innerSessionId;if(!Y)throw Error("Cloud Hub session was not initialized");await Z.client.command("run.abort",{sessionId:Y},Y,{beforeDispatch:()=>{if($(),Z.innerSessionId!==Y)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}$();let X=this.sessions.get(J);if(X)X.busy=!1,X.status="aborted";return this.publishSnapshot(J),{sessionId:J,ok:!0}}async pendingPrompts(J){if(this.knownSessions.get(J)?.status==="provisioning")return{sessionId:J,promptsInQueue:[]};if(!(await this.ensureConnection(J)).innerSessionId)return{sessionId:J,promptsInQueue:[]};let $=await this.queueCommand(J,"session.pending_prompts",{});return{sessionId:J,promptsInQueue:this.applyQueueSnapshot(J,$)}}async updatePendingPrompt(J,Z,$){let X=await this.queueCommand(J,"session.update_pending_prompt",{promptId:Z,...$});return{sessionId:J,updated:X.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot(J,X)}}async removePendingPrompt(J,Z){let $=await this.queueCommand(J,"session.remove_pending_prompt",{promptId:Z});return{sessionId:J,removed:$.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot(J,$)}}async queueCommand(J,Z,$){let X=await this.ensureConnection(J),Y=X.innerSessionId;if(!Y)throw Error("Cloud Hub session was not initialized");await X.client.connect(),await X.reconnectResolution,await this.ensureAttached(X),await X.reconnectResolution;let Q=await X.client.command(Z,{sessionId:Y,...$},Y,{beforeDispatch:()=>{if(this.assertSessionActive(J,X),X.innerSessionId!==Y)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive(J,X),Q}applyQueueSnapshot(J,Z){if(!Array.isArray(Z.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let X=Z.payload.prompts.map((Q)=>({id:typeof Q.id==="string"?Q.id:"",prompt:typeof Q.prompt==="string"?Q.prompt:"",steer:Q.delivery==="steer",attachmentCount:typeof Q.attachmentCount==="number"?Q.attachmentCount:0,userImages:Array.isArray(Q.userImages)?Q.userImages.filter((j)=>typeof j==="string"):void 0})).filter((Q)=>Q.id),Y=this.sessions.get(J);if(Y)Y.promptsInQueue=X;return this.publishSnapshot(J,!1,"queue"),X}async readMessages(J){let Z=this.knownSessions.get(J);if(Z?.status==="provisioning"||Z?.status==="failed")return[];if(Z&&R(Z))return await this.loadArchivedMessages(Z)??[];try{let $=await this.ensureConnection(J);if(!$.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop(J,$)).messages}catch($){let X=await this.refreshKnownSession(J)??Z;if(X){let Y=await this.loadArchivedMessages(X).catch(()=>null);if(Y!==null)return Y}throw $}}async updateTitle(J,Z){let $=this.titleWrites.get(J),X=(async()=>{await $?.catch(()=>{}),this.assertSessionActive(J),await this.options.api.updateTitle(J,Z);let Y=this.knownSessions.get(J);if(Y)Y.title=Z;let Q=this.sessions.get(J);if(Q)Q.title=Z;this.publishSnapshot(J)})();this.titleWrites.set(J,X);try{await X}finally{if(this.titleWrites.get(J)===X)this.titleWrites.delete(J)}}async delete(J){this.deletingSessions.add(J),this.abortProvisioningControllers(J);try{let Z=this.connectionPromises.get(J);if(Z)await Z.catch(()=>{return});await this.disposeConnection(J);try{await this.options.api.delete(J)}catch($){let X=$ instanceof L?$.code:"";if(X!=="session_not_found"&&X!=="session_expired")throw $}this.knownSessions.delete(J),this.unlistedSessions.delete(J),this.pendingInitialTasks.delete(J),this.sessions.delete(J),this.authoritativeMessages.delete(J),this.restoredOptions.delete(J),this.publish({type:"removed",sessionId:J}),this.sendAbortTokens.delete(J);for(let[$,X]of this.approvals)if(X.item.sessionId===J)this.approvals.delete($)}finally{this.deletingSessions.delete(J)}}async dispose(){this.disposed=!0;for(let Z of this.snapshotTimers.keys())this.cancelScheduledSnapshot(Z);this.sendAbortTokens.clear();for(let Z of this.provisioningControllers.values())for(let $ of Z)$.abort();this.provisioningControllers.clear();let J=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[Z,$]of this.approvals)if(J.has($.item.sessionId))this.approvals.delete(Z);for(let Z of J)this.sessions.delete(Z),this.knownSessions.delete(Z),this.publish({type:"removed",sessionId:Z});if(this.knownSessions.clear(),this.unlistedSessions.clear(),!this.options.pendingInitialTasks)this.pendingInitialTasks.clear();this.listeners.clear(),await Promise.allSettled(Array.from(this.connections.keys()).map((Z)=>this.disposeConnection(Z)))}async attachExpired(J){let Z=this.sessions.get(J.id)??x0(J);return Z.busy=!1,Z.status="expired",this.sessions.set(J.id,Z),await this.loadArchivedMessages(J).catch(()=>{return}),P0(J,"expired")}async loadArchivedMessages(J){let Z=this.sessionGenerations.get(J.id),$=await this.options.api.history(J.id);if(this.assertSessionActive(J.id),this.sessionGenerations.get(J.id)!==Z)throw Error("Cloud session attachment changed while loading history");if($===null)return null;let X=this.sessions.get(J.id)??x0(J);return X.messages=structuredClone($),this.sessions.set(J.id,X),this.authoritativeMessages.set(J.id,structuredClone(X.messages)),this.publishSnapshot(J.id,!0),$}async refreshKnownSession(J){let Z=await this.resolveActiveOrganizationId(),$=await this.options.api.list(Z).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!$)return this.knownSessions.get(J);for(let X of $)this.knownSessions.set(X.id,X);return $.find((X)=>X.id===J)}async ensureKnownSession(J){let Z=this.knownSessions.get(J);if(Z)return Z;let $=(await this.list()).find((X)=>X.id===J);if(!$)throw new L("session_not_found",`Cloud session ${J} was not found.`);return this.knownSessions.get(J)??structuredClone($)}assertSessionActive(J,Z){if(this.disposed||Z?.disposed||this.detachedSessions.has(J)||Z?.generation!==void 0&&Z.generation!==(this.sessionGenerations.get(J)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has(J))throw new L("session_not_found","This cloud session is being deleted.")}async ensureConnection(J,Z={}){let $=this.sessionGenerations.get(J)??0,X=()=>{if(this.assertSessionActive(J),$!==(this.sessionGenerations.get(J)??0))throw Error("Cloud viewer detached during connection")};X();let Y=this.connectionPromises.get(J),Q=Y?await Y:this.connections.get(J);if(Q){if(this.assertSessionActive(J,Q),await Q.reconnectResolution,this.assertSessionActive(J,Q),!Q.innerSessionId)await Q.client.connect(),await Q.reconnectResolution,this.assertSessionActive(J,Q),await this.resolveInnerSession(J,Q),this.assertSessionActive(J,Q);if(Z.createInner&&!Q.innerSessionId)await this.createInnerSession(Q);return this.assertSessionActive(J,Q),Q}let j=(async()=>{let V=await this.ensureKnownSession(J);if(X(),V.status==="provisioning"){let W=new AbortController,q=this.trackProvisioningController(J,W);try{if(await this.options.api.waitUntilReady(J,W.signal,({phase:F})=>{V.metadata.provisioningPhase=F,this.notify("chat_session_status",{sessionId:J,status:"provisioning",phase:F})}),this.disposed)throw Error("Cloud session manager was disposed");if(V=await this.refreshKnownSession(J)??V,W.signal.throwIfAborted(),V.status==="provisioning")V.status="ready";let z=this.sessions.get(J);if(z?.status==="provisioning")z.status="idle"}catch(z){if(z instanceof L&&z.code==="session_failed"){if(V.status="failed",V.metadata.statusReason=z.detail,V.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set(J,V);let F=this.sessions.get(J);if(F)F.status="error";this.notify("chat_session_status",{sessionId:J,status:"error"})}throw z}finally{q()}}if(X(),V.status==="failed")throw new L("session_failed",V.metadata.statusReason||"The cloud sandbox could not be prepared.");if(R(V))throw new L("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set(J,this.sessions.get(J)??this.stateFromRecord(V));let G,N=0,K=this.createHubClient({url:h5(this.options.apiBaseUrl,J),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${J}-${w5()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:O,cwd:O,resolveConnectionHeaders:async()=>{X();let W=N>0;if(N+=1,G)G.connected=!1,G.reconnecting=W,this.publishSnapshot(J);if(W){let z=G;if(z&&!z.disposed){z.transcriptKnown=!1,z.innerSessionId=void 0;let F=(async()=>{if(await this.resolveInnerSession(J,z),z.innerSessionId)await this.rehydrateAfterTransportDrop(J,z)})().catch(()=>this.disposeConnectionIfSessionGone(J,z)).finally(()=>{if(z.reconnectResolution===F)z.reconnectResolution=void 0,z.connected=z.transcriptKnown,this.publishSnapshot(J)});z.reconnectResolution=F}}let q=await this.options.getAuthToken();if(!q?.trim())throw new L("authentication_required","Sign in to Cline to reconnect this cloud session.");return X(),{Authorization:`Bearer ${q.trim()}`}}});G={generation:$,remote:V,client:K,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},G.unsubscribe=K.subscribe(()=>{},{sessionId:V.metadata.taskId?.trim()||J}),this.connections.set(J,G);try{if(await K.connect(),G.connected=!0,this.publishSnapshot(J),this.assertSessionActive(J,G),await this.resolveInnerSession(J,G),this.assertSessionActive(J,G),Z.createInner&&!G.innerSessionId)await this.createInnerSession(G);return this.assertSessionActive(J,G),G}catch(W){if(O1(W)&&!this.disposed&&!G.disposed&&!this.deletingSessions.has(J))throw W;if(this.connections.get(J)===G)this.connections.delete(J);if(G.disposed=!0,G.unsubscribe(),!this.disposed&&$===(this.sessionGenerations.get(J)??0))this.clearPendingApprovals(J);throw await K.dispose().catch(()=>{return}),W}})().finally(()=>{if(this.connectionPromises.get(J)===j)this.connectionPromises.delete(J)});return this.connectionPromises.set(J,j),await j}async resolveInnerSession(J,Z){if(this.assertSessionActive(J,Z),Z.innerSessionId)return;let $=Z.remote.metadata.taskId?.trim(),X;if($)try{let j=await Z.client.command("session.get",{sessionId:$},$);this.assertSessionActive(J,Z),X=j.payload?.session&&typeof j.payload.session==="object"&&!Array.isArray(j.payload.session)?j.payload.session:void 0}catch(j){if(!k0(j))throw j}else{let j=await Z.client.command("session.list",{limit:100});this.assertSessionActive(J,Z),X=M1(j.payload).filter(_1).sort((V,G)=>_0(G)-_0(V))[0]}let Y=String(X?.sessionId??"").trim();if(!Y){if(!this.pendingInitialTasks.has(J))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}this.pendingInitialTasks.delete(J),Z.innerSessionId=Y,this.subscribeToInnerSession(J,Z);let Q=f0(X);if(Q)this.applyModel(Z,Q);await this.ensureAttached(Z)}async createInnerSession(J){if(this.assertSessionActive(J.remote.id,J),J.innerSessionId)return;if(J.innerSessionCreation)return await J.innerSessionCreation;let Z=this.createInnerSessionOnce(J).finally(()=>{J.innerSessionCreation=void 0});return J.innerSessionCreation=Z,await Z}async createInnerSessionOnce(J){let Z=J.remote.metadata.modelId?.trim();if(!Z)throw Error("Cloud session is missing its model id");let $=this.sessions.get(J.remote.id),X=`cline/${(J.remote.metadata.taskId?.trim()||J.remote.id).slice(-8).toLowerCase()}`,Y=`${b5}
|
|
7
|
+
`)}if(J&&typeof J==="object"){let Z=J;if(typeof Z.text==="string")return Z.text}return""}function P6(J){let Z=J0(J??void 0);if(!Z)return;return Z.split(`
|
|
8
|
+
`)[0]?.trim().slice(0,70)||void 0}function R6(J){for(let Z of["user","assistant"])for(let $ of J){if(!$||typeof $!=="object")continue;let X=$;if(X.role!==Z)continue;let Y=J0(H0(X.content));if(!Y)continue;return Y.split(`
|
|
9
|
+
`)[0]?.trim().slice(0,70)||void 0}return}function O0(J){let Z=J.metadata&&typeof J.metadata==="object"?J0(J.metadata.title):void 0;if(Z)return Z.slice(0,70);let $=P6(J.prompt);if($)return $;let X=J.messages?R6(J.messages):void 0;if(X)return X;return`Session ${J.sessionId.slice(-6)}`}function O1(J,Z,$,X){let Y=Z.payload??{},Q=()=>{let V=$.get(X);if(V===void 0||!J.messages[V]||J.messages[V]?.role!=="assistant")V=J.messages.length,J.messages.push({role:"assistant",content:[]}),$.set(X,V);let G=J.messages[V];if(!Array.isArray(G.content))G.content=[];return G.content},j=(V,G,N)=>{let K=Q(),W=K.at(-1);if(W?.type===V)W[G]=`${W[G]??""}${N}`;else K.push({type:V,[G]:N})};switch(Z.event){case"assistant.delta":if(typeof Y.text==="string")j("text","text",Y.text);return;case"reasoning.delta":if(typeof Y.text==="string"&&Y.text)j("thinking","thinking",Y.text);else if(Y.redacted===!0)Q().push({type:"redacted_thinking",data:""});return;case"assistant.finished":$.delete(X);return;case"assistant.media":if(Y.media)Q().push({type:"media",media:structuredClone(Y.media)});return;case"tool.started":{let V=String(Y.toolCallId??"");if(V&&!J.messages.some((G)=>Array.isArray(G.content)&&G.content.some((N)=>N.type==="tool_use"&&N.id===V)))Q().push({type:"tool_use",id:V,name:String(Y.toolName??"tool"),input:structuredClone(Y.input??{})});return}case"tool.finished":{let V=String(Y.toolCallId??"");if(V&&!J.messages.some((G)=>Array.isArray(G.content)&&G.content.some((N)=>N.type==="tool_result"&&N.tool_use_id===V)))J.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:V,content:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output??""),is_error:Boolean(Y.error)}]}),$.delete(X);return}case"usage.updated":J.usage=structuredClone(Y.totals??Y.delta??{});return;case"session.pending_prompts":{let V=Array.isArray(Y.prompts)?Y.prompts:[];J.promptsInQueue=V.map((G)=>({id:String(G.id??""),prompt:String(G.prompt??""),steer:G.delivery==="steer",attachmentCount:typeof G.attachmentCount==="number"?G.attachmentCount:0,userImages:Array.isArray(G.userImages)?G.userImages.filter((N)=>typeof N==="string"):void 0})).filter((G)=>G.id&&(G.prompt||G.attachmentCount));return}case"session.pending_prompt_submitted":{let V=Y.prompt,G=String(V?.id??"");if(!G||J.lastQueuedPromptStartId===G)return;if(J.lastQueuedPromptStartId=G,J.promptsInQueue=J.promptsInQueue.filter((N)=>N.id!==G),Y.transcriptReflected!==!0)J.messages.push({role:"user",content:[{type:"text",text:String(V?.prompt??"")}]});J.busy=!0,J.status="running",J.endedAt=void 0,$.delete(X);return}case"run.started":case"session.attached":case"session.updated":{if(typeof Z.sequence==="number"&&J.lastHubStatusSequence!==void 0&&Z.sequence<J.lastHubStatusSequence)return;if(typeof Z.sequence==="number")J.lastHubStatusSequence=Z.sequence;let V=Y.session,G=typeof V?.status==="string"?V.status:Z.event==="run.started"?"running":J.status,N=G==="pending"?"running":G;if(Z.event==="session.updated"&&N==="running"&&J.endedAt!==void 0&&!J.busy)return;let K=J.busy;if(J.status=N,J.busy=N==="running",Z.event==="run.started"){if(!K)$.delete(X);J.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof Z.sequence==="number"&&J.lastHubStatusSequence!==void 0&&Z.sequence<J.lastHubStatusSequence)return;if(typeof Z.sequence==="number")J.lastHubStatusSequence=Z.sequence;J.status=typeof Y.reason==="string"?Y.reason:Z.event==="run.failed"?"error":Z.event==="run.aborted"?"aborted":"completed",J.busy=!1,J.endedAt=Date.now(),$.delete(X);return}}}function x1(J){return J instanceof Error&&J.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String(J.code))}function P1(J,Z){return J instanceof Error&&J.name==="HubCommandError"&&J.code==="hub_command_timeout"&&(!Z||J.command===Z)}var O="/workspace",T6=30000,C6=2000,E6=2000,b6="IMPORTANT: GitHub authentication is handled automatically by the infrastructure. An egress proxy transparently injects credentials into all GitHub traffic. You do NOT need to set up, configure, or manage any tokens, API keys, or credentials, and you must never run `gh auth login` or attempt to authenticate manually. "+"The GitHub CLI (`gh`) is installed and already authenticated — prefer it for GitHub work "+"(`gh pr create`, `gh pr diff`, `gh issue list`, `gh api`, ...). `git` push and pull are authenticated the same way. "+"Simply run the commands normally — credentials are injected transparently.";class w1 extends L{constructor(){super("request_failed","The connection was interrupted and Cline could not confirm whether this message was queued. Check the cloud session before resending it.");this.name="CloudQueueUnconfirmedError"}}function R(J){let Z=J.expiredAt?Date.parse(J.expiredAt):Number.NaN;return Number.isFinite(Z)&&Z<=Date.now()}function k6(J){return J.trim().startsWith("ses-")}function h6(J,Z){let $=new URL(`/api/v1/session/${encodeURIComponent(Z)}`,J);return $.protocol=$.protocol==="https:"?"wss:":"ws:",$.toString()}function x0(J){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:J.metadata.modelId??"",modelId:J.metadata.modelId??"",repoUrl:J.repoContext.repoUrl??"",branch:J.repoContext.branch??"",cwd:O,workspaceRoot:O},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse(J.createdAt)||Date.now(),endedAt:R(J)&&J.expiredAt?Date.parse(J.expiredAt):void 0,status:J.status,attachedViaHub:!0}}function P0(J,Z,$){return{sessionId:J.id,origin:"cloud",executionTarget:"cloud",status:Z,provider:"cline",model:J.metadata.modelId??"",repoUrl:J.repoContext.repoUrl??"",branch:J.repoContext.branch??"",cwd:O,workspaceRoot:O,...$?.trim()?{prompt:$.trim()}:{},metadata:{origin:"cloud",repoUrl:J.repoContext.repoUrl??"",git:{url:J.repoContext.repoUrl??"",branch:J.repoContext.branch??""}}}}function R1(J){return{sessionId:J.id,origin:"cloud",executionTarget:"cloud",status:J.status,provider:"cline",model:J.metadata.modelId??"",cwd:O,workspaceRoot:O,repoUrl:J.repoContext.repoUrl??"",branch:J.repoContext.branch??"",startedAt:J.createdAt,...J.lastActivityAt?{lastActivityAt:J.lastActivityAt}:{},endedAt:R(J)?J.expiredAt??void 0:J.status==="failed"?J.lastActivityAt??J.createdAt:void 0,updatedAt:J.updatedAt,...J.title?.trim()?{title:J.title.trim()}:{},metadata:{...J.title?.trim()?{title:J.title.trim()}:{},origin:"cloud",...J.metadata.provisioningPhase?{provisioningPhase:J.metadata.provisioningPhase}:{},repoUrl:J.repoContext.repoUrl??"",git:{url:J.repoContext.repoUrl??"",branch:J.repoContext.branch??""}}}}function g6(J){if(typeof J!=="string")return J;try{return JSON.parse(J)}catch{return J}}function y6(J,Z){let $=[...J??[]],X=new Set($.map((Y)=>Y.id));for(let Y of Z)if(!X.has(Y.id))$.push(Y);return $}class v6{options;sessionGenerations=new Map;sessions=new Map;approvals=new Map;listeners=new Set;detachedSessions=new Set;restoredOptions=new Map;authoritativeMessages=new Map;streamingMessages=new Map;disposed=!1;connections=new Map;connectionPromises=new Map;knownSessions=new Map;unlistedSessions=new Map;pendingInitialTasks;lastListedSessions=[];discoveryRefresh;createRequests=new Map;provisioningControllers=new Map;sendAbortTokens=new Map;titleWrites=new Map;deletingSessions=new Set;createHubClient;constructor(J){this.options=J;this.pendingInitialTasks=J.pendingInitialTasks??new Map,this.createHubClient=J.createHubClient??((Z)=>new I(Z))}restoreCreationOptions(J,Z){if(this.restoredOptions.set(J,structuredClone(Z)),this.pendingInitialTasks.has(J))this.pendingInitialTasks.set(J,{...this.pendingInitialTasks.get(J),...structuredClone(Z)});let $=this.sessions.get(J);if($)Object.assign($.config,structuredClone(Z))}seedSessionState(J,Z){if(!this.sessions.has(J))this.sessions.set(J,structuredClone(Z))}stateFromRecord(J){let Z=x0(J);return Object.assign(Z.config,this.pendingInitialTasks.get(J.id),this.restoredOptions.get(J.id)),Z}getSnapshot(J){let Z=this.knownSessions.get(J),$=this.sessions.get(J)??(Z?this.stateFromRecord(Z):void 0);if(!$)return;let X=this.connections.get(J);return e({...$,sessionId:J,record:Z,approvals:Array.from(this.approvals.values()).filter((Y)=>Y.item.sessionId===J).map((Y)=>Y.item),connectionState:this.detachedSessions.has(J)||this.disposed?"detached":X?.reconnectResolution||X?.rehydrationPromise?"reconnecting":X?X.connected?"connected":X.reconnecting?"reconnecting":"connecting":this.connectionPromises.has(J)?"connecting":"detached",transcriptKnown:X?.transcriptKnown??Boolean(Z&&R(Z))})}subscribe(J,Z){let $=(X)=>{if(!Z||X.sessionId===Z)J(X)};return this.listeners.add($),()=>{this.listeners.delete($)}}publish(J){let Z=J.type==="snapshot"?Object.freeze(J):e(J);for(let $ of this.listeners)try{$(Z)}catch(X){this.options.logger?.error?.("Cloud session subscriber failed",{error:X})}}publishSnapshot(J,Z=!1,$){this.cancelScheduledSnapshot(J);let X=this.getSnapshot(J);if(X)this.publish({type:"snapshot",sessionId:J,snapshot:X,replace:Z,cause:$});else this.publish({type:"removed",sessionId:J})}snapshotTimers=new Map;cancelScheduledSnapshot(J){clearTimeout(this.snapshotTimers.get(J)),this.snapshotTimers.delete(J)}scheduleSnapshot(J){if(this.disposed||this.detachedSessions.has(J)||this.snapshotTimers.has(J))return;let Z=setTimeout(()=>this.publishSnapshot(J),100);Z.unref?.(),this.snapshotTimers.set(J,Z)}notify(J,Z){let $=String(Z.sessionId??"");if(J==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:$,message:String(Z.message??"Cloud synchronization failed")});else this.publishSnapshot($,J==="cloud_session_rehydrated",J==="chat_session_status"?"status":J==="chat_session_ended"?"ended":J==="tool_approval_state"?"approvals":void 0)}applyLiveEvent(J,Z){let $=this.sessions.get(J);if($)O1($,Z,this.streamingMessages,J)}async respondApproval(J,Z,$){this.assertSessionActive(J);let X=this.approvals.get(`${J}:${Z}`);if(!X){if(!this.connections.has(J))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new L("request_failed","This approval was already resolved or is no longer available.")}await X.resolve($)}async detach(J){this.detachedSessions.add(J),this.sessionGenerations.set(J,(this.sessionGenerations.get(J)??0)+1),this.connectionPromises.delete(J),this.sendAbortTokens.set(J,Symbol()),this.abortProvisioningControllers(J,Error("Cloud viewer detached")),await this.disposeConnection(J),this.publishSnapshot(J)}isCloudSession(J){return k6(J)||this.knownSessions.has(J)||this.connections.has(J)||this.sessions.get(J)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord(J){let Z=this.knownSessions.get(J);return Z?R1(Z):void 0}async getCrossScopeDiscoveryRecord(J){let Z=this.getCachedDiscoveryRecord(J);if(!Z)return;try{let X=(await this.options.api.status(J)).status?.trim();return X?{...Z,status:X}:Z}catch($){if($ instanceof L&&($.code==="session_not_found"||$.code==="session_expired")){this.knownSessions.delete(J),this.unlistedSessions.delete(J),this.pendingInitialTasks.delete(J);return}return Z}}async list(){if(this.disposed)throw Error("Cloud session controller was disposed");let J=await this.resolveActiveOrganizationId(),Z=(await this.options.api.list(J)).map((X)=>this.preserveConnectedRuntimeModel(X));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=Z;for(let X of Z)this.knownSessions.set(X.id,X),this.unlistedSessions.delete(X.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(X)=>this.getCrossScopeDiscoveryRecord(X)));let $=await Promise.all(Z.map(async(X)=>{if(X.status!=="provisioning")return X;let Y=await this.options.api.status(X.id).catch(()=>{return}),Q=Y?.status?.trim();if(!Q)return X;return{...X,status:Q,metadata:{...X.metadata,...Q0(Y?.phase)?{provisioningPhase:Y?.phase}:{},...Y?.statusReason?.trim()?{statusReason:Y.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let X of $){this.knownSessions.set(X.id,X);let Y=this.sessions.get(X.id);if(Y?.status==="provisioning"&&X.status!=="provisioning")Y.status=X.status;let Q=this.connections.get(X.id);if(Q)Q.remote=X;let j=R(X);if(j||X.status==="failed"){if(Y)Y.busy=!1,Y.status=j?"expired":"failed",Y.endedAt=j?Date.parse(X.expiredAt??"")||Date.now():Math.max(Y.endedAt??0,Date.parse(X.lastActivityAt??X.createdAt)||0)||void 0;if(Q)this.disposeConnection(X.id).catch(()=>{return})}}this.lastListedSessions=$;for(let X of $)if(this.sessions.has(X.id))this.publishSnapshot(X.id);return e($)}preserveConnectedRuntimeModel(J){let Z=this.connections.get(J.id)?.remote.metadata.modelId?.trim();if(!Z||Z===J.metadata.modelId)return J;return{...J,metadata:{...J.metadata,modelId:Z}}}async resolveActiveOrganizationId(J){return await this.options.getActiveOrganizationId?.(J)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listBranches(J,Z={}){return await this.options.api.listBranches(J,await this.resolveActiveOrganizationId(),Z)}async listForDiscovery(J={}){let Z=this.discoveryRefresh??this.list().finally(()=>{if(this.discoveryRefresh===Z)this.discoveryRefresh=void 0});this.discoveryRefresh=Z;let $=this.lastListedSessions;if(J.timeoutMs===void 0)$=await Z;else{let Q,j=await Promise.race([Z.then((V)=>({value:V}),(V)=>{if(!(V instanceof L&&V.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:V});return{value:this.lastListedSessions}}),new Promise((V)=>{Q=setTimeout(()=>V({value:this.lastListedSessions}),Math.max(0,J.timeoutMs??0))})]);if(Q)clearTimeout(Q);$=j.value}return[...new Map([...this.unlistedSessions.values(),...$].map((Q)=>[Q.id,Q])).values()].map((Q)=>{let j=R1(Q),V=this.sessions.get(Q.id);if(!V)return j;let G=V.title?.trim()||Q.title?.trim();return{...j,status:V.status,prompt:V.prompt,endedAt:V.endedAt!==void 0?new Date(V.endedAt).toISOString():j.endedAt,metadata:{...j.metadata??{},title:O0({sessionId:Q.id,metadata:G?{title:G}:void 0,prompt:V.prompt,messages:V.messages})}}})}async create(J){let Z=J.requestId?.trim();if(!Z)return await this.createOnce(J);let $=this.createRequests.get(Z);if($)return await $;let X=this.createOnce(J).finally(()=>{if(this.createRequests.get(Z)===X)this.createRequests.delete(Z)});return this.createRequests.set(Z,X),await X}trackProvisioningController(J,Z){let $=this.provisioningControllers.get(J);if(!$)$=new Set,this.provisioningControllers.set(J,$);return $.add(Z),()=>{if($.delete(Z),$.size===0)this.provisioningControllers.delete(J)}}abortProvisioningControllers(J,Z){let $=this.provisioningControllers.get(J);if(!$?.size)return!1;for(let X of $)X.abort(Z);return!0}async createOnce(J){if(this.disposed)throw Error("Cloud session manager was disposed");let Z=J.organizationId??await this.resolveActiveOrganizationId({fresh:!0}),$=await this.options.api.create({...J,organizationId:Z});if(!$?.sessionId?.trim())throw new L("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose($.sessionId,$.cleanupAuthToken);throw Error("Cline account changed while the cloud session was starting")}let X={id:$.sessionId,status:$.status,sandboxUrl:$.sandboxUrl,repoContext:{repoUrl:J.repoUrl,...J.branch?.trim()?{branch:J.branch.trim()}:{}},metadata:{modelId:J.modelId},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.knownSessions.set(X.id,X),this.unlistedSessions.set(X.id,X);let{autoApproveTools:Y,thinking:Q,reasoningEffort:j}=J;this.pendingInitialTasks.set(X.id,{autoApproveTools:Y,thinking:Q,reasoningEffort:j});let V=this.stateFromRecord(X);return V.prompt=J.initialPrompt?.trim()||void 0,this.sessions.set(X.id,V),this.notify("chat_session_status",{sessionId:X.id,status:V.status}),{sessionId:X.id,origin:"cloud",executionTarget:"cloud",status:X.status,provider:"cline",model:J.modelId,repoUrl:J.repoUrl,branch:J.branch??"",cwd:O,workspaceRoot:O,...V.prompt?{prompt:V.prompt}:{}}}async deleteProvisionedSessionAfterDispose(J,Z){this.knownSessions.delete(J),this.unlistedSessions.delete(J),this.pendingInitialTasks.delete(J),this.sessions.delete(J),await this.options.api.delete(J,Z).catch(($)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:J,error:$})})}async attach(J,Z){let $=this.sessionGenerations.get(J)??0;if(this.detachedSessions.delete(J),Z)this.restoreCreationOptions(J,Z);let X=await this.ensureKnownSession(J);if(this.assertSessionActive(J),$!==(this.sessionGenerations.get(J)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has(J))this.sessions.set(J,this.stateFromRecord(X));if(X.status==="provisioning"||X.status==="failed")return P0(X,X.status,this.sessions.get(J)?.prompt);if(R(X))return await this.disposeConnection(J),await this.attachExpired(X);let Y;try{Y=await this.ensureConnection(J)}catch(V){let G=await this.refreshKnownSession(J);if(G&&R(G))return await this.disposeConnection(J),await this.attachExpired(G);throw V}await this.ensureAttached(Y);let Q=Y.remote,j=this.sessions.get(J);return P0(Q,j?.status??Q.status,j?.prompt)}async send(J,Z,$,X,Y){let Q=this.sendAbortTokens.get(J),j=this.knownSessions.get(J);if(j&&R(j))throw new L("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let V=await this.ensureConnection(J,{createInner:!0}),G=()=>this.disposed||V.disposed||this.deletingSessions.has(J)||this.sendAbortTokens.get(J)!==Q,N=()=>{if(G())throw Error("Cloud session prompt cancelled")};if(N(),await V.reconnectResolution,N(),await this.ensureAttached(V),await V.reconnectResolution,N(),!V.transcriptKnown)await this.rehydrateAfterTransportDrop(J,V);N(),await this.updateModel(V,X),await V.reconnectResolution,N();let K=V.innerSessionId;if(!K)throw Error("Cloud Hub session was not initialized");let W=this.sessions.get(J),q=$??(W?.busy?"queue":void 0),z=p(W?.messages??[],W?.promptsInQueue??[],Z),F=q!=="queue"&&q!=="steer",A=W&&q!=="queue"?{role:"user",content:[{type:"text",text:Z}]}:void 0;if(W&&A)W.messages=[...W.messages,A];let B=()=>{if(W&&A)W.messages=W.messages.filter((D)=>D!==A),this.publishSnapshot(J)};if(W&&F){let D=W.status!=="running";if(W.busy=!0,W.status="running",W.prompt||=Z,D)this.publishSnapshot(J,!1,"status")}let M=this.knownSessions.get(J);if(M&&!M.title?.trim()&&!this.titleWrites.has(J)){let D=E0(Z);if(D){if(M.title=D,W)W.title=D;let H=this.options.api.updateTitle?.(J,D).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get(J)===H)this.titleWrites.delete(J)});if(H)this.titleWrites.set(J,H)}}let _=new Set,x=!1,T=()=>{if(x||G())return;x=!0,this.publish({type:"prompt_accepted",sessionId:J,prompt:Z,delivery:q})};try{let D=await V.client.command("session.send_input",{prompt:Z,delivery:q,...Y?.length?{attachments:{userImages:Y}}:{}},K,{timeoutMs:q==="queue"?T6:null,onDispatch:(E)=>{_.add(E),V.pendingInputs??=new Map,V.pendingInputs.set(E,{clientId:V.client.getClientId(),ownsBusyState:F,accept:T})},beforeDispatch:()=>{if(N(),V.innerSessionId!==K)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.")}});T();let H=q==="queue"||q!=="steer"&&D.payload?.result===void 0;if(H)B();return{sessionId:J,ok:!0,...H?{queued:!0}:{},result:D.payload?.result}}catch(D){if(G())throw B(),D;if(x1(D)||P1(D,"session.send_input")){let H;try{H=await this.rehydrateAfterTransportDrop(J,V)}catch(l){if(N(),B(),W&&F)W.busy=!1,W.status="error";if(q==="queue")throw new w1;throw l}if(N(),q==="queue"||q==="steer")throw new L("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(p(H.messages,y6(H.prompts,H.submittedPrompts),Z)<=z)throw new L("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:J,ok:!0,...q==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:H.status}}if(B(),W&&F)W.busy=!1,W.status="error";throw this.publishSnapshot(J),D}finally{for(let D of _)V.pendingInputs?.delete(D)}}async updateModel(J,Z){let $=Z?.trim();if(!$||J.remote.metadata.modelId===$)return;let X=J.innerSessionId;if(!X)throw Error("Cloud Hub session was not initialized");await J.client.command("session.update_connection",{sessionId:X,updates:{modelId:$}},X,{beforeDispatch:()=>{if(this.assertSessionActive(J.remote.id,J),J.innerSessionId!==X)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive(J.remote.id,J),this.applyModel(J,$)}applyModel(J,Z){J.remote.metadata.modelId=Z;let $=this.sessions.get(J.remote.id);if($)$.config.model=Z,$.config.modelId=Z}async rehydrateAfterTransportDrop(J,Z){if(this.assertSessionActive(J,Z),Z.rehydrationPromise)return Z.rehydrationRerunRequested=!0,await Z.rehydrationPromise;let $=(async()=>{let X;do Z.rehydrationRerunRequested=!1,X=await this.performTransportRehydration(J,Z),this.assertSessionActive(J,Z);while(Z.rehydrationRerunRequested&&!this.disposed);return X})().finally(()=>{if(Z.rehydrationPromise===$)Z.rehydrationPromise=void 0,this.publishSnapshot(J)});return Z.rehydrationPromise=$,await $}async performTransportRehydration(J,Z){this.assertSessionActive(J,Z);let $=Z.innerSessionId;if(!$)throw Error("Cloud Hub session was not initialized");Z.bufferingEvents=!0,Z.bufferedEvents=[],Z.bufferedEventsDropped=0;try{await this.ensureAttached(Z),this.assertSessionActive(J,Z);let X=await Z.client.command("session.get",{includeSnapshot:!0},$);this.assertSessionActive(J,Z);let Y=X.payload?.session&&typeof X.payload.session==="object"&&!Array.isArray(X.payload.session)?X.payload.session:void 0;this.applySessionModel(Z,Y);let Q=this.sessions.get(J),j=this.authoritativeMessages.get(J)??[],V=String(Y?.status??Q?.status??"running").trim(),G=V==="pending"?"running":V;if(G==="running"&&!Z.transcriptKnown&&!Z.pendingInputs?.size)Z.externalRun??={progressHydrated:!0};let N=()=>Z.client.command("session.messages",{sessionId:$},$),K=await N().catch((D)=>{if(!P1(D,"session.messages"))throw D;return this.assertSessionActive(J,Z),N()});if(this.assertSessionActive(J,Z),!Array.isArray(K.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let W=K.payload.messages,q=Z.bufferedEventsDropped+Z.bufferedEvents.length,z=await Z.client.command("session.pending_prompts",{sessionId:$},$).catch(()=>{return});this.assertSessionActive(J,Z);let F=Z.bufferedEventsDropped+Z.bufferedEvents.length;if(Q){let D=Q.status!==G;if(this.authoritativeMessages.set(J,structuredClone(W)),Q.messages=structuredClone(W),this.streamingMessages.delete(J),Q.status=G,Q.busy=G==="running",D)if(G==="completed"||G==="failed"||G==="aborted")Q.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:J,reason:G==="failed"?"error":G});else this.notify("chat_session_status",{sessionId:J,status:G})}let A=z!==void 0&&z.ok!==!1&&Array.isArray(z.payload?.prompts),B=A?this.applyQueueSnapshot(J,z):void 0;Z.transcriptKnown=!0;let M=W;this.assertSessionActive(J,Z),this.notify("cloud_session_rehydrated",{sessionId:J,status:G,transcriptKnown:!0,messages:M}),this.assertSessionActive(J,Z);let _=Z.bufferedEvents,x=U0(_),T=H1(_,W,{queueSnapshotApplied:A,queueSnapshotEventCutoff:Math.max(0,F-Z.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,q-Z.bufferedEventsDropped),baselineMessages:j});Z.bufferedEvents=[],Z.bufferingEvents=!1,Z.syncFailureNotified=!1;for(let D of T)this.forwardEvent(J,Z,D);return{status:G,messages:W,prompts:B,submittedPrompts:x}}catch(X){let Y=Z.bufferedEvents;Z.bufferedEvents=[],Z.bufferingEvents=!1,this.assertSessionActive(J,Z);for(let Q of Y)this.forwardEvent(J,Z,Q);if(!Z.syncFailureNotified)Z.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:J,message:X instanceof Error?X.message:String(X)});throw X}}async abort(J){if(this.sendAbortTokens.set(J,Symbol()),this.abortProvisioningControllers(J,Error("Cloud session prompt cancelled")))return{sessionId:J,ok:!0};let Z=await this.ensureConnection(J),$=()=>{if(this.disposed||Z.disposed)throw Error("Cloud session connection was disposed")};if($(),await Z.client.connect(),await Z.reconnectResolution,$(),await this.resolveInnerSession(J,Z),Z.innerSessionId){await this.ensureAttached(Z),await Z.reconnectResolution,$();let Y=Z.innerSessionId;if(!Y)throw Error("Cloud Hub session was not initialized");await Z.client.command("run.abort",{sessionId:Y},Y,{beforeDispatch:()=>{if($(),Z.innerSessionId!==Y)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}$();let X=this.sessions.get(J);if(X)X.busy=!1,X.status="aborted";return this.publishSnapshot(J),{sessionId:J,ok:!0}}async pendingPrompts(J){if(this.knownSessions.get(J)?.status==="provisioning")return{sessionId:J,promptsInQueue:[]};if(!(await this.ensureConnection(J)).innerSessionId)return{sessionId:J,promptsInQueue:[]};let $=await this.queueCommand(J,"session.pending_prompts",{});return{sessionId:J,promptsInQueue:this.applyQueueSnapshot(J,$)}}async updatePendingPrompt(J,Z,$){let X=await this.queueCommand(J,"session.update_pending_prompt",{promptId:Z,...$});return{sessionId:J,updated:X.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot(J,X)}}async removePendingPrompt(J,Z){let $=await this.queueCommand(J,"session.remove_pending_prompt",{promptId:Z});return{sessionId:J,removed:$.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot(J,$)}}async queueCommand(J,Z,$){let X=await this.ensureConnection(J),Y=X.innerSessionId;if(!Y)throw Error("Cloud Hub session was not initialized");await X.client.connect(),await X.reconnectResolution,await this.ensureAttached(X),await X.reconnectResolution;let Q=await X.client.command(Z,{sessionId:Y,...$},Y,{beforeDispatch:()=>{if(this.assertSessionActive(J,X),X.innerSessionId!==Y)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive(J,X),Q}applyQueueSnapshot(J,Z){if(!Array.isArray(Z.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let X=Z.payload.prompts.map((Q)=>({id:typeof Q.id==="string"?Q.id:"",prompt:typeof Q.prompt==="string"?Q.prompt:"",steer:Q.delivery==="steer",attachmentCount:typeof Q.attachmentCount==="number"?Q.attachmentCount:0,userImages:Array.isArray(Q.userImages)?Q.userImages.filter((j)=>typeof j==="string"):void 0})).filter((Q)=>Q.id),Y=this.sessions.get(J);if(Y)Y.promptsInQueue=X;return this.publishSnapshot(J,!1,"queue"),X}async readMessages(J){let Z=this.knownSessions.get(J);if(Z?.status==="provisioning"||Z?.status==="failed")return[];if(Z&&R(Z))return await this.loadArchivedMessages(Z)??[];try{let $=await this.ensureConnection(J);if(!$.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop(J,$)).messages}catch($){let X=await this.refreshKnownSession(J)??Z;if(X){let Y=await this.loadArchivedMessages(X).catch(()=>null);if(Y!==null)return Y}throw $}}async updateTitle(J,Z){let $=this.titleWrites.get(J),X=(async()=>{await $?.catch(()=>{}),this.assertSessionActive(J),await this.options.api.updateTitle(J,Z);let Y=this.knownSessions.get(J);if(Y)Y.title=Z;let Q=this.sessions.get(J);if(Q)Q.title=Z;this.publishSnapshot(J)})();this.titleWrites.set(J,X);try{await X}finally{if(this.titleWrites.get(J)===X)this.titleWrites.delete(J)}}async delete(J){this.deletingSessions.add(J),this.abortProvisioningControllers(J);try{let Z=this.connectionPromises.get(J);if(Z)await Z.catch(()=>{return});await this.disposeConnection(J);try{await this.options.api.delete(J)}catch($){let X=$ instanceof L?$.code:"";if(X!=="session_not_found"&&X!=="session_expired")throw $}this.knownSessions.delete(J),this.unlistedSessions.delete(J),this.pendingInitialTasks.delete(J),this.sessions.delete(J),this.authoritativeMessages.delete(J),this.restoredOptions.delete(J),this.publish({type:"removed",sessionId:J}),this.sendAbortTokens.delete(J);for(let[$,X]of this.approvals)if(X.item.sessionId===J)this.approvals.delete($)}finally{this.deletingSessions.delete(J)}}async dispose(){this.disposed=!0;for(let Z of this.snapshotTimers.keys())this.cancelScheduledSnapshot(Z);this.sendAbortTokens.clear();for(let Z of this.provisioningControllers.values())for(let $ of Z)$.abort();this.provisioningControllers.clear();let J=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[Z,$]of this.approvals)if(J.has($.item.sessionId))this.approvals.delete(Z);for(let Z of J)this.sessions.delete(Z),this.knownSessions.delete(Z),this.publish({type:"removed",sessionId:Z});if(this.knownSessions.clear(),this.unlistedSessions.clear(),!this.options.pendingInitialTasks)this.pendingInitialTasks.clear();this.listeners.clear(),await Promise.allSettled(Array.from(this.connections.keys()).map((Z)=>this.disposeConnection(Z)))}async attachExpired(J){let Z=this.sessions.get(J.id)??x0(J);return Z.busy=!1,Z.status="expired",this.sessions.set(J.id,Z),await this.loadArchivedMessages(J).catch(()=>{return}),P0(J,"expired")}async loadArchivedMessages(J){let Z=this.sessionGenerations.get(J.id),$=await this.options.api.history(J.id);if(this.assertSessionActive(J.id),this.sessionGenerations.get(J.id)!==Z)throw Error("Cloud session attachment changed while loading history");if($===null)return null;let X=this.sessions.get(J.id)??x0(J);return X.messages=structuredClone($),this.sessions.set(J.id,X),this.authoritativeMessages.set(J.id,structuredClone(X.messages)),this.publishSnapshot(J.id,!0),$}async refreshKnownSession(J){let Z=await this.resolveActiveOrganizationId(),$=await this.options.api.list(Z).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!$)return this.knownSessions.get(J);for(let X of $)this.knownSessions.set(X.id,X);return $.find((X)=>X.id===J)}async ensureKnownSession(J){let Z=this.knownSessions.get(J);if(Z)return Z;let $=(await this.list()).find((X)=>X.id===J);if(!$)throw new L("session_not_found",`Cloud session ${J} was not found.`);return this.knownSessions.get(J)??structuredClone($)}assertSessionActive(J,Z){if(this.disposed||Z?.disposed||this.detachedSessions.has(J)||Z?.generation!==void 0&&Z.generation!==(this.sessionGenerations.get(J)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has(J))throw new L("session_not_found","This cloud session is being deleted.")}async ensureConnection(J,Z={}){let $=this.sessionGenerations.get(J)??0,X=()=>{if(this.assertSessionActive(J),$!==(this.sessionGenerations.get(J)??0))throw Error("Cloud viewer detached during connection")};X();let Y=this.connectionPromises.get(J),Q=Y?await Y:this.connections.get(J);if(Q){if(this.assertSessionActive(J,Q),await Q.reconnectResolution,this.assertSessionActive(J,Q),!Q.innerSessionId)await Q.client.connect(),await Q.reconnectResolution,this.assertSessionActive(J,Q),await this.resolveInnerSession(J,Q),this.assertSessionActive(J,Q);if(Z.createInner&&!Q.innerSessionId)await this.createInnerSession(Q);return this.assertSessionActive(J,Q),Q}let j=(async()=>{let V=await this.ensureKnownSession(J);if(X(),V.status==="provisioning"){let W=new AbortController,q=this.trackProvisioningController(J,W);try{if(await this.options.api.waitUntilReady(J,W.signal,({phase:F})=>{V.metadata.provisioningPhase=F,this.notify("chat_session_status",{sessionId:J,status:"provisioning",phase:F})}),this.disposed)throw Error("Cloud session manager was disposed");if(V=await this.refreshKnownSession(J)??V,W.signal.throwIfAborted(),V.status==="provisioning")V.status="ready";let z=this.sessions.get(J);if(z?.status==="provisioning")z.status="idle"}catch(z){if(z instanceof L&&z.code==="session_failed"){if(V.status="failed",V.metadata.statusReason=z.detail,V.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set(J,V);let F=this.sessions.get(J);if(F)F.status="error";this.notify("chat_session_status",{sessionId:J,status:"error"})}throw z}finally{q()}}if(X(),V.status==="failed")throw new L("session_failed",V.metadata.statusReason||"The cloud sandbox could not be prepared.");if(R(V))throw new L("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set(J,this.sessions.get(J)??this.stateFromRecord(V));let G,N=0,K=this.createHubClient({url:h6(this.options.apiBaseUrl,J),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${J}-${w6()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:O,cwd:O,resolveConnectionHeaders:async()=>{X();let W=N>0;if(N+=1,G)G.connected=!1,G.reconnecting=W,this.publishSnapshot(J);if(W){let z=G;if(z&&!z.disposed){z.transcriptKnown=!1,z.innerSessionId=void 0;let F=(async()=>{if(await this.resolveInnerSession(J,z),z.innerSessionId)await this.rehydrateAfterTransportDrop(J,z)})().catch(()=>this.disposeConnectionIfSessionGone(J,z)).finally(()=>{if(z.reconnectResolution===F)z.reconnectResolution=void 0,z.connected=z.transcriptKnown,this.publishSnapshot(J)});z.reconnectResolution=F}}let q=await this.options.getAuthToken();if(!q?.trim())throw new L("authentication_required","Sign in to Cline to reconnect this cloud session.");return X(),{Authorization:`Bearer ${q.trim()}`}}});G={generation:$,remote:V,client:K,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},G.unsubscribe=K.subscribe(()=>{},{sessionId:V.metadata.taskId?.trim()||J}),this.connections.set(J,G);try{if(await K.connect(),G.connected=!0,this.publishSnapshot(J),this.assertSessionActive(J,G),await this.resolveInnerSession(J,G),this.assertSessionActive(J,G),Z.createInner&&!G.innerSessionId)await this.createInnerSession(G);return this.assertSessionActive(J,G),G}catch(W){if(x1(W)&&!this.disposed&&!G.disposed&&!this.deletingSessions.has(J))throw W;if(this.connections.get(J)===G)this.connections.delete(J);if(G.disposed=!0,G.unsubscribe(),!this.disposed&&$===(this.sessionGenerations.get(J)??0))this.clearPendingApprovals(J);throw await K.dispose().catch(()=>{return}),W}})().finally(()=>{if(this.connectionPromises.get(J)===j)this.connectionPromises.delete(J)});return this.connectionPromises.set(J,j),await j}async resolveInnerSession(J,Z){if(this.assertSessionActive(J,Z),Z.innerSessionId)return;let $=Z.remote.metadata.taskId?.trim(),X;if($)try{let j=await Z.client.command("session.get",{sessionId:$},$);this.assertSessionActive(J,Z),X=j.payload?.session&&typeof j.payload.session==="object"&&!Array.isArray(j.payload.session)?j.payload.session:void 0}catch(j){if(!k0(j))throw j}else{let j=await Z.client.command("session.list",{limit:100});this.assertSessionActive(J,Z),X=_1(j.payload).filter(f1).sort((V,G)=>_0(G)-_0(V))[0]}let Y=String(X?.sessionId??"").trim();if(!Y){if(!this.pendingInitialTasks.has(J))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}this.pendingInitialTasks.delete(J),Z.innerSessionId=Y,this.subscribeToInnerSession(J,Z);let Q=f0(X);if(Q)this.applyModel(Z,Q);await this.ensureAttached(Z)}async createInnerSession(J){if(this.assertSessionActive(J.remote.id,J),J.innerSessionId)return;if(J.innerSessionCreation)return await J.innerSessionCreation;let Z=this.createInnerSessionOnce(J).finally(()=>{J.innerSessionCreation=void 0});return J.innerSessionCreation=Z,await Z}async createInnerSessionOnce(J){let Z=J.remote.metadata.modelId?.trim();if(!Z)throw Error("Cloud session is missing its model id");let $=this.sessions.get(J.remote.id),X=`cline/${(J.remote.metadata.taskId?.trim()||J.remote.id).slice(-8).toLowerCase()}`,Y=`${b6}
|
|
10
10
|
|
|
11
|
-
SAVE YOUR WORK: This sandbox is temporary. Push your progress to origin so it remains available outside the sandbox. The branch \`${X}\` is a backup of your work-in-progress, not a finished deliverable, so commit to it freely even when the work is incomplete. Do all work for this task on that branch: create it from the current checkout before your first change (or check it out if it already exists), and never commit directly to the default branch. Commit regularly as you complete meaningful steps, using clear, descriptive messages. The first time you commit, push the branch with \`git push -u origin ${X}\`, and push again after each later commit. Do not force-push or amend commits that are already pushed unless the user explicitly asks.`,Q=await J.client.command("session.create",{workspaceRoot:O,cwd:O,sessionConfig:{...J.remote.metadata.taskId?.trim()?{sessionId:J.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:Z,workspaceRoot:O,cwd:O,systemPrompt:Y,mode:"act",enableTools:!0,...typeof $?.config.thinking==="boolean"?{thinking:$.config.thinking}:{},...typeof $?.config.reasoningEffort==="string"?{reasoningEffort:$.config.reasoningEffort}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:Z,interactive:!0},runtimeOptions:{mode:"act"},modelSelection:{provider:"cline",model:Z},toolPolicies:{"*":{autoApprove:$?.config.autoApproveTools!==!1}}});this.assertSessionActive(J.remote.id,J);let j=Q.payload?.session&&typeof Q.payload.session==="object"?Q.payload.session:void 0,V=String(j?.sessionId??Q.payload?.sessionId??"").trim();if(!V)throw Error("Cloud Hub did not return an inner session id");J.innerSessionId=V,this.subscribeToInnerSession(J.remote.id,J),this.pendingInitialTasks.delete(J.remote.id),this.applySessionModel(J,j),J.transcriptKnown=!0}handleEvent(J,Z,$){if(this.disposed||Z.disposed)return;if(Z.innerSessionId&&$.sessionId&&$.sessionId!==Z.innerSessionId)return;let X=$.eventId?.trim();if(X&&!($.event==="approval.requested"&&$.sequence===void 0)){if(Z.seenEventIds.has(X))return;Z.seenEventIds.add(X);while(Z.seenEventIds.size>
|
|
11
|
+
SAVE YOUR WORK: This sandbox is temporary. Push your progress to origin so it remains available outside the sandbox. The branch \`${X}\` is a backup of your work-in-progress, not a finished deliverable, so commit to it freely even when the work is incomplete. Do all work for this task on that branch: create it from the current checkout before your first change (or check it out if it already exists), and never commit directly to the default branch. Commit regularly as you complete meaningful steps, using clear, descriptive messages. The first time you commit, push the branch with \`git push -u origin ${X}\`, and push again after each later commit. Do not force-push or amend commits that are already pushed unless the user explicitly asks.`,Q=await J.client.command("session.create",{workspaceRoot:O,cwd:O,sessionConfig:{...J.remote.metadata.taskId?.trim()?{sessionId:J.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:Z,workspaceRoot:O,cwd:O,systemPrompt:Y,mode:"act",enableTools:!0,...typeof $?.config.thinking==="boolean"?{thinking:$.config.thinking}:{},...typeof $?.config.reasoningEffort==="string"?{reasoningEffort:$.config.reasoningEffort}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:Z,interactive:!0},runtimeOptions:{mode:"act"},modelSelection:{provider:"cline",model:Z},toolPolicies:{"*":{autoApprove:$?.config.autoApproveTools!==!1}}});this.assertSessionActive(J.remote.id,J);let j=Q.payload?.session&&typeof Q.payload.session==="object"?Q.payload.session:void 0,V=String(j?.sessionId??Q.payload?.sessionId??"").trim();if(!V)throw Error("Cloud Hub did not return an inner session id");J.innerSessionId=V,this.subscribeToInnerSession(J.remote.id,J),this.pendingInitialTasks.delete(J.remote.id),this.applySessionModel(J,j),J.transcriptKnown=!0}handleEvent(J,Z,$){if(this.disposed||Z.disposed)return;if(Z.innerSessionId&&$.sessionId&&$.sessionId!==Z.innerSessionId)return;let X=$.eventId?.trim();if(X&&!($.event==="approval.requested"&&$.sequence===void 0)){if(Z.seenEventIds.has(X))return;Z.seenEventIds.add(X);while(Z.seenEventIds.size>E6){let Y=Z.seenEventIds.values().next().value;if(Y)Z.seenEventIds.delete(Y)}}if(Z.bufferingEvents){if(Z.bufferedEvents.push($),Z.bufferedEvents.length>C6)Z.bufferedEvents.shift(),Z.bufferedEventsDropped+=1,this.options.logger?.log("Cloud sync event buffer reached its limit",{sessionId:J,severity:"warn"});return}this.forwardEvent(J,Z,$)}forwardEvent(J,Z,$){if(this.disposed||Z.disposed)return;if($.event==="session.attached"||$.event==="session.updated"||$.event==="session.created")this.applySessionModel(Z,$.payload?.session);if($.event==="approval.requested"){this.handleApprovalRequested(J,Z,$);return}if($.event==="approval.resolved"){let j=String($.payload?.approvalId??"").trim();if(j)this.removeApproval(J,j);return}if($.event==="run.started"){let j=this.sessions.get(J)?.busy,V=$.payload?.requestId,G=typeof V==="string"?Z.pendingInputs?.get(V):void 0;if(G&&$.payload?.clientId===G.clientId){if(G.accept(),G.ownsBusyState)Z.externalRun=void 0}else if(typeof $.payload?.clientId==="string")Z.externalRun??={progressHydrated:Boolean(j)}}let X=Z.externalRun,Y=$.event==="run.completed"||$.event==="run.failed"||$.event==="run.aborted",Q=X&&!X.progressHydrated&&($.event==="assistant.delta"||$.event==="reasoning.delta"||$.event==="tool.started");if(X&&(Q||Y)){if(X.progressHydrated=!0,Y)Z.externalRun=void 0;let j=Boolean(Z.rehydrationPromise);if(this.rehydrateAfterTransportDrop(J,Z).catch((V)=>{if(this.disposed||Z.disposed)return;this.notify("cloud_session_sync_failed",{sessionId:J,message:V instanceof Error?V.message:"Cloud transcript refresh failed"})}),!j){Z.bufferedEvents.push($);return}}if(this.applyLiveEvent(J,$),this.publish({type:"hub_event",sessionId:J,event:{...$,sessionId:J}}),$.event==="assistant.delta"||$.event==="reasoning.delta"||$.event==="tool.updated")this.scheduleSnapshot(J);else this.publishSnapshot(J)}handleApprovalRequested(J,Z,$){this.storePendingApproval(J,Z,$.payload),this.sendApprovalSnapshot(J)}storePendingApproval(J,Z,$){let X=String($?.approvalId??"").trim();if(!X)return;let Y=`${J}:${X}`,Q={approvalId:X,requestId:Y,sessionId:J,createdAt:new Date(typeof $?.createdAt==="number"?$.createdAt:Date.now()).toISOString(),toolCallId:String($?.toolCallId??""),toolName:String($?.toolName??"tool"),input:g6($?.inputJson),iteration:typeof $?.iteration==="number"?$.iteration:void 0,agentId:typeof $?.agentId==="string"?$.agentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0};this.approvals.set(Y,{item:Q,resolve:async(j)=>{if(this.disposed||Z.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");if(await this.ensureAttached(Z),this.disposed||Z.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");await Z.client.command("approval.respond",{approvalId:X,approved:j.approved,reason:j.reason},Z.innerSessionId)}})}removeApproval(J,Z){this.approvals.delete(`${J}:${Z}`),this.sendApprovalSnapshot(J)}clearPendingApprovals(J){for(let[Z,$]of this.approvals)if($.item.sessionId===J)this.approvals.delete(Z);this.sendApprovalSnapshot(J)}sendApprovalSnapshot(J){this.notify("tool_approval_state",{sessionId:J,items:Array.from(this.approvals.values()).filter((Z)=>Z.item.sessionId===J).map((Z)=>Z.item)})}async ensureAttached(J){if(this.assertSessionActive(J.remote.id,J),!J.innerSessionId)return;let Z=await J.client.command("session.attach",{sessionId:J.innerSessionId},J.innerSessionId);this.assertSessionActive(J.remote.id,J),this.applySessionModel(J,Z.payload?.session)}subscribeToInnerSession(J,Z){let $=Z.innerSessionId;if(!$)return;Z.unsubscribe(),this.clearPendingApprovals(J),Z.unsubscribe=Z.client.subscribe((X)=>this.handleEvent(J,Z,X),{sessionId:$})}applySessionModel(J,Z){if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let $=f0(Z);if($)this.applyModel(J,$)}async disposeConnection(J){this.cancelScheduledSnapshot(J);let Z=this.connections.get(J);if(this.connections.delete(J),!Z)return;Z.disposed=!0,Z.pendingInputs?.clear(),Z.unsubscribe(),this.clearPendingApprovals(J),await Z.client.dispose()}async disposeConnectionIfSessionGone(J,Z){if(Z.disposed||this.disposed)return;let $;try{$=await this.resolveActiveOrganizationId()}catch{return}let X=await this.options.api.list($).catch(()=>{return});if(!X||Z.disposed)return;let Y=X.find((j)=>j.id===J),Q=Y?this.preserveConnectedRuntimeModel(Y):void 0;if(!Q){await this.disposeConnection(J).catch(()=>{return});return}if(this.knownSessions.set(J,Q),Z.remote=Q,Q.status==="failed"){let j=this.sessions.get(J);if(j)j.busy=!1,j.status="failed",j.endedAt=Date.parse(Q.updatedAt)||Date.now();await this.disposeConnection(J).catch(()=>{return});return}if(R(Q))await this.attachExpired(Q).catch(()=>{return}),await this.disposeConnection(J).catch(()=>{return})}}export{_0 as updatedAt,U0 as submittedPromptsFromEvents,H0 as stringifyMessageContent,f0 as sessionRowModelId,O0 as resolveSessionListTitle,H1 as reconcileBufferedCloudEvents,_1 as readSessionRows,Q0 as parseCloudProvisioningPhase,J0 as normalizeSessionTitle,f1 as isRootSessionRow,k6 as isCloudOuterSessionId,E0 as deriveCloudSessionTitle,p as countPromptOccurrences,R1 as cloudSessionToDiscoveryRecord,L as CloudSessionError,v6 as CloudSessionController,v1 as CloudSessionApi,w1 as CloudQueueUnconfirmedError};
|
|
@@ -31,6 +31,11 @@ export interface LocalHubResolutionOptions {
|
|
|
31
31
|
strategy?: "prefer-hub" | "require-hub";
|
|
32
32
|
workspaceRoot?: string;
|
|
33
33
|
cwd?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Called with the error when starting a detached Hub fails. The function
|
|
36
|
+
* still resolves `undefined` in that case; this lets a caller report why.
|
|
37
|
+
*/
|
|
38
|
+
onStartupError?: (error: unknown) => void;
|
|
34
39
|
}
|
|
35
40
|
export type HubTransportErrorCode = "hub_connect_timeout" | "hub_connect_failed" | "hub_connection_closed" | "hub_connection_not_open";
|
|
36
41
|
export declare class HubTransportError extends Error {
|