@cline/core 0.0.86-nightly.1790649045 → 0.0.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,21 @@
1
- import{execFile as J2}from"node:child_process";import{basename as P6,resolve as Z2}from"node:path";import{promisify as X2}from"node:util";import{processWorkspaceInfo as x6}from"@cline/shared";import i0 from"simple-git";var Q2=X2(J2);function V2($,J){return Q2("git",$,{cwd:J.cwd,encoding:"utf8",windowsHide:!0,signal:J.signal,timeout:15000,maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND||"ssh -o BatchMode=yes"}})}function i($){if(!$||typeof $!=="object"||!("stderr"in $))return"";return typeof $.stderr==="string"?$.stderr.trim():""}function t($){if(!$||typeof $!=="object"||!("code"in $))return;return typeof $.code==="number"?$.code:void 0}function t0($){let J=r0($.cwd),Z=$.git??V2,X=async(V)=>(await Z(V,{cwd:J,signal:$.signal})).stdout,Q=async(V)=>(await X(V)).trim();return{async isInsideWorkTree(){try{return await Q(["rev-parse","--is-inside-work-tree"])==="true"}catch(V){if(t(V)===128&&/not a git repository|Kein Git-Repository/i.test(i(V)))return!1;throw V}},remotes:()=>i0({baseDir:J}).getRemotes(!0),displayBranch:async()=>(await i0({baseDir:J}).branch()).current.trim(),symbolicBranch:()=>Q(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>Q(["rev-parse","HEAD"]),workspacePrefix:async()=>(await X(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>Q(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(V)=>Q(["config","--get",`branch.${V}.remote`]),branchMergeRef:(V)=>Q(["config","--get",`branch.${V}.merge`]),remoteUrl:(V)=>Q(["remote","get-url",V]),remoteRefs:(V,j)=>Q(["ls-remote","--exit-code",V,j])}}function r0($){return Z2($)}class C extends Error{code;constructor($,J,Z){super(J,Z);this.code=$;this.name="CloudHandoffGitPreflightError"}}function s0($){let J=0,Z=$.length;while(J<Z&&$[J]==="/")J+=1;while(Z>J&&$[Z-1]==="/")Z-=1;let X=$.slice(J,Z);return X.toLowerCase().endsWith(".git")?X.slice(0,-4):X}function n0($){let J=$.trim();if(!J)return null;let Z=J.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(Z?.[1]){let X=s0(Z[1]);return X.split("/").length===2?`https://github.com/${X}`:null}try{let X=new URL(J);if(X.hostname.toLowerCase()!=="github.com")return null;if(!new Set(["https:","http:","ssh:","git:"]).has(X.protocol))return null;let Q=s0(X.pathname);return Q.split("/").length===2?`https://github.com/${Q}`:null}catch{return null}}async function y($,J,Z){try{return await $()}catch(X){let Q=i(X);throw new C(J,Q?`${Z} (${Q})`:Z,{cause:X})}}function Y2($,J){let Z=`refs/heads/${J}`;for(let X of $.split(`
2
- `)){let[Q,V]=X.trim().split(/\s+/,2);if(V===Z&&/^[0-9a-f]{40,64}$/i.test(Q??""))return Q??null}return null}function j2($){let J=$.replace(/[\r\n]+$/,"").replace(/\/+$/,"");if(!J)return;let Z=J.split("/");if(J.startsWith("/")||Z.some((X)=>!X||X==="."||X===".."))throw new C("git_command_failed","Could not resolve the workspace path relative to the Git repository.");return J}async function f6($){let J=t0($);if(!await y(J.isInsideWorkTree,"not_git_repository","Cloud handoff requires a Git repository."))throw new C("not_git_repository","Cloud handoff requires a Git working tree.");let X=j2(await y(J.workspacePrefix,"git_command_failed","Could not resolve the workspace path relative to the Git repository.")),Q=await y(J.worktreeStatus,"git_command_failed","Could not inspect the Git worktree.");if(Q){let F=Q.split(`
3
- `).filter(Boolean),q=F.slice(0,5).join(`
4
- `),O=F.length>5?`
5
- ...and ${F.length-5} more`:"";throw new C("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
1
+ import{execFile as nn}from"node:child_process";import{basename as Po,resolve as sn}from"node:path";import{promisify as on}from"node:util";import{processWorkspaceInfo as xo}from"@cline/shared";import Ve from"simple-git";var rn=on(nn);function an(e,t){return rn("git",e,{cwd:t.cwd,encoding:"utf8",windowsHide:!0,signal:t.signal,timeout:15000,maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND||"ssh -o BatchMode=yes"}})}function V(e){if(!e||typeof e!=="object"||!("stderr"in e))return"";return typeof e.stderr==="string"?e.stderr.trim():""}function K(e){if(!e||typeof e!=="object"||!("code"in e))return;return typeof e.code==="number"?e.code:void 0}function Ke(e){let t=Qe(e.cwd),n=e.git??an,s=async(i)=>(await n(i,{cwd:t,signal:e.signal})).stdout,o=async(i)=>(await s(i)).trim();return{async isInsideWorkTree(){try{return await o(["rev-parse","--is-inside-work-tree"])==="true"}catch(i){if(K(i)===128&&/not a git repository|Kein Git-Repository/i.test(V(i)))return!1;throw i}},remotes:()=>Ve({baseDir:t}).getRemotes(!0),displayBranch:async()=>(await Ve({baseDir:t}).branch()).current.trim(),symbolicBranch:()=>o(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>o(["rev-parse","HEAD"]),workspacePrefix:async()=>(await s(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>o(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(i)=>o(["config","--get",`branch.${i}.remote`]),branchMergeRef:(i)=>o(["config","--get",`branch.${i}.merge`]),remoteUrl:(i)=>o(["remote","get-url",i]),remoteRefs:(i,a)=>o(["ls-remote","--exit-code",i,a])}}function Qe(e){return sn(e)}class _ extends Error{code;constructor(e,t,n){super(t,n);this.code=e;this.name="CloudHandoffGitPreflightError"}}function Ye(e){let t=0,n=e.length;while(t<n&&e[t]==="/")t+=1;while(n>t&&e[n-1]==="/")n-=1;let s=e.slice(t,n);return s.toLowerCase().endsWith(".git")?s.slice(0,-4):s}function Xe(e){let t=e.trim();if(!t)return null;let n=t.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(n?.[1]){let s=Ye(n[1]);return s.split("/").length===2?`https://github.com/${s}`:null}try{let s=new URL(t);if(s.hostname.toLowerCase()!=="github.com")return null;if(!new Set(["https:","http:","ssh:","git:"]).has(s.protocol))return null;let o=Ye(s.pathname);return o.split("/").length===2?`https://github.com/${o}`:null}catch{return null}}async function O(e,t,n){try{return await e()}catch(s){let o=V(s);throw new _(t,o?`${n} (${o})`:n,{cause:s})}}function dn(e,t){let n=`refs/heads/${t}`;for(let s of e.split(`
2
+ `)){let[o,i]=s.trim().split(/\s+/,2);if(i===n&&/^[0-9a-f]{40,64}$/i.test(o??""))return o??null}return null}function cn(e){let t=e.replace(/[\r\n]+$/,"").replace(/\/+$/,"");if(!t)return;let n=t.split("/");if(t.startsWith("/")||n.some((s)=>!s||s==="."||s===".."))throw new _("git_command_failed","Could not resolve the workspace path relative to the Git repository.");return t}async function Oo(e){let t=Ke(e);if(!await O(t.isInsideWorkTree,"not_git_repository","Cloud handoff requires a Git repository."))throw new _("not_git_repository","Cloud handoff requires a Git working tree.");let s=cn(await O(t.workspacePrefix,"git_command_failed","Could not resolve the workspace path relative to the Git repository.")),o=await O(t.worktreeStatus,"git_command_failed","Could not inspect the Git worktree.");if(o){let u=o.split(`
3
+ `).filter(Boolean),g=u.slice(0,5).join(`
4
+ `),y=u.length>5?`
5
+ ...and ${u.length-5} more`:"";throw new _("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
6
6
 
7
- ${q}${O}`)}let V;try{V=await J.symbolicBranch()}catch(F){let q=t(F)===1,O=i(F),B=q?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new C(q?"detached_head":"git_command_failed",O?`${B} (${O})`:B,{cause:F})}if(!V)throw new C("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[j,Y,W]=await Promise.all([y(()=>J.branchRemote(V),"missing_upstream",`Branch ${V} has no upstream. Push it with -u before handing off.`),y(()=>J.branchMergeRef(V),"missing_upstream",`Branch ${V} has no upstream. Push it with -u before handing off.`),y(J.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!j||j==="."||!Y.startsWith("refs/heads/"))throw new C("missing_upstream",`Branch ${V} has no remote branch upstream. Push it with -u before handing off.`);let K=Y.slice(11),G=j;if(!n0(j))try{G=await J.remoteUrl(j)}catch{throw new C("missing_upstream","Could not resolve the upstream remote.")}let N=n0(G);if(!N)throw new C("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let z;try{z=await J.remoteRefs(j,Y)}catch(F){let q=t(F)===2,O=q?`The upstream branch ${K} was not found. Push it before handing off.`:"Could not verify the remote branch. Check your network and GitHub authentication, then try again.";throw new C(q?"remote_branch_missing":"git_command_failed",O)}let L=Y2(z,K);if(!L)throw new C("remote_branch_missing",`The upstream branch ${K} was not found. Push it before handing off.`);if(L.toLowerCase()!==W.toLowerCase())throw new C("unpushed_commits",`Local HEAD does not match the upstream branch ${K}. Push the current commit before handing off.`);return{repoUrl:N,branch:K,headSha:W,...X?{workspaceRelativePath:X}:{}}}function K0($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function T($){if(typeof $!=="string")return;return $.trim()||void 0}function W2($){return typeof $==="string"&&$.length>0?$:void 0}function N2($){let J=T($.repoUrl),Z=T($.branch),X=T($.headSha),Q=T($.modelId);if(!J||!Z||!X||!Q)throw Error("Cloud handoff fingerprint fields cannot be empty.");let V=T($.organizationId),j=W2($.workspaceRelativePath),Y=$.mode;return{repoUrl:J,branch:Z,headSha:X,modelId:Q,...V?{organizationId:V}:{},...j?{workspaceRelativePath:j}:{},...Y?{mode:Y}:{}}}function k6($,J){return $!==void 0&&J!==void 0&&$.repoUrl===J.repoUrl&&$.branch===J.branch&&$.headSha.toLowerCase()===J.headSha.toLowerCase()&&$.modelId===J.modelId&&$.organizationId===J.organizationId&&$.workspaceRelativePath===J.workspaceRelativePath&&$.mode===J.mode}function F2($){let J=K0($);if(!J||typeof J.repoUrl!=="string"||typeof J.branch!=="string"||typeof J.headSha!=="string"||typeof J.modelId!=="string")return;try{return N2({repoUrl:J.repoUrl,branch:J.branch,headSha:J.headSha,modelId:J.modelId,...typeof J.organizationId==="string"?{organizationId:J.organizationId}:{},...typeof J.workspaceRelativePath==="string"?{workspaceRelativePath:J.workspaceRelativePath}:{},...J.mode==="plan"||J.mode==="yolo"||J.mode==="zen"?{mode:J.mode}:{}})}catch{return}}function y6($){let J=K0(K0($)?.handoff);if(!J)return;let Z=T(J.toCloudSessionId),X=T(J.handedOffAt),Q=J.status;if(!Z||!X||Q!=="pending"&&Q!=="complete")return;let V=T(J.innerSessionId),j=T(J.dashboardUrl),Y=F2(J.fingerprint);return{toCloudSessionId:Z,handedOffAt:X,status:Q,...V?{innerSessionId:V}:{},...j?{dashboardUrl:j}:{},...Y?{fingerprint:Y}:{}}}function g6($,J){return{...$??{},handoff:J}}function h6($){let{handoff:J,cloudHandoffIntent:Z,cloudHandoffSeedDispatched:X,...Q}=$??{};return Q}function v6($,J){let Z=J.trim();if(!Z)throw Error("Cloud session id cannot be empty.");let X=new URL("/agents",$);return X.searchParams.set("sessionId",Z),X.toString()}function o0($){return $.map((J)=>{let Z=J&&typeof J==="object"?J:{};return{role:Z.role,content:Z.content}})}function L0($,J){return $.length===J.length&&JSON.stringify(o0($))===JSON.stringify(o0(J))}class G0 extends Error{constructor($,J){super(`Cloud transcript verification failed (local ${$} messages, cloud ${J}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as K2}from"node:crypto";import{decodeJwtPayload as L2}from"@cline/shared";var G2=610000,z2=3000,S=15000,_2="CLOUD_SESSION_ERROR:",J1="__cline_create_request__:";function Z1($){return($.trim().split(`
8
- `)[0]??"").trim().slice(0,72)}class _ extends Error{code;detail;connectUrl;status;constructor($,J,Z,X){super(`${_2}${JSON.stringify({code:$,message:J,connectUrl:Z})}`);this.code=$;this.detail=J;this.connectUrl=Z;this.status=X;this.name="CloudSessionError"}}class X1 extends Error{constructor($){super($ instanceof Error?$.message:"Cloud handoff creation was rejected.",{cause:$});this.name="CloudHandoffCreationRejectedError"}}function q0($){let J=$.length;while(J>0&&$[J-1]==="/")J--;return $.slice(0,J)}function q2($){return`${J1}${$}`.slice(0,255)}function e0($){return $?.startsWith(J1)===!0}function O0($){switch($){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return $;default:return}}function z0($){let J=L2($.replace(/^workos:/,""));return typeof J?.sub==="string"&&J.sub.trim()?J.sub.trim():void 0}function $1($){return new Promise((J,Z)=>{if($.aborted){Z($.reason);return}let X=()=>{clearTimeout(Q),Z($.reason)},Q=setTimeout(()=>{$.removeEventListener("abort",X),J()},z2);$.addEventListener("abort",X,{once:!0})})}function O2($,J){if($&&typeof $==="object"){let Z=$.error;if(typeof Z==="string"&&Z.trim())return Z.trim()}return J}function _0($,J,Z,X){let Q=O2(J,`Cloud session request failed (${$})`);if($===401)return new _("authentication_required",Q);if($===404)return new _("session_not_found",Q);if($===410)return new _("session_expired",Q);if($===412)return new _("github_not_connected",Q,X??`${q0(Z)}/dashboard/integrations`);if($===403&&Q.trim().toLowerCase()==="forbidden")return new _("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,$);return new _("request_failed",Q,void 0,$)}class A2{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor($){this.options=$;this.apiBaseUrl=q0($.apiBaseUrl),this.appBaseUrl=q0($.appBaseUrl),this.fetchImpl=$.fetch??fetch,this.createTimeoutMs=$.createTimeoutMs??G2}async request($,J={},Z,X,Q){let V=!1,j;while(!0){let Y;try{Y=typeof X==="string"?X:await this.options.getAuthToken()}catch(G){if(j)throw _0(401,void 0,this.appBaseUrl,Z);throw G}if(!Y?.trim())throw new _("authentication_required","Sign in to Cline before starting a cloud session.");if(Y.trim()===j)throw new _("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof X==="object"){if(X.subject?z0(Y.trim())!==X.subject:Y.trim()!==X.token)throw new _("authentication_required","The signed-in account changed during cloud session creation.");X.token=Y.trim()}Q?.();let W=await this.fetchImpl(`${this.apiBaseUrl}${$}`,{...J,signal:J.signal??AbortSignal.timeout(S),headers:{Accept:"application/json",Authorization:`Bearer ${Y.trim()}`,...J.body?{"Content-Type":"application/json"}:{},...J.headers}}),K=W.status===204?void 0:await W.json().catch(()=>{return});if(!W.ok){if(W.status===401&&typeof X==="object"&&!V&&X.subject){V=!0,j=Y.trim();continue}throw _0(W.status,K,this.appBaseUrl,Z)}return K?.data}}async list($){return await this.listWithToken($)}async listWithToken($,J,Z=!1){let X=$?.trim()?`?organizationId=${encodeURIComponent($.trim())}`:"";return(await this.request(`/api/v1/session${X}`,{},void 0,J)??[]).flatMap((V)=>{if(!V||typeof V!=="object"||typeof V.id!=="string")return[];return[{...V,title:!Z&&e0(V.title)?void 0:V.title,repoContext:V.repoContext&&typeof V.repoContext==="object"?V.repoContext:{},metadata:{...V.metadata&&typeof V.metadata==="object"?V.metadata:{},...!Z&&e0(V.title)?{createRequestTitle:V.title}:{}}}]})}async listRepositories($){let J=$?.trim(),Z=J?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,X=J?`/api/v1/organizations/${encodeURIComponent(J)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let Q=await this.request(X)??[];return{connected:!0,connectUrl:Z,repositories:Q.flatMap((V)=>{let j=Number(V.id),Y=String(V.html_url??V.clone_url??"").trim();if(!Number.isSafeInteger(j)||j<=0||!Y)return[];let W=String(V.name??"").trim();return[{id:j,name:W,fullName:String(V.full_name??(W||Y)).trim(),url:Y,defaultBranch:String(V.default_branch??"").trim()}]})}}catch(Q){if(Q instanceof _&&Q.code==="session_not_found")return{connected:!1,connectUrl:Z,repositories:[]};throw Q}}async listBranches($,J,Z={}){if(!Number.isSafeInteger($)||$<=0)throw new _("request_failed","Select a GitHub repository before loading branches.");let X=J?.trim(),Q=X?`/api/v1/organizations/${encodeURIComponent(X)}/integrations/github/repositories/${$}/branches`:`/api/v1/integrations/github/repositories/${$}/branches`,V=new URLSearchParams,j=Z.query?.trim(),Y=Z.cursor?.trim();if(j)V.set("query",j);if(Y)V.set("cursor",Y);let W=V.size>0?`${Q}?${V}`:Q;try{let K=await this.request(W),G=Array.isArray(K)?K:Array.isArray(K?.items)?K.items:[],N=j?.toLowerCase();return{available:!0,branches:G.flatMap((z)=>{let L=String(z.name??"").trim();return L&&(!Array.isArray(K)||!N||L.toLowerCase().includes(N))?[L]:[]}),nextToken:Array.isArray(K)?"":String(K?.nextToken??"").trim()}}catch(K){if(K instanceof _&&K.code==="session_not_found")return{available:!1,branches:[]};throw K}}async status($,J={}){return await this.request(`/api/v1/session/${encodeURIComponent($)}/status`,{signal:J.signal?AbortSignal.any([J.signal,AbortSignal.timeout(S)]):void 0},void 0,J.authToken)}async create($){if($.handoff&&typeof $.handoff.onCreating!=="function")throw new _("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let J=(await this.options.getAuthToken())?.trim();if(!J)throw new _("authentication_required","Sign in to Cline before starting a cloud session.");let Z={token:J,subject:z0(J)},X=q2($.requestId?.trim()||K2()),Q=$.handoff?`${Z.subject??J}/${$.organizationId??""}/${$.requestId?.trim()??""}`:void 0;if($.handoff&&!$.requestId?.trim())throw new _("request_failed","A stable request id is required for cloud handoff creation.");let V=async()=>(await this.listWithToken($.organizationId??void 0,Z,!0)).filter((N)=>N.title===X&&N.repoContext.repoUrl===$.repoUrl&&N.metadata.modelId===$.modelId&&(!$.branch?.trim()||N.repoContext.branch===$.branch.trim())),j=async(N)=>{if(N.status==="failed"||N.expiredAt&&Date.parse(N.expiredAt)<=Date.now()){let L=new _(N.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(N.id,Z)}catch(F){if(!(F instanceof _&&(F.code==="session_not_found"||F.code==="session_expired")))throw AggregateError([L,F],"The unusable recovered cloud handoff workspace could not be removed.")}if(Q)this.unconfirmedHandoffCreates.delete(Q),this.completedHandoffCreates.delete(Q);throw await $.handoff?.onOuterSessionRemoved?.(N.id),L}await $.handoff?.onOuterSessionCreated(N.id,{created:!1});let z={sessionId:N.id,status:N.status,sandboxUrl:N.sandboxUrl,cleanupAuthToken:Z.token};if(Q)this.unconfirmedHandoffCreates.delete(Q),this.completedHandoffCreates.set(Q,z);return z};if(Q){let N=await V();if(N.length>1)throw new _("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(N[0])return await j(N[0]);let z=this.completedHandoffCreates.get(Q);if(z){try{await this.request(`/api/v1/session/${encodeURIComponent(z.sessionId)}/status`,{},void 0,Z)}catch(L){if(L instanceof _&&(L.code==="session_not_found"||L.code==="session_expired"))await $.handoff?.onOuterSessionRemoved?.(z.sessionId),this.completedHandoffCreates.delete(Q),this.unconfirmedHandoffCreates.delete(Q);throw L}return await $.handoff?.onOuterSessionCreated(z.sessionId,{created:!1}),{...z,cleanupAuthToken:Z.token}}if(this.unconfirmedHandoffCreates.has(Q))throw new _("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(Q)}try{await $.handoff?.onCreating()}catch(N){if(Q)this.unconfirmedHandoffCreates.delete(Q);throw N}let Y=new AbortController,W=setTimeout(()=>Y.abort(),this.createTimeoutMs),K,G=!1;try{let N=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:$.modelId,repoUrl:$.repoUrl,...$.sandboxType?{sandboxType:$.sandboxType}:{},title:X,...$.branch?.trim()?{branch:$.branch.trim()}:{},...$.organizationId?.trim()?{organizationId:$.organizationId.trim()}:{}}),signal:Y.signal},$.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,Z,()=>{G=!0}),z=N?.sessionId?.trim();if(!z)throw new _("request_failed","The cloud session service returned no session id.");K=z,await this.persistHandoffOuterSession($,z,Z,Q);let L={sessionId:z,status:N.status?.trim()||"provisioning",sandboxUrl:N.sandboxUrl?.trim()??"",cleanupAuthToken:Z.token};if(Q)this.unconfirmedHandoffCreates.delete(Q),this.completedHandoffCreates.set(Q,L);return L}catch(N){if(K)throw N;let z=!G||N instanceof _&&(N.status!==void 0&&N.status>=400&&N.status<500&&N.status!==408&&N.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(N.code));if(Q&&z)throw this.unconfirmedHandoffCreates.delete(Q),new X1(N);if(Y.signal.aborted||!(N instanceof _)||N instanceof _&&N.code==="request_failed"&&(N.status===void 0||N.status>=500||N.status===408||N.status===409)){let F=[];try{F=await V()}catch(O){if($.handoff)throw AggregateError([N,O],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(F.length>1)throw new _("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let q=F[0];if(q){if($.handoff)return await j(q);return{sessionId:q.id,status:q.status,sandboxUrl:q.sandboxUrl,cleanupAuthToken:Z.token}}}else if(Q)this.unconfirmedHandoffCreates.delete(Q);throw N}finally{clearTimeout(W)}}async persistHandoffOuterSession($,J,Z,X){if(!$.handoff)return;try{await $.handoff.onOuterSessionCreated(J,{created:!0})}catch(Q){try{await this.deleteWithAuth(J,Z.token)}catch(V){if(!(V instanceof _&&(V.code==="session_not_found"||V.code==="session_expired")))throw AggregateError([Q,V],`Cloud session ${J} was created but its recovery record could not be saved or its sandbox removed.`)}if(X)this.unconfirmedHandoffCreates.delete(X);throw await $.handoff.onOuterSessionRemoved?.(J),Q}}async waitUntilReady($,J,Z){J=AbortSignal.any([J,AbortSignal.timeout(this.createTimeoutMs)]);let X=await this.options.getAuthToken(),Q=X?{token:X,subject:z0(X)}:void 0;while(!J.aborted){let V;try{V=await this.request(`/api/v1/session/${encodeURIComponent($)}/status`,{signal:AbortSignal.any([J,AbortSignal.timeout(S)])},void 0,Q)}catch(Y){if(J.aborted)throw Y;if(Y instanceof _&&Y.code!=="request_failed")throw Y;await $1(J);continue}let j=V?.status?.trim().toLowerCase();if(Z?.({phase:O0(V?.phase)}),j==="ready"||j==="active")return;if(j==="failed")throw new _("session_failed",V?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(j!=="provisioning")throw new _("request_failed","The cloud session service returned an unexpected provisioning status.");await $1(J)}throw J.reason}async resume($,J){return await this.request(`/api/v1/session/${encodeURIComponent($)}/resume`,{method:"POST",signal:J?AbortSignal.any([J,AbortSignal.timeout(S)]):void 0})}async delete($,J){await this.deleteWithAuth($,J)}async deleteWithAuth($,J){let Z;try{await this.request(`/api/v1/session/${encodeURIComponent($)}`,{method:"DELETE"},void 0,J)}catch(X){if(!(X instanceof _)||X.code!=="session_not_found"&&X.code!=="session_expired")throw X;Z=X}for(let[X,Q]of this.completedHandoffCreates)if(Q.sessionId===$)this.completedHandoffCreates.delete(X),this.unconfirmedHandoffCreates.delete(X);if(Z)throw Z}async updateTitle($,J){return await this.request(`/api/v1/session/${encodeURIComponent($)}`,{method:"PATCH",body:JSON.stringify({title:J})})}async history($){let J=await this.options.getAuthToken();if(!J?.trim())throw new _("authentication_required","Sign in to Cline to load this session's history.");let Z=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent($)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${J.trim()}`},signal:AbortSignal.timeout(S)});if(Z.status===404)return null;let X=await Z.json().catch(()=>{return});if(!Z.ok)throw _0(Z.status,X,this.appBaseUrl);if(!X||typeof X!=="object"||!("version"in X)||X.version!==1||!("messages"in X)||!Array.isArray(X.messages))throw new _("request_failed","Invalid archived session history");return X.messages}}import{randomUUID as G6}from"node:crypto";import{posix as N0}from"node:path";import{createSessionId as h4,ensureLoopbackProxyBypass as h1,isHubProtocolCompatible as v4,resolveClineBuildEnv as S4,resolveHubCommandTimeoutMs as m4}from"@cline/shared";import I4 from"ws";var Q1="session_not_found";class r extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function A0($){return $ instanceof r||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}import{spawn as J4}from"node:child_process";import{closeSync as Z4,mkdirSync as X4,openSync as Q4,readFileSync as V4,unlinkSync as Y4}from"node:fs";import{basename as j4,dirname as W4,join as N4}from"node:path";import{fileURLToPath as F4}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as K4,isBunEmbeddedModulePath as L4,isHubDaemonProcess as G4,resolveClineBuildEnv as E1,withResolvedClineBuildEnv as z4}from"@cline/shared";import{createHash as D2,randomBytes as U2}from"node:crypto";import{mkdir as D0,open as V1,readFile as F1,rename as M2,rm as U0,writeFile as R2}from"node:fs/promises";import{dirname as K1,join as M0}from"node:path";import{ensureLoopbackProxyBypass as P2,isHubProtocolCompatible as C2}from"@cline/shared";import{resolveClineDataDir as m,resolveClineDir as J5}from"@cline/shared/storage";var s={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.86-nightly.1790649045",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 H2="CLINE_HUB_DISCOVERY_PATH",x2="CLINE_HUB_BUILD_ID",E2="CLINE_HUB_BUILD_EPOCH_MS",T2=30000,w2=15000,Y1=100;function f2($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function b2($){return D2("sha256").update($).digest("hex").slice(0,12)}function k2($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function j1($){return new Promise((J)=>setTimeout(J,$))}function y2($){return`${$}.lock`}async function g2($){try{let J=JSON.parse(await F1(M0($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function B0($){await U0($,{recursive:!0,force:!0}).catch(()=>{return})}function g(){let $=process.env[x2]?.trim();if($)return $;return"sdk-v1-8ac3e5ea11b6e1a57c372abee01daeb3ceba17048934b317209e04df360b32ae".trim()||`source-${String(s.version)}`}function h2(){let $=Number(process.env[E2]);if(Number.isFinite($)&&$>0)return $;return Number.isFinite(1790649073846)?1790649073846:void 0}function n($,J=g()){let Z=C2($);if(!Z.compatible)return Z;let X=$.buildId?.trim();if(!X)return{compatible:!1,reason:"missing_build"};if(X!==J)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function W1($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:void 0}function N1($){let J=$?.trim().split(/[-+]/,1)[0];if(!J)return;let Z=J.split(".").map((X)=>Number(X));if(Z.length===0||Z.some((X)=>!Number.isInteger(X)||X<0))return;return Z}function v2($,J){for(let Z=0;Z<Math.max($.length,J.length);Z++){let X=$[Z]??0,Q=J[Z]??0;if(X!==Q)return X<Q?-1:1}return 0}function L1($,J){let Z=$.buildId?.trim(),X=J.buildId?.trim();if(Z&&X&&Z===X)return 0;let Q=W1($.buildEpochMs),V=W1(J.buildEpochMs);if(Q!==void 0&&V!==void 0&&Q!==V)return Q<V?-1:1;let j=N1($.coreVersion),Y=N1(J.coreVersion);if(j&&Y){let W=v2(j,Y);if(W!==0)return W}if(Z&&X&&Z!==X)return Z<X?-1:1;return 0}function G1(){return{buildId:g(),buildEpochMs:h2(),coreVersion:String(s.version)}}function o($,J){let Z=J?.self??G1(),X=n($,Z.buildId??"");if(X.compatible)return!0;if(X.reason!=="build_mismatch"&&X.reason!=="missing_build")return!1;return L1(Z,$)<=0}function z1($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${b2($)}`,Z=process.env[H2]?.trim()||M0(m(),"locks","hub","owners",`${f2(J)}.json`);return{ownerId:J,discoveryPath:Z}}async function b($){try{let J=JSON.parse(await F1($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,buildEpochMs:typeof J.buildEpochMs==="number"?J.buildEpochMs:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function _1($,J){await O1($,async()=>{let Z=K1($);await D0(Z,{recursive:!0});let X=`${$}.${process.pid}.${U2(6).toString("hex")}.tmp`,Q;try{Q=await V1(X,"wx",384),await Q.writeFile(`${JSON.stringify(J,null,2)}
9
- `,{encoding:"utf8"}),await Q.sync(),await Q.close(),Q=void 0,await M2(X,$);let V;try{V=await V1(Z,"r"),await V.sync()}catch{}finally{await V?.close().catch(()=>{return})}}catch(V){throw await Q?.close().catch(()=>{return}),await U0(X,{force:!0}).catch(()=>{return}),V}})}async function h($){await O1($,async()=>{await U0($,{force:!0}).catch(()=>{return})})}async function q1($,J,Z){let X=y2($);await D0(K1(X),{recursive:!0});let Q=Date.now()+w2;while(!0){try{await D0(X,{recursive:!1})}catch(V){if((V instanceof Error&&"code"in V?String(V.code):"")!=="EEXIST")throw V;let Y=await g2(X);if(!Y){if(Date.now()>=Q){await B0(X);continue}await j1(Y1);continue}let W=Date.now()-Date.parse(Y.acquiredAt);if(!k2(Y.pid)||W>T2){await B0(X);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub ${J} lock ${X}`);await j1(Y1);continue}try{return await R2(M0(X,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
10
- `,"utf8"),await Z()}finally{await B0(X)}}}function O1($,J){return q1(`${$}.mutation`,"discovery mutation",J)}function A1($,J){return q1($,"startup",J)}async function e($,J){P2();try{let Z=await fetch(J?.authToken?S2($):D1($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0,signal:J?.signal});if(!Z.ok)return;let X=await Z.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((Q)=>typeof Q==="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 B1($,J,Z="/hub"){return new URL(`ws://${$}:${J}${Z}`).toString()}function D1($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function S2($){let J=new URL(D1($));return J.pathname="/status",J.toString()}import{CLINE_HUB_DEV_PORT as m2,CLINE_HUB_PORT as I2,resolveClineBuildEnv as p2}from"@cline/shared";var l2="CLINE_HUB_HOST",u2="CLINE_HUB_PORT",c2="CLINE_HUB_PATHNAME",a2="127.0.0.1",d2=I2,i2="/hub";function U1($){return p2($)==="development"?m2:d2}function t2($={}){return($.env??process.env)[l2]?.trim()||a2}function r2($={}){let Z=($.env??process.env)[u2]?.trim();if(!Z)return U1($);let X=Number.parseInt(Z,10);if(!Number.isInteger(X)||X<1||X>65535)return U1($);return X}function s2($={}){return($.env??process.env)[c2]?.trim()||i2}function M1($={},J={}){return{host:$.host??t2(J),port:$.port??r2(J),pathname:$.pathname??s2(J)}}import{join as n2}from"node:path";var o2="shared:cline",e2="CLINE_HUB_DISCOVERY_PATH",$4="hub-production";function I($=o2){return z1(`${$}@${g()}`)}function $0(){return{ownerId:$4,discoveryPath:process.env[e2]?.trim()||n2(m(),"locks","hub","production.json")}}var R1=15000,_4=200,P1=3000,q4=100,O4=[100,250,500,1000,2000],A4="--cline-hub-daemon",B4=3,D4=60000,C1=new Map;function U4($,J=Date.now()){let Z=C1.get($);if(!Z||J-Z.windowStartedAt>D4)return C1.set($,{count:1,windowStartedAt:J}),!0;return Z.count+=1,Z.count<=B4}function M4($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function R4(){try{let $=N4(m(),"logs","hub-daemon.log");return X4(W4($),{recursive:!0}),{fd:Q4($,"a"),logPath:$}}catch{return}}function P4(){return E1()==="production"?$0():I()}function p($){return o($)}function C4($){try{let J=JSON.parse(V4(`${$}.superseded`,"utf8"));return{url:typeof J.url==="string"?J.url:void 0,authToken:typeof J.authToken==="string"?J.authToken:void 0,pid:typeof J.pid==="number"?J.pid:void 0}}catch{return}}function R0($){try{Y4(`${$}.superseded`)}catch{}}function H1($,J,Z){if(!J||J.url!==Z)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function l($,J){try{return await e($,{authToken:J})}catch{return}}async function x1($,J){let Z=Date.now()+J;while(Date.now()<Z){if(!(await l($))?.url)return!0;await new Promise((Q)=>setTimeout(Q,q4))}return!1}async function C0($,J){if(!U4($.url))return!1;await u($.url,$.authToken,"retired by newer install").catch(()=>!1),await w1($.url,$.authToken).catch(()=>!1);let Z=await x1($.url,P1);if(!Z&&$.pid&&H4($.pid)){try{process.kill($.pid,"SIGTERM")}catch{}Z=await x1($.url,P1)}if(Z)await h(J).catch(()=>{return});return Z}function H4($){try{return process.kill($,0),!0}catch(J){return J?.code==="EPERM"}}async function x4($){try{return(await H0($.url,$.authToken)).activeSessionCount>0}catch{return!1}}async function P0($,J){if(p($))return"reusable";let Z=await u($.url,$.authToken,"retired by newer install").catch(()=>!1);if(await x4($)){if(Z)await u($.url,$.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let X=await C0($,J);if(!X&&Z)await u($.url,$.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return X?"retired":"failed"}async function E4($){if(E1()!=="production")return;let J=I();if(J.discoveryPath===$.discoveryPath)return;let Z=await b(J.discoveryPath);if(Z?.url)await C0(Z,J.discoveryPath);else await h(J.discoveryPath).catch(()=>{return})}function T4(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return F4(new URL(`./entry.${$}`,import.meta.url))}function w4($,J){if(L4($))return[A4];return[...J&&$.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],$]}function f4($,J){let Z=T4(),X=process.execPath?.trim();if(!X)throw Error("unable to resolve runtime executable for hub daemon");let Q=j4(X).toLowerCase().includes("bun"),V=w4(Z,Q);return{launcher:X,args:[...V,"--cwd",$,...M4(J),...J.manageConnectors===!1?["--no-connectors"]:[]],cwd:$,env:{...z4(process.env),CLINE_NO_INTERACTIVE:"1",[K4]:"1"}}}function b4($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function k4($,J={}){if(G4())return;let Z=f4($,J),X=R4();try{J4(Z.launcher,Z.args,{detached:!0,stdio:X?["ignore",X.fd,X.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(X)Z4(X.fd)}}async function y4($,J={}){for(let Z=0;;Z++)try{k4($,J);return}catch(X){let Q=O4[Z];if(!b4(X)||Q===void 0)throw X;await new Promise((V)=>setTimeout(V,Q))}}async function g4($,J,Z={}){let X=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=M1(Z),V=B1(Q.host,Q.port,Q.pathname),j=(F)=>{if(!X)J0(F.url,F.authToken);return F};await E4($).catch(()=>{return});let Y=await b($.discoveryPath),W=Y?.url?void 0:C4($.discoveryPath),K=!1;if(Y?.url){let F=Y.authToken;if(!F)K=!0,await C0(Y,$.discoveryPath);else{let q=await l(Y.url,F);if(q?.url&&p(q)&&await w(q.url,{authToken:F}))return R0($.discoveryPath),j({url:q.url,authToken:F});if(q?.url){if(await P0({...q,authToken:F},$.discoveryPath)==="deferred_busy"&&await w(q.url,{authToken:F}))return j({url:q.url,authToken:F})}else await h($.discoveryPath).catch(()=>{return})}}let G=await l(V);if(G?.url){let F=H1(G,Y??W,V);if(p(G)){let O=[G.authToken,Y?.authToken,W?.authToken].filter((D)=>typeof D==="string"&&D.trim().length>0);for(let D of O){if(!await w(G.url,{authToken:D}))continue;let H={hubId:G.hubId??`repaired-${G.port}`,protocolVersion:G.protocolVersion,minClientProtocolVersion:G.minClientProtocolVersion,maxClientProtocolVersion:G.maxClientProtocolVersion,capabilities:G.capabilities,coreVersion:G.coreVersion,buildId:G.buildId,authToken:D,host:G.host,port:G.port,url:G.url,pid:G.pid??Y?.pid??W?.pid,startedAt:G.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await _1($.discoveryPath,H)}catch{}return R0($.discoveryPath),j({url:G.url,authToken:D})}throw Error(`A compatible Cline Hub is already running at ${V}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${K?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let q=await P0(F,$.discoveryPath);if(q==="deferred_busy"){for(let O of[F.authToken,Y?.authToken].filter((B)=>typeof B==="string"&&B.trim().length>0))if(await w(G.url,{authToken:O}))return j({url:G.url,authToken:O});if(Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An older Cline Hub is running at ${V} 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(q==="failed"&&Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An incompatible Cline Hub is already running at ${V} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let z=Z.allowPortFallback===!0&&Q.port!==0?{...Q,port:0}:Q;await y4(J,{...z,manageConnectors:Z.manageConnectors});let L=Date.now()+R1;while(Date.now()<L){let F=await b($.discoveryPath);if(F?.url&&F.authToken){let O=await l(F.url,F.authToken);if(O?.url&&p(O)&&await w(O.url,{authToken:F.authToken}))return R0($.discoveryPath),j({url:O.url,authToken:F.authToken})}let q=await l(V);if(q?.url&&!p(q)){let O=H1(q,F??W,V),B=await P0(O,$.discoveryPath);if(B==="deferred_busy"&&F?.authToken&&await w(q.url,{authToken:F.authToken}))return j({url:q.url,authToken:F.authToken});if(B==="failed"&&Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An incompatible Cline Hub is still running at ${V} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((O)=>setTimeout(O,_4))}throw Error(`Timed out after ${R1}ms waiting for detached hub startup.`)}async function T1($,J={}){let Z=P4();return await A1(Z.discoveryPath,async()=>g4(Z,$,J))}function p4(){return S4()==="production"?$0():I()}function l4(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function v1($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return v1($.data);return String($)}function u4($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function f1($){let J=$,Z=u4(J.reason);return new R("hub_connection_closed",J.code||Z?`Hub connection closed (code=${J.code??0}${Z?`, reason=${Z}`:""})`:E0,{closeCode:J.code,closeReason:Z||void 0})}function b1($,J){if($ instanceof R)return $;if($ instanceof Error)return new R("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new R("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new R("hub_connect_failed",Z);let X=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new R("hub_connect_failed",X?`Failed to connect to hub at ${J.toString()} (${X} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var x0="*",Z0=8000,c4="cline-hub-auth.",S1=new Map,m1=new Set,a4=3000;var E0="Hub connection closed",d4=250,i4=5000,k1=0.5;class R extends Error{code;details;constructor($,J,Z){super(J);this.code=$;this.details=Z;this.name="HubTransportError"}}function t4($){return $ instanceof R}class T0 extends Error{command;code;constructor($,J,Z){super(Z);this.command=$;this.code=J;this.name="HubCommandError"}}function f0($,J={}){let Z=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Z)return Z;if(J.skipRegistry)return;let X=b0($.toString());return X?S1.get(X):void 0}function r4($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function b0($){if(!r4($))return;let J=new URL(I1($));return J.search="",J.hash="",J.toString()}function y1($){let J=b0($);return!!J&&m1.has(J)}function J0($,J){let Z=b0($);if(Z){if(m1.add(Z),J?.trim())S1.set(Z,J)}return $}class c{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 R("hub_connection_closed",E0);sawSocketClose=!1;registered=!1;capabilities;constructor($){this.options=$;if($.authToken?.trim()&&$.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url,this.capabilities=[...$.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($){if(this.capabilities=$.map((J)=>({...J})),!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 $=new URL(this.currentUrl),J=this.options.authToken?.trim()||f0($,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if($.hash="",J&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let Z=++this.connectGeneration,X=this.openSocket($,J,Z),Q;this.connectPromise=X.then(async(j)=>{if(Q=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),Z!==this.connectGeneration||this.closedByClient){try{j.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let Y of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Y));this.reconnectAttempt=0});let V=this.connectPromise;try{await V}catch(j){if(this.connectPromise===V)this.connectPromise=void 0;if(Q&&this.socket===Q){this.lastCloseError=b1(j,$),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{Q.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw j}}async openSocket($,J,Z){let X=this.options.resolveConnectionHeaders,Q;if(X){let W;try{Q=await Promise.race([Promise.resolve().then(()=>X()),new Promise((K,G)=>{W=setTimeout(()=>{G(new R("hub_connect_timeout",`Timed out resolving hub connection headers after ${Z0}ms`))},Z0)})])}catch(K){let G=K instanceof R?K:new R("hub_connect_failed",K instanceof Error?K.message:String(K));if(Z===this.connectGeneration)this.lastCloseError=G;throw G}finally{clearTimeout(W)}}if(Z!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(Q&&Object.keys(Q).some((W)=>W.toLowerCase()==="sec-websocket-protocol")){let W=new R("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(Z===this.connectGeneration)this.lastCloseError=W;throw W}let V=Q?new I4($.toString(),{headers:{...Q}}):new(l4())($.toString(),J?[`${c4}${J}`]:void 0);this.socket=V;let j=!1,Y=new Promise((W,K)=>{let G=!1,N=setTimeout(()=>{if(G)return;G=!0,j=!0;let z=new R("hub_connect_timeout",`Timed out connecting to hub after ${Z0}ms`);if(this.socket===V)this.lastCloseError=z,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{V.close()}catch{}K(z)},Z0);V.addEventListener("open",()=>{if(G)return;G=!0,clearTimeout(N),W()}),V.addEventListener("error",(z)=>{if(G)return;G=!0,clearTimeout(N);let L=b1(z,$);if(this.socket===V)this.lastCloseError=L,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;K(L)}),V.addEventListener("close",(z)=>{if(G)return;G=!0,clearTimeout(N);let L=j?this.lastCloseError:f1(z);if(this.socket===V){if(!j)this.lastCloseError=L,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}K(L)})});return V.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(v1(W)))}),V.addEventListener("close",(W)=>{if(this.socket!==V)return;if(!j)this.lastCloseError=f1(W),this.sawSocketClose=!0;this.registered=!1;for(let K of this.pendingReplies.values())K.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await Y,V}subscribe($,J){let Z=J?.sessionId?.trim()||void 0,X={listener:$,sessionId:Z};return this.listeners.add(X),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(X))return;this.adjustSubscriptionCount(Z,-1)}}async command($,J,Z,X){let Q=0,V=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Z,X)}catch(j){if(!V||Q>=1||!await this.recoverLocalHubTransport(j))throw j;Q+=1}}async commandOnce($,J,Z,X,Q=!0){if(Q)await this.connect();X?.beforeDispatch?.();let V=h4("hubreq_");X?.onDispatch?.(V);let j=m4($,X?.timeoutMs),Y=new Promise((K,G)=>{let N=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(V))return;G(new T0($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${V}, 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(V,{resolve:(z)=>{if(N)clearTimeout(N);K(z)},reject:(z)=>{if(N)clearTimeout(N);G(z)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:V,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:J}})}catch(K){throw this.pendingReplies.delete(V),K}let W=await Y;if(!W.ok){if(W.error?.code===Q1){let K=Z??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new r(K,W.error.message)}throw new T0($,W.error?.code,W.error?.message??`Hub command ${$} failed`)}return W}async recoverLocalHubTransport($){if(!y1(this.currentUrl)||!t4($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await g1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,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 $=Math.min(d4*2**this.reconnectAttempt,i4),J=Math.round($*(1-k1)+Math.random()*$*k1);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!y1(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await g1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,$)this.lastCloseError=new R("hub_connection_closed",E0);for(let J of this.pendingReplies.values())J.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!$)return;this.sawSocketClose=!1,this.socket=void 0;try{$.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($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new R("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){let Z=$==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(J)):void 0;this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{},...Z!==void 0?{sinceSequence:Z}:{}})}adjustSubscriptionCount($,J){let Z=this.subscriptionKeyForSessionId($),X=(this.subscriptionCounts.get(Z)??0)+J;if(X<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,X),J>0&&X===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??x0}subscriptionSessionIdFromKey($){return $===x0?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Z=this.pendingReplies.get(J);if(!Z)return;this.pendingReplies.delete(J),Z.resolve($.envelope);return}case"event":{let J=$.envelope.sequence;if(typeof J==="number"){let Z=$.envelope.sessionId?.trim();for(let X of[x0,Z]){if(!X||!this.subscriptionCounts.has(X))continue;let Q=this.lastEventSequenceByKey.get(X)??0;if(J>Q)this.lastEventSequenceByKey.set(X,J)}}for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==$.envelope.sessionId?.trim())continue;Z.listener($.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function I1($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function w($,J){let Z=new c({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function w0($,J){let Z=I1($),X=await e(Z,{authToken:J?.authToken});if(!X)return{status:"unreachable",url:Z};if(J?.requireCurrentBuild){let Q=g(),V=n(X,Q);if(!V.compatible&&!o(X))return{status:V.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!v4(X).compatible)return{status:"protocol_mismatch",url:Z};if(J?.verifyConnection===!0&&!await w(Z,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}function s4($){let J=$&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[],Z=0,X=new Set;for(let Q of J){if(!Q||typeof Q!=="object")continue;let V=Q.participants;if(!Array.isArray(V)||V.length===0)continue;Z+=1;for(let j of V){let Y=j&&typeof j==="object"?j.clientId:void 0;if(typeof Y==="string"&&Y.trim())X.add(Y)}}return{activeSessionCount:Z,participantClientCount:X.size}}async function H0($,J,Z){let X=new c({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let Q=await X.command("session.list",{limit:500},void 0,{timeoutMs:a4});return s4(Q.payload)}finally{await X.dispose().catch(()=>{return})}}async function n4($,J,Z){try{return(await H0($,J,Z)).activeSessionCount===0}catch{return!1}}async function o4($,J){let Z=`${$.discoveryPath}.superseded`,X=await b(Z);if(!X?.url||!X.authToken)return;let Q=await w0(X.url,{authToken:X.authToken});if(Q.status!=="compatible")return;if(await n4(Q.url,X.authToken,J))return;return J0(Q.url,X.authToken)}async function e4($={}){if($.endpoint?.trim()){let Q=await w0($.endpoint);return Q.status==="compatible"?Q.url:void 0}let J=p4(),Z=await b(J.discoveryPath);if(!Z?.url)return await o4(J,$);let X=await w0(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if(X.status==="compatible")return J0(X.url,Z.authToken);if(X.status==="protocol_mismatch")await h(J.discoveryPath).catch(()=>{return});return}async function g1($={}){let J=await e4($);if(J&&await w(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;try{return(await T1($.workspaceRoot??process.cwd())).url}catch(Z){$.onStartupError?.(Z);return}}async function u($,J,Z,X){h1();let Q=new URL($),V=J?.trim()||f0(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";if(Q.pathname="/drain",Q.hash="",Z)Q.searchParams.set("reason",Z);if(X?.off)Q.searchParams.set("off","1");return(await fetch(Q,{method:"POST",headers:V?{authorization:`Bearer ${V}`}:void 0})).ok}async function w1($,J){h1();let Z=new URL($),X=J?.trim()||f0(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:X?{authorization:`Bearer ${X}`}:void 0})).ok}function $6($,J){if(!$||typeof $!=="object")return;let Z=$,X=typeof Z.id==="string"?Z.id.trim():"";if(!X)return;let Q=typeof Z.display_name==="string"?Z.display_name.trim():typeof Z.displayName==="string"?Z.displayName.trim():"",V=typeof Z.name==="string"?Z.name.trim():"";return{id:X,name:Q||V||X,catalogId:J}}function k0($,J){return Array.isArray($)?$.flatMap((Z)=>{let X=$6(Z,J);return X?[X]:[]}):[]}async function p1($,J={}){let Z=$.trim(),X=Z.length;while(X>0&&Z[X-1]==="/")X--;let Q=Z.slice(0,X),V=async(q)=>{let O=await(J.fetchImpl??fetch)(`${Q}${q}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!O.ok)throw Error(`HTTP ${O.status}`);return await O.json()},j,Y;try{[j,Y]=await Promise.all([V("/api/v1/ai/cline/models"),V("/api/v1/ai/cline/recommended-models")])}catch(q){throw Error("Could not load the cloud model catalog.",{cause:q})}let W=j&&typeof j==="object"?j:void 0,K=k0(Array.isArray(j)?j:W?.data,"cline"),G=Y&&typeof Y==="object"?Y:void 0,N=G?.data&&typeof G.data==="object"?G.data:G,z=k0(N?.clinePass,"cline-pass"),L=k0(N?.clineCloud,"cline-cloud"),F=new Set;return[...J.isOrganizationSession?[]:z,...L,...K].filter((q)=>{if(F.has(q.id))return!1;return F.add(q.id),!0})}import{formatDisplayUserInput as l1}from"@cline/shared";var J6=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function Z6($){switch($){case"user":case"assistant":case"tool":case"system":case"status":case"error":return $;default:return"assistant"}}function X6($){return $.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}function Q6($){let J=$?.userRunSpan;return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:void 0}function V6($){if(typeof $.content==="string")return{hasAttachment:!1,text:$.content};if(!Array.isArray($.content))return{hasAttachment:!1,text:"unknown"};let J=!1,Z=!1,X=[];for(let Q of $.content){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let V=Q;if(V.type==="text"&&typeof V.text==="string")X.push(V.text);else if(V.type==="tool_result"||V.type==="tool-result")Z=!0;else if(V.type==="file"||V.type==="image")J=!0}return{hasAttachment:J&&!Z,text:X.join(`
11
- `)}}function Y6($){let J=l1($);return J.startsWith("[TASK RESUMPTION]")||J==="The user approved switching to act mode. Continue with the approved plan now."}function j6($){if(Z6($.role)!=="user")return 0;let J=X6($),Z=typeof J?.kind==="string"?J.kind:void 0,X=Q6(J);if(Z==="compaction"||Z==="compaction_summary")return X??1;if(X!==void 0)return X;if(Z&&J6.has(Z))return 0;let Q=V6($);if(!Q.hasAttachment&&!l1(Q.text))return 0;if(!Q.hasAttachment&&Y6(Q.text))return 0;return 1}function u1($){return j6($)>0}function V0($){return Array.isArray($?.sessions)?$.sessions.filter((J)=>Boolean(J)&&typeof J==="object"&&!Array.isArray(J)):[]}function y0($){let J=$.updatedAt;return typeof J==="number"?J:Date.parse(String(J??""))||0}function g0($){let J=$?.metadata&&typeof $.metadata==="object"?$.metadata:void 0;return String(J?.model??$?.model??"").trim()}function Y0($){let J=$.metadata&&typeof $.metadata==="object"?$.metadata:void 0;return!String(J?.parentSessionId??$.parentSessionId??"").trim()}function i1($,J="text"){if(!$||typeof $!=="object"||Array.isArray($))return"";let Z=$.content;if(typeof Z==="string")return J==="text"?Z.trim():"";if(!Array.isArray(Z))return"";return Z.map((X)=>X&&typeof X==="object"&&!Array.isArray(X)?J==="thinking"&&X.type==="redacted_thinking"?"[redacted]":String(X[J]??""):"").join("").trim()}function X0($){let J=$.trim(),Z=J.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(Z?Z[1]:J).trim()}function a($,J,Z){let X=X0(Z);return $.filter((Q)=>Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)&&String(Q.role??"").toLowerCase()==="user"&&(X!==""||u1(Q))&&X0(i1(Q))===X).length+J.filter((Q)=>X0(Q.prompt)===X).length}function h0($){return $.flatMap((J)=>{if(J.event!=="session.pending_prompt_submitted")return[];let Z=J.payload?.prompt&&typeof J.payload.prompt==="object"&&!Array.isArray(J.payload.prompt)?J.payload.prompt:void 0,X=String(Z?.id??"").trim();if(!X)return[];return[{id:X,prompt:String(Z?.prompt??""),steer:Z?.delivery==="steer",attachmentCount:typeof Z?.attachmentCount==="number"?Z.attachmentCount:0,userImages:Array.isArray(Z?.userImages)?Z.userImages.filter((Q)=>typeof Q==="string"):void 0}]})}var W6=new Set(["run.completed","run.aborted","run.failed"]),N6=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function c1($,J){return $.filter((Z)=>Boolean(Z)&&typeof Z==="object"&&!Array.isArray(Z)&&String(Z.role??"").toLowerCase()==="assistant").map((Z)=>i1(Z,J)).filter(Boolean)}function a1($,J,Z="text"){let X=new Map;for(let Q of c1(J,Z))X.set(Q,(X.get(Q)??0)+1);return c1($,Z).filter((Q)=>{let V=X.get(Q)??0;if(V===0)return!0;if(V===1)X.delete(Q);else X.set(Q,V-1);return!1})}function Q0($,J,Z=new Set){if(!$||typeof $!=="object")return Z;if(Array.isArray($)){for(let V of $)Q0(V,J,Z);return Z}let X=$,Q=J==="tool_use"?X.id:X.tool_use_id;if(X.type===J&&typeof Q==="string")Z.add(Q);for(let V of Object.values(X))Q0(V,J,Z);return Z}function d1($,J="assistant"){let Z="",X="";for(let Q of $)if(Q.event===`${J}.delta`)X+=J==="reasoning"&&Q.payload?.redacted&&!Q.payload?.text?"[redacted]":typeof Q.payload?.text==="string"?Q.payload.text:"";else if(Q.event===`${J}.finished`){let V=Q.payload?.[J==="assistant"?"text":"reasoning"],j=typeof V==="string"&&V?V:X;if(j)Z=j;X=""}return(Z||X).trim()}function t1($,J,Z={}){let X=Z.queueSnapshotApplied!==!1,Q=a1(J,Z.baselineMessages??[]),V=a1(J,Z.baselineMessages??[],"thinking"),j=Q0(J,"tool_use"),Y=Q0(J,"tool_result"),W=new Set($.slice(0,Z.messagesSnapshotEventCutoff??$.length)),K=new Set,G=new Map;for(let O of $.slice(0,Z.messagesSnapshotEventCutoff??$.length)){let B=h0([O])[0];if(!B)continue;let D=X0(B.prompt),H=G.get(D)??Math.max(0,a(J,[],D)-a(Z.baselineMessages??[],[],D));if(G.set(D,Math.max(0,H-1)),H>0)K.add(O)}let z=[...X?$.slice(Z.queueSnapshotEventCutoff??$.length):$].reverse().find((O)=>O.event==="session.pending_prompts"),L=[],F=[],q=(O)=>{if(F.length===0)return;let B=F.filter((x)=>W.has(x)),D=(x)=>{if(!O)return-1;let M=[...B].reverse().findIndex(($2)=>$2.event===`${x}.finished`),v=M<0?-1:B.length-1-M;return v>=0||F.at(-1)?.event==="run.aborted"?v:B.length-1},H=D("assistant"),f=D("reasoning"),A=d1(B.slice(0,H+1)),P=A?Q.findIndex((x)=>x.endsWith(A)):-1,k=P>=0;if(k)Q.splice(P,1);let d=d1(B.slice(0,f+1),"reasoning"),F0=d?V.findIndex((x)=>x.endsWith(d)):-1;if(F0>=0)V.splice(F0,1);for(let[x,M]of F.entries()){if(K.has(M)){L.push({...M,payload:{...M.payload,transcriptReflected:!0}});continue}if(W.has(M)&&N6.has(M.event)&&(M.event.startsWith("reasoning.")?F0>=0&&x<=f:k&&x<=H))continue;if(M.event==="session.pending_prompts"&&M!==z)continue;if(W.has(M)&&M.event.startsWith("tool.")){let v=String(M.payload?.toolCallId??"").trim();if(Y.has(v)||M.event==="tool.started"&&j.has(v))continue}L.push(M)}F=[]};for(let O of $)if(F.push(O),W6.has(O.event))q(!0);return q(!1),L}import{formatDisplayUserInput as F6}from"@cline/shared";function j0($){let J=structuredClone($),Z=(X)=>{if(!X||typeof X!=="object"||Object.isFrozen(X))return;for(let Q of Object.values(X))Z(Q);Object.freeze(X)};return Z(J),J}function W0($){let J=$?.trim();return J?F6(J).slice(0,120):void 0}function v0($){if(typeof $==="string")return $;if(Array.isArray($)){let J=[];for(let Z of $){if(typeof Z==="string"){if(Z.trim())J.push(Z);continue}if(!Z||typeof Z!=="object")continue;let X=Z,Q=typeof X.type==="string"?X.type:"",V=Q==="text"?String(X.text??""):Q==="thinking"?String(X.thinking??""):Q==="tool_use"?`[tool] ${String(X.name??"tool_call")}`:Q==="tool_result"?`[tool_result]
12
- ${v0(X.content)}`:Q==="image"?"[image]":Q==="redacted_thinking"?"[redacted_thinking]":typeof X.text==="string"?X.text:"";if(V.trim())J.push(V)}return J.join(`
13
- `)}if($&&typeof $==="object"){let J=$;if(typeof J.text==="string")return J.text}return""}function K6($){let J=W0($??void 0);if(!J)return;return J.split(`
14
- `)[0]?.trim().slice(0,70)||void 0}function L6($){for(let J of["user","assistant"])for(let Z of $){if(!Z||typeof Z!=="object")continue;let X=Z;if(X.role!==J)continue;let Q=W0(v0(X.content));if(!Q)continue;return Q.split(`
15
- `)[0]?.trim().slice(0,70)||void 0}return}function S0($){let J=$.metadata&&typeof $.metadata==="object"?W0($.metadata.title):void 0;if(J)return J.slice(0,70);let Z=K6($.prompt);if(Z)return Z;let X=$.messages?L6($.messages):void 0;if(X)return X;return`Session ${$.sessionId.slice(-6)}`}function r1($,J,Z,X){let Q=J.payload??{},V=()=>{let Y=Z.get(X);if(Y===void 0||!$.messages[Y]||$.messages[Y]?.role!=="assistant")Y=$.messages.length,$.messages.push({role:"assistant",content:[]}),Z.set(X,Y);let W=$.messages[Y];if(!Array.isArray(W.content))W.content=[];return W.content},j=(Y,W,K)=>{let G=V(),N=G.at(-1);if(N?.type===Y)N[W]=`${N[W]??""}${K}`;else G.push({type:Y,[W]:K})};switch(J.event){case"assistant.delta":if(typeof Q.text==="string")j("text","text",Q.text);return;case"reasoning.delta":if(typeof Q.text==="string"&&Q.text)j("thinking","thinking",Q.text);else if(Q.redacted===!0)V().push({type:"redacted_thinking",data:""});return;case"assistant.finished":Z.delete(X);return;case"assistant.media":if(Q.media)V().push({type:"media",media:structuredClone(Q.media)});return;case"tool.started":{let Y=String(Q.toolCallId??"");if(Y&&!$.messages.some((W)=>Array.isArray(W.content)&&W.content.some((K)=>K.type==="tool_use"&&K.id===Y)))V().push({type:"tool_use",id:Y,name:String(Q.toolName??"tool"),input:structuredClone(Q.input??{})});return}case"tool.finished":{let Y=String(Q.toolCallId??"");if(Y&&!$.messages.some((W)=>Array.isArray(W.content)&&W.content.some((K)=>K.type==="tool_result"&&K.tool_use_id===Y)))$.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:Y,content:typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??""),is_error:Boolean(Q.error)}]}),Z.delete(X);return}case"usage.updated":$.usage=structuredClone(Q.totals??Q.delta??{});return;case"session.pending_prompts":{let Y=Array.isArray(Q.prompts)?Q.prompts:[];$.promptsInQueue=Y.map((W)=>({id:String(W.id??""),prompt:String(W.prompt??""),steer:W.delivery==="steer",attachmentCount:typeof W.attachmentCount==="number"?W.attachmentCount:0,userImages:Array.isArray(W.userImages)?W.userImages.filter((K)=>typeof K==="string"):void 0})).filter((W)=>W.id&&(W.prompt||W.attachmentCount));return}case"session.pending_prompt_submitted":{let Y=Q.prompt,W=String(Y?.id??"");if(!W||$.lastQueuedPromptStartId===W)return;if($.lastQueuedPromptStartId=W,$.promptsInQueue=$.promptsInQueue.filter((K)=>K.id!==W),Q.transcriptReflected!==!0)$.messages.push({role:"user",content:[{type:"text",text:String(Y?.prompt??"")}]});$.busy=!0,$.status="running",$.endedAt=void 0,Z.delete(X);return}case"run.started":case"session.attached":case"session.updated":{if(typeof J.sequence==="number"&&$.lastHubStatusSequence!==void 0&&J.sequence<$.lastHubStatusSequence)return;if(typeof J.sequence==="number")$.lastHubStatusSequence=J.sequence;let Y=Q.session,W=typeof Y?.status==="string"?Y.status:J.event==="run.started"?"running":$.status,K=W==="pending"?"running":W;if(J.event==="session.updated"&&K==="running"&&$.endedAt!==void 0&&!$.busy)return;let G=$.busy;if($.status=K,$.busy=K==="running",J.event==="run.started"){if(!G)Z.delete(X);$.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof J.sequence==="number"&&$.lastHubStatusSequence!==void 0&&J.sequence<$.lastHubStatusSequence)return;if(typeof J.sequence==="number")$.lastHubStatusSequence=J.sequence;$.status=typeof Q.reason==="string"?Q.reason:J.event==="run.failed"?"error":J.event==="run.aborted"?"aborted":"completed",$.busy=!1,$.endedAt=Date.now(),Z.delete(X);return}}}function m0($){return $ instanceof Error&&$.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String($.code))}function I0($,J){return $ instanceof Error&&$.name==="HubCommandError"&&$.code==="hub_command_timeout"&&(!J||$.command===J)}var U="/workspace",z6=30000,_6=2000,q6=2000,s1="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.";function p0($){if(!$)return U;if(N0.isAbsolute($)||$.includes("\\")||$.split("/").some((Z)=>!Z||Z==="."||Z===".."))throw new _("request_failed","The handoff workspace path must stay inside the repository.");let J=N0.join(U,$);if(!J.startsWith(`${U}/`))throw new _("request_failed","The handoff workspace path must stay inside the repository.");return J}function d0($){let J=$.metadata.cwd;return typeof J==="string"&&N0.normalize(J)===J&&(J===U||J.startsWith(`${U}/`))?J:U}function n1($){let J=$?.metadata&&typeof $.metadata==="object"?$.metadata:void 0,Z=J?.handoff&&typeof J.handoff==="object"?J.handoff:void 0;return String(Z?.sourceSessionId??"").trim()}class c0 extends Error{constructor($){super($ instanceof Error?$.message:"Cloud conversation creation was not dispatched.",{cause:$});this.name="CloudHandoffSeedRejectedError"}}class a0 extends _{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"}}class e1 extends Error{constructor(){super("The cloud session was created, but its transcript was not persisted. This cloud runtime cannot durably seed handoff transcripts and must use @cline/core 0.0.72 or newer. Updating the cloud runtime or pod is required; retrying /cloud against this same pod will not help.");this.name="CloudHandoffSeedUnsupportedError"}}function E($){let J=$.expiredAt?Date.parse($.expiredAt):Number.NaN;return Number.isFinite(J)&&J<=Date.now()}function O6($){return $.trim().startsWith("ses-")}function A6($,J){let Z=new URL(`/api/v1/session/${encodeURIComponent(J)}`,$);return Z.protocol=Z.protocol==="https:"?"wss:":"ws:",Z.toString()}function l0($){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:$.metadata.modelId??"",modelId:$.metadata.modelId??"",repoUrl:$.repoContext.repoUrl??"",branch:$.repoContext.branch??"",cwd:d0($),workspaceRoot:U},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse($.createdAt)||Date.now(),endedAt:E($)&&$.expiredAt?Date.parse($.expiredAt):void 0,status:$.status,attachedViaHub:!0}}function u0($,J,Z){return{sessionId:$.id,origin:"cloud",executionTarget:"cloud",status:J,provider:"cline",model:$.metadata.modelId??"",repoUrl:$.repoContext.repoUrl??"",branch:$.repoContext.branch??"",cwd:d0($),workspaceRoot:U,...Z?.trim()?{prompt:Z.trim()}:{},metadata:{origin:"cloud",repoUrl:$.repoContext.repoUrl??"",git:{url:$.repoContext.repoUrl??"",branch:$.repoContext.branch??""}}}}function o1($){return{sessionId:$.id,origin:"cloud",executionTarget:"cloud",status:$.status,provider:"cline",model:$.metadata.modelId??"",cwd:d0($),workspaceRoot:U,repoUrl:$.repoContext.repoUrl??"",branch:$.repoContext.branch??"",startedAt:$.createdAt,...$.lastActivityAt?{lastActivityAt:$.lastActivityAt}:{},endedAt:E($)?$.expiredAt??void 0:$.status==="failed"?$.lastActivityAt??$.createdAt:void 0,updatedAt:$.updatedAt,...$.title?.trim()?{title:$.title.trim()}:{},metadata:{...$.title?.trim()?{title:$.title.trim()}:{},origin:"cloud",...$.metadata.provisioningPhase?{provisioningPhase:$.metadata.provisioningPhase}:{},repoUrl:$.repoContext.repoUrl??"",git:{url:$.repoContext.repoUrl??"",branch:$.repoContext.branch??""}}}}function B6($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function D6($,J){let Z=[...$??[]],X=new Set(Z.map((Q)=>Q.id));for(let Q of J)if(!X.has(Q.id))Z.push(Q);return Z}class U6{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;unconfirmedInnerCreates=new Set;createRequests=new Map;provisioningControllers=new Map;sendAbortTokens=new Map;titleWrites=new Map;deletingSessions=new Set;createHubClient;constructor($){this.options=$;this.pendingInitialTasks=$.pendingInitialTasks??new Map,this.createHubClient=$.createHubClient??((J)=>new c(J))}restoreCreationOptions($,J){if(this.restoredOptions.set($,structuredClone(J)),this.pendingInitialTasks.has($))this.pendingInitialTasks.set($,{...this.pendingInitialTasks.get($),...structuredClone(J)});let Z=this.sessions.get($);if(Z)Object.assign(Z.config,structuredClone(J))}seedSessionState($,J){if(!this.sessions.has($))this.sessions.set($,structuredClone(J))}stateFromRecord($){let J=l0($);return Object.assign(J.config,this.pendingInitialTasks.get($.id),this.restoredOptions.get($.id)),J}getSnapshot($){let J=this.knownSessions.get($),Z=this.sessions.get($)??(J?this.stateFromRecord(J):void 0);if(!Z)return;let X=this.connections.get($);return j0({...Z,sessionId:$,record:J,approvals:Array.from(this.approvals.values()).filter((Q)=>Q.item.sessionId===$).map((Q)=>Q.item),connectionState:this.detachedSessions.has($)||this.disposed?"detached":X?.reconnectResolution||X?.rehydrationPromise?"reconnecting":X?X.connected?"connected":X.reconnecting?"reconnecting":"connecting":this.connectionPromises.has($)?"connecting":"detached",transcriptKnown:X?.transcriptKnown??Boolean(J&&E(J))})}subscribe($,J){let Z=(X)=>{if(!J||X.sessionId===J)$(X)};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}publish($){let J=$.type==="snapshot"?Object.freeze($):j0($);for(let Z of this.listeners)try{Z(J)}catch(X){this.options.logger?.error?.("Cloud session subscriber failed",{error:X})}}publishSnapshot($,J=!1,Z){this.cancelScheduledSnapshot($);let X=this.getSnapshot($);if(X)this.publish({type:"snapshot",sessionId:$,snapshot:X,replace:J,cause:Z});else this.publish({type:"removed",sessionId:$})}snapshotTimers=new Map;cancelScheduledSnapshot($){clearTimeout(this.snapshotTimers.get($)),this.snapshotTimers.delete($)}scheduleSnapshot($){if(this.disposed||this.detachedSessions.has($)||this.snapshotTimers.has($))return;let J=setTimeout(()=>this.publishSnapshot($),100);J.unref?.(),this.snapshotTimers.set($,J)}notify($,J){let Z=String(J.sessionId??"");if($==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:Z,message:String(J.message??"Cloud synchronization failed")});else this.publishSnapshot(Z,$==="cloud_session_rehydrated",$==="chat_session_status"?"status":$==="chat_session_ended"?"ended":$==="tool_approval_state"?"approvals":void 0)}applyLiveEvent($,J){let Z=this.sessions.get($);if(Z)r1(Z,J,this.streamingMessages,$)}async respondApproval($,J,Z){this.assertSessionActive($);let X=this.approvals.get(`${$}:${J}`);if(!X){if(!this.connections.has($))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new _("request_failed","This approval was already resolved or is no longer available.")}await X.resolve(Z)}async detach($){this.detachedSessions.add($),this.sessionGenerations.set($,(this.sessionGenerations.get($)??0)+1),this.connectionPromises.delete($),this.sendAbortTokens.set($,Symbol()),this.abortProvisioningControllers($,Error("Cloud viewer detached")),await this.disposeConnection($),this.publishSnapshot($)}isCloudSession($){return O6($)||this.knownSessions.has($)||this.connections.has($)||this.sessions.get($)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord($){let J=this.knownSessions.get($);return J?o1(J):void 0}async getCrossScopeDiscoveryRecord($){let J=this.getCachedDiscoveryRecord($);if(!J)return;try{let X=(await this.options.api.status($)).status?.trim();return X?{...J,status:X}:J}catch(Z){if(Z instanceof _&&(Z.code==="session_not_found"||Z.code==="session_expired")){this.knownSessions.delete($),this.unlistedSessions.delete($),this.pendingInitialTasks.delete($);return}return J}}async list(){if(this.disposed)throw Error("Cloud session controller was disposed");let $=await this.resolveActiveOrganizationId(),J=(await this.options.api.list($)).map((X)=>this.preserveConnectedRuntimeModel(X));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=J;for(let X of J)this.knownSessions.set(X.id,X),this.unlistedSessions.delete(X.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(X)=>this.getCrossScopeDiscoveryRecord(X)));let Z=await Promise.all(J.map(async(X)=>{if(X.status!=="provisioning")return X;let Q=await this.options.api.status(X.id).catch(()=>{return}),V=Q?.status?.trim();if(!V)return X;return{...X,status:V,metadata:{...X.metadata,...O0(Q?.phase)?{provisioningPhase:Q?.phase}:{},...Q?.statusReason?.trim()?{statusReason:Q.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let X of Z){this.knownSessions.set(X.id,X);let Q=this.sessions.get(X.id);if(Q?.status==="provisioning"&&X.status!=="provisioning")Q.status=X.status;let V=this.connections.get(X.id);if(V)V.remote=X;let j=E(X);if(j||X.status==="failed"||X.status==="suspended"){if(Q)Q.busy=!1,Q.status=j?"expired":X.status,Q.endedAt=j?Date.parse(X.expiredAt??"")||Date.now():Math.max(Q.endedAt??0,Date.parse(X.lastActivityAt??X.createdAt)||0)||void 0;if(V)this.disposeConnection(X.id).catch(()=>{return})}}this.lastListedSessions=Z;for(let X of Z)if(this.sessions.has(X.id))this.publishSnapshot(X.id);return j0(Z)}async handoffTargetExists($){try{return await this.options.api.status($),!0}catch(J){if(J instanceof _&&(J.code==="session_not_found"||J.code==="session_expired"))return!1;throw J}}preserveConnectedRuntimeModel($){let J=this.connections.get($.id)?.remote.metadata,Z=J?.cwd??this.knownSessions.get($.id)?.metadata.cwd;return{...$,metadata:{...$.metadata,...J?.modelId?{modelId:J.modelId}:{},...Z?{cwd:Z}:{}}}}async resolveActiveOrganizationId($){return await this.options.getActiveOrganizationId?.($)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listModels(){if(this.disposed)throw Error("Cloud session manager was disposed");let $=await this.resolveActiveOrganizationId({fresh:!0}),J=await p1(this.options.apiBaseUrl,{isOrganizationSession:Boolean($)});if(this.disposed)throw Error("Cloud session manager was disposed");return J}async prepareHandoffRepository($){let J=await this.resolveActiveOrganizationId(),Z=await this.options.api.listRepositories(J);if(!Z.connected)throw new _("github_not_connected","Connect GitHub before handing this session off to cloud.",Z.connectUrl);let X=(Q)=>Q.trim().replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();if(!Z.repositories.some((Q)=>X(Q.url)===X($)))throw new _("github_not_connected",`The GitHub integration cannot access ${$}. Grant repository access before handing off.`,Z.connectUrl);return J?{organizationId:J}:{}}async listBranches($,J={}){return await this.options.api.listBranches($,await this.resolveActiveOrganizationId(),J)}async listForDiscovery($={}){let J=this.discoveryRefresh??this.list().finally(()=>{if(this.discoveryRefresh===J)this.discoveryRefresh=void 0});this.discoveryRefresh=J;let Z=this.lastListedSessions;if($.timeoutMs===void 0)Z=await J;else{let V,j=await Promise.race([J.then((Y)=>({value:Y}),(Y)=>{if(!(Y instanceof _&&Y.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:Y});return{value:this.lastListedSessions}}),new Promise((Y)=>{V=setTimeout(()=>Y({value:this.lastListedSessions}),Math.max(0,$.timeoutMs??0))})]);if(V)clearTimeout(V);Z=j.value}return[...new Map([...this.unlistedSessions.values(),...Z].map((V)=>[V.id,V])).values()].map((V)=>{let j=o1(V),Y=this.sessions.get(V.id);if(!Y)return j;let W=Y.title?.trim()||V.title?.trim();return{...j,status:Y.status,prompt:Y.prompt,endedAt:Y.endedAt!==void 0?new Date(Y.endedAt).toISOString():j.endedAt,metadata:{...j.metadata??{},title:S0({sessionId:V.id,metadata:W?{title:W}:void 0,prompt:Y.prompt,messages:Y.messages})}}})}async create($){let J=$.requestId?.trim();if(!J)return await this.createOnce($);let Z=this.createRequests.get(J);if(Z)return await Z;let X=this.createOnce($).finally(()=>{if(this.createRequests.get(J)===X)this.createRequests.delete(J)});return this.createRequests.set(J,X),await X}trackProvisioningController($,J){let Z=this.provisioningControllers.get($);if(!Z)Z=new Set,this.provisioningControllers.set($,Z);return Z.add(J),()=>{if(Z.delete(J),Z.size===0)this.provisioningControllers.delete($)}}abortProvisioningControllers($,J){let Z=this.provisioningControllers.get($);if(!Z?.size)return!1;for(let X of Z)X.abort(J);return!0}async waitUntilReady($){this.detachedSessions.delete($),this.assertSessionActive($);let J=new AbortController,Z=this.trackProvisioningController($,J);try{await this.options.api.waitUntilReady($,AbortSignal.any([J.signal,AbortSignal.timeout(610000)])),J.signal.throwIfAborted(),this.assertSessionActive($),await this.refreshKnownSession($)}finally{Z()}}async seedHandoff($,J){p0(J.workspaceRelativePath),this.detachedSessions.delete($);let Z=await this.ensureConnection($,{createInner:!0,handoffSeed:J});if(!Z.innerSessionId)throw Error("Cloud Hub did not return an inner session id");return{innerSessionId:Z.innerSessionId}}async verifyHandoffTranscript($,J,Z={}){let X=await this.ensureConnection($),Q=X.innerSessionId;if(!Q)throw Error("Cloud Hub did not return an inner session id");let V=await X.client.command("session.messages",{sessionId:Q},Q);this.assertSessionActive($,X);let j=V.payload?.messages;if(!Array.isArray(j))throw Error("Cloud runtime returned no transcript after seeding.");if(J.length>0&&j.length===0)throw new e1;if(!(Z.allowAppendedMessages?j.length>=J.length&&L0(J,j.slice(0,J.length)):L0(J,j)))throw new G0(J.length,j.length);X.transcriptKnown=!0;let W=this.sessions.get($);if(W)W.messages=structuredClone(j),this.authoritativeMessages.set($,structuredClone(j)),this.streamingMessages.delete($),this.publishSnapshot($,!0)}async createOnce($){if(this.disposed)throw Error("Cloud session manager was disposed");let J=p0($.workspaceRelativePath),Z=$.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):$.organizationId??void 0,X=$.handoff,Q=!X,V=await this.options.api.create({...$,organizationId:Z,...X&&{handoff:{...X,onOuterSessionCreated:async(z,L)=>{Q=L?.created===!0,await X.onOuterSessionCreated(z,L)}}}});if(!V?.sessionId?.trim())throw new _("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(Q&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(V.sessionId,V.cleanupAuthToken,$.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let j={id:V.sessionId,sandboxType:$.sandboxType,status:V.status,sandboxUrl:V.sandboxUrl,repoContext:{repoUrl:$.repoUrl,...$.branch?.trim()?{branch:$.branch.trim()}:{}},metadata:{modelId:$.modelId,cwd:J},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.knownSessions.set(j.id,j),this.unlistedSessions.set(j.id,j);let{autoApproveTools:Y,thinking:W,reasoningEffort:K}=$;this.pendingInitialTasks.set(j.id,{autoApproveTools:Y,thinking:W,reasoningEffort:K});let G=this.stateFromRecord(j);G.prompt=$.initialPrompt?.trim()||void 0,G.config.mode=$.mode??"act",this.sessions.set(j.id,G);let N;try{if($.handoff){let z=await $.handoff.resolveMessages();this.assertSessionActive(j.id),N=(await this.seedHandoff(j.id,{sourceSessionId:$.handoff.sourceSessionId,messages:z,mode:$.mode,workspaceRelativePath:$.workspaceRelativePath,config:{autoApproveTools:$.autoApproveTools,thinking:$.thinking,reasoningEffort:$.reasoningEffort},onSeeding:$.handoff.onSeeding})).innerSessionId}}catch(z){if(this.disposed&&Q&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(j.id,V.cleanupAuthToken,$.handoff?.onOuterSessionRemoved);throw z}return this.assertSessionActive(j.id),this.notify("chat_session_status",{sessionId:j.id,status:G.status}),{sessionId:j.id,origin:"cloud",executionTarget:"cloud",status:j.status,provider:"cline",model:$.modelId,repoUrl:$.repoUrl,branch:$.branch??"",cwd:J,workspaceRoot:U,...N?{innerSessionId:N}:{},...G.prompt?{prompt:G.prompt}:{}}}async deleteProvisionedSessionAfterDispose($,J,Z){this.knownSessions.delete($),this.unlistedSessions.delete($),this.pendingInitialTasks.delete($),this.sessions.delete($),await this.options.api.delete($,J).then(()=>Z?.($)).catch((X)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:$,error:X})})}async attach($,J){let Z=this.sessionGenerations.get($)??0;if(this.detachedSessions.delete($),J)this.restoreCreationOptions($,J);let X=await this.ensureKnownSession($);if(this.assertSessionActive($),Z!==(this.sessionGenerations.get($)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has($))this.sessions.set($,this.stateFromRecord(X));if(X.status==="provisioning"||X.status==="failed")return u0(X,X.status,this.sessions.get($)?.prompt);if(E(X))return await this.disposeConnection($),await this.attachExpired(X);let Q;try{Q=await this.ensureConnection($)}catch(Y){let W=await this.refreshKnownSession($);if(W&&E(W))return await this.disposeConnection($),await this.attachExpired(W);throw Y}await this.ensureAttached(Q);let V=Q.remote,j=this.sessions.get($);return u0(V,j?.status??V.status,j?.prompt)}async send($,J,Z,X,Q){let V=this.sendAbortTokens.get($),j=this.knownSessions.get($);if(j&&E(j))throw new _("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let Y=await this.ensureConnection($,{createInner:!0}),W=()=>this.disposed||Y.disposed||this.deletingSessions.has($)||this.sendAbortTokens.get($)!==V,K=()=>{if(W())throw Error("Cloud session prompt cancelled")};if(K(),await Y.reconnectResolution,K(),await this.ensureAttached(Y),await Y.reconnectResolution,K(),!Y.transcriptKnown)await this.rehydrateAfterTransportDrop($,Y);K(),await this.updateModel(Y,X),await Y.reconnectResolution,K();let G=Y.innerSessionId;if(!G)throw Error("Cloud Hub session was not initialized");let N=this.sessions.get($),z=Z??(N?.busy?"queue":void 0),L=a(N?.messages??[],N?.promptsInQueue??[],J),F=z!=="queue"&&z!=="steer",q=N&&z!=="queue"?{role:"user",content:[{type:"text",text:J}]}:void 0;if(N&&q)N.messages=[...N.messages,q];let O=()=>{if(N&&q)N.messages=N.messages.filter((A)=>A!==q),this.publishSnapshot($)};if(N&&F){let A=N.status!=="running";if(N.busy=!0,N.status="running",N.prompt||=J,A)this.publishSnapshot($,!1,"status")}let B=this.knownSessions.get($);if(B&&!B.title?.trim()&&!this.titleWrites.has($)){let A=Z1(J);if(A){if(B.title=A,N)N.title=A;let P=this.options.api.updateTitle?.($,A).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get($)===P)this.titleWrites.delete($)});if(P)this.titleWrites.set($,P)}}let D=new Set,H=!1,f=()=>{if(H||W())return;H=!0,this.publish({type:"prompt_accepted",sessionId:$,prompt:J,delivery:z})};try{let A=await Y.client.command("session.send_input",{prompt:J,delivery:z,...Q?.length?{attachments:{userImages:Q}}:{}},G,{timeoutMs:z==="queue"?z6:null,onDispatch:(k)=>{D.add(k),Y.pendingInputs??=new Map,Y.pendingInputs.set(k,{clientId:Y.client.getClientId(),ownsBusyState:F,accept:f})},beforeDispatch:()=>{if(K(),Y.innerSessionId!==G)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.")}});f();let P=z==="queue"||z!=="steer"&&A.payload?.result===void 0;if(P)O();return{sessionId:$,ok:!0,...P?{queued:!0}:{},result:A.payload?.result}}catch(A){if(W())throw O(),A;if(m0(A)||I0(A,"session.send_input")){let P;try{P=await this.rehydrateAfterTransportDrop($,Y)}catch(d){if(K(),O(),N&&F)N.busy=!1,N.status="error";if(z==="queue")throw new a0;throw d}if(K(),z==="queue")throw new a0;if(z==="steer")throw new _("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(a(P.messages,D6(P.prompts,P.submittedPrompts),J)<=L)throw new _("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:$,ok:!0,...z==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:P.status}}if(O(),N&&F)N.busy=!1,N.status="error";throw this.publishSnapshot($),A}finally{for(let A of D)Y.pendingInputs?.delete(A)}}async updateModel($,J){let Z=J?.trim();if(!Z||$.remote.metadata.modelId===Z)return;let X=$.innerSessionId;if(!X)throw Error("Cloud Hub session was not initialized");await $.client.command("session.update_connection",{sessionId:X,updates:{modelId:Z}},X,{beforeDispatch:()=>{if(this.assertSessionActive($.remote.id,$),$.innerSessionId!==X)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive($.remote.id,$),this.applyModel($,Z)}applyModel($,J){$.remote.metadata.modelId=J;let Z=this.sessions.get($.remote.id);if(Z)Z.config.model=J,Z.config.modelId=J}async rehydrateAfterTransportDrop($,J){if(this.assertSessionActive($,J),J.rehydrationPromise)return J.rehydrationRerunRequested=!0,await J.rehydrationPromise;let Z=(async()=>{let X;do J.rehydrationRerunRequested=!1,X=await this.performTransportRehydration($,J),this.assertSessionActive($,J);while(J.rehydrationRerunRequested&&!this.disposed);return X})().finally(()=>{if(J.rehydrationPromise===Z)J.rehydrationPromise=void 0,this.publishSnapshot($)});return J.rehydrationPromise=Z,await Z}async performTransportRehydration($,J){this.assertSessionActive($,J);let Z=J.innerSessionId;if(!Z)throw Error("Cloud Hub session was not initialized");J.bufferingEvents=!0,J.bufferedEvents=[],J.bufferedEventsDropped=0;try{await this.ensureAttached(J),this.assertSessionActive($,J);let X=await J.client.command("session.get",{includeSnapshot:!0},Z);this.assertSessionActive($,J);let Q=X.payload?.session&&typeof X.payload.session==="object"&&!Array.isArray(X.payload.session)?X.payload.session:void 0;this.applySessionModel(J,Q);let V=this.sessions.get($),j=this.authoritativeMessages.get($)??[],Y=String(Q?.status??V?.status??"running").trim(),W=Y==="pending"?"running":Y;if(W==="running"&&!J.transcriptKnown&&!J.pendingInputs?.size)J.externalRun??={progressHydrated:!0};let K=()=>J.client.command("session.messages",{sessionId:Z},Z),G=await K().catch((A)=>{if(!I0(A,"session.messages"))throw A;return this.assertSessionActive($,J),K()});if(this.assertSessionActive($,J),!Array.isArray(G.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let N=G.payload.messages,z=J.bufferedEventsDropped+J.bufferedEvents.length,L=await J.client.command("session.pending_prompts",{sessionId:Z},Z).catch(()=>{return});this.assertSessionActive($,J);let F=J.bufferedEventsDropped+J.bufferedEvents.length;if(V){let A=V.status!==W;if(this.authoritativeMessages.set($,structuredClone(N)),V.messages=structuredClone(N),this.streamingMessages.delete($),V.status=W,V.busy=W==="running",A)if(W==="completed"||W==="failed"||W==="aborted")V.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:$,reason:W==="failed"?"error":W});else this.notify("chat_session_status",{sessionId:$,status:W})}let q=L!==void 0&&L.ok!==!1&&Array.isArray(L.payload?.prompts),O=q?this.applyQueueSnapshot($,L):void 0;J.transcriptKnown=!0;let B=N;this.assertSessionActive($,J),this.notify("cloud_session_rehydrated",{sessionId:$,status:W,transcriptKnown:!0,messages:B}),this.assertSessionActive($,J);let D=J.bufferedEvents,H=h0(D),f=t1(D,N,{queueSnapshotApplied:q,queueSnapshotEventCutoff:Math.max(0,F-J.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,z-J.bufferedEventsDropped),baselineMessages:j});J.bufferedEvents=[],J.bufferingEvents=!1,J.syncFailureNotified=!1;for(let A of f)this.forwardEvent($,J,A);return{status:W,messages:N,prompts:O,submittedPrompts:H}}catch(X){let Q=J.bufferedEvents;J.bufferedEvents=[],J.bufferingEvents=!1,this.assertSessionActive($,J);for(let V of Q)this.forwardEvent($,J,V);if(!J.syncFailureNotified)J.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:$,message:X instanceof Error?X.message:String(X)});throw X}}async abort($){if(this.sendAbortTokens.set($,Symbol()),this.abortProvisioningControllers($,Error("Cloud session prompt cancelled")))return{sessionId:$,ok:!0};let J=await this.ensureConnection($),Z=()=>{if(this.disposed||J.disposed)throw Error("Cloud session connection was disposed")};if(Z(),await J.client.connect(),await J.reconnectResolution,Z(),await this.resolveInnerSession($,J),J.innerSessionId){await this.ensureAttached(J),await J.reconnectResolution,Z();let Q=J.innerSessionId;if(!Q)throw Error("Cloud Hub session was not initialized");await J.client.command("run.abort",{sessionId:Q},Q,{beforeDispatch:()=>{if(Z(),J.innerSessionId!==Q)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}Z();let X=this.sessions.get($);if(X)X.busy=!1,X.status="aborted";return this.publishSnapshot($),{sessionId:$,ok:!0}}async pendingPrompts($){if(this.knownSessions.get($)?.status==="provisioning")return{sessionId:$,promptsInQueue:[]};if(!(await this.ensureConnection($)).innerSessionId)return{sessionId:$,promptsInQueue:[]};let Z=await this.queueCommand($,"session.pending_prompts",{});return{sessionId:$,promptsInQueue:this.applyQueueSnapshot($,Z)}}async updatePendingPrompt($,J,Z){let X=await this.queueCommand($,"session.update_pending_prompt",{promptId:J,...Z});return{sessionId:$,updated:X.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot($,X)}}async removePendingPrompt($,J){let Z=await this.queueCommand($,"session.remove_pending_prompt",{promptId:J});return{sessionId:$,removed:Z.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot($,Z)}}async queueCommand($,J,Z){let X=await this.ensureConnection($),Q=X.innerSessionId;if(!Q)throw Error("Cloud Hub session was not initialized");await X.client.connect(),await X.reconnectResolution,await this.ensureAttached(X),await X.reconnectResolution;let V=await X.client.command(J,{sessionId:Q,...Z},Q,{beforeDispatch:()=>{if(this.assertSessionActive($,X),X.innerSessionId!==Q)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive($,X),V}applyQueueSnapshot($,J){if(!Array.isArray(J.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let X=J.payload.prompts.map((V)=>({id:typeof V.id==="string"?V.id:"",prompt:typeof V.prompt==="string"?V.prompt:"",steer:V.delivery==="steer",attachmentCount:typeof V.attachmentCount==="number"?V.attachmentCount:0,userImages:Array.isArray(V.userImages)?V.userImages.filter((j)=>typeof j==="string"):void 0})).filter((V)=>V.id),Q=this.sessions.get($);if(Q)Q.promptsInQueue=X;return this.publishSnapshot($,!1,"queue"),X}async readMessages($){let J=this.knownSessions.get($);if(J?.status==="provisioning"||J?.status==="failed")return[];if(J&&E(J))return await this.loadArchivedMessages(J)??[];try{let Z=await this.ensureConnection($);if(!Z.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop($,Z)).messages}catch(Z){let X=await this.refreshKnownSession($)??J;if(X){let Q=await this.loadArchivedMessages(X).catch(()=>null);if(Q!==null)return Q}throw Z}}async updateTitle($,J){let Z=this.titleWrites.get($),X=(async()=>{await Z?.catch(()=>{}),this.assertSessionActive($),await this.options.api.updateTitle($,J);let Q=this.knownSessions.get($);if(Q)Q.title=J;let V=this.sessions.get($);if(V)V.title=J;this.publishSnapshot($)})();this.titleWrites.set($,X);try{await X}finally{if(this.titleWrites.get($)===X)this.titleWrites.delete($)}}async delete($){this.deletingSessions.add($),this.abortProvisioningControllers($);try{let J=this.connectionPromises.get($);if(J)await J.catch(()=>{return});await this.disposeConnection($);try{await this.options.api.delete($)}catch(Z){let X=Z instanceof _?Z.code:"";if(X!=="session_not_found"&&X!=="session_expired")throw Z}this.knownSessions.delete($),this.unlistedSessions.delete($),this.pendingInitialTasks.delete($),this.sessions.delete($),this.authoritativeMessages.delete($),this.restoredOptions.delete($),this.publish({type:"removed",sessionId:$}),this.sendAbortTokens.delete($);for(let[Z,X]of this.approvals)if(X.item.sessionId===$)this.approvals.delete(Z)}finally{this.deletingSessions.delete($)}}async dispose(){this.disposed=!0;for(let J of this.snapshotTimers.keys())this.cancelScheduledSnapshot(J);this.sendAbortTokens.clear();for(let J of this.provisioningControllers.values())for(let Z of J)Z.abort();this.provisioningControllers.clear();let $=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[J,Z]of this.approvals)if($.has(Z.item.sessionId))this.approvals.delete(J);for(let J of $)this.sessions.delete(J),this.knownSessions.delete(J),this.publish({type:"removed",sessionId:J});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((J)=>this.disposeConnection(J)))}async attachExpired($){let J=this.sessions.get($.id)??l0($);return J.busy=!1,J.status="expired",this.sessions.set($.id,J),await this.loadArchivedMessages($).catch(()=>{return}),u0($,"expired")}async loadArchivedMessages($){let J=this.sessionGenerations.get($.id),Z=await this.options.api.history($.id);if(this.assertSessionActive($.id),this.sessionGenerations.get($.id)!==J)throw Error("Cloud session attachment changed while loading history");if(Z===null)return null;let X=this.sessions.get($.id)??l0($);return X.messages=structuredClone(Z),this.sessions.set($.id,X),this.authoritativeMessages.set($.id,structuredClone(X.messages)),this.publishSnapshot($.id,!0),Z}async refreshKnownSession($){let J=await this.resolveActiveOrganizationId(),Z=await this.options.api.list(J).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!Z)return this.knownSessions.get($);for(let X of Z)this.knownSessions.set(X.id,X);return Z.find((X)=>X.id===$)}async ensureKnownSession($){let J=this.knownSessions.get($);if(J)return J;let Z=(await this.list()).find((X)=>X.id===$);if(!Z)throw new _("session_not_found",`Cloud session ${$} was not found.`);return this.knownSessions.get($)??structuredClone(Z)}assertSessionActive($,J){if(this.disposed||J?.disposed||this.detachedSessions.has($)||J?.generation!==void 0&&J.generation!==(this.sessionGenerations.get($)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has($))throw new _("session_not_found","This cloud session is being deleted.")}async ensureConnection($,J={}){let Z=this.sessionGenerations.get($)??0,X=()=>{if(this.assertSessionActive($),Z!==(this.sessionGenerations.get($)??0))throw Error("Cloud viewer detached during connection")};X();let Q=this.connectionPromises.get($),V=Q?await Q:this.connections.get($);if(V?.remote.status==="suspended")return await this.disposeConnection($),X(),await this.ensureConnection($,J);if(V){if(this.assertSessionActive($,V),await V.reconnectResolution,this.assertSessionActive($,V),!V.innerSessionId)await V.client.connect(),await V.reconnectResolution,this.assertSessionActive($,V),await this.resolveInnerSession($,V,Boolean(J.handoffSeed)),this.assertSessionActive($,V);if(J.handoffSeed&&V.innerSessionId)await this.assertHandoffConnectionReusable(V,J.handoffSeed);if(J.createInner&&!V.innerSessionId)await this.createInnerSession(V,J.handoffSeed);return this.assertSessionActive($,V),V}let j=(async()=>{let Y=await this.ensureKnownSession($);if(X(),!this.pendingInitialTasks.has($)&&(Y.sandboxType==="resumable"||Y.metadata.sandboxType==="resumable"||Y.status==="suspended")){let N=await this.options.api.status($).catch(async(L)=>{if(!(L instanceof _?L.code==="request_failed"&&(L.status===void 0||L.status===408||L.status===429||L.status>=500):L instanceof TypeError||L instanceof Error&&L.name==="TimeoutError"))throw L;return X(),await this.refreshKnownSession($).catch(()=>{return})});if(X(),N?.status)Y.status=N.status;let z=this.sessions.get($);if(z?.status==="suspended"&&["provisioning","ready","active"].includes(Y.status))z.status=Y.status,z.busy=!1,z.endedAt=void 0}if(Y.status==="suspended"){let N=new AbortController,z=this.trackProvisioningController($,N);try{try{Y=await this.options.api.resume($,N.signal)}catch(F){if(!(F instanceof _)||F.status!==409)throw F;X(),N.signal.throwIfAborted();let q=await this.options.api.status($,{signal:N.signal});if(q.status!=="provisioning"&&q.status!=="ready"&&q.status!=="active")throw F;Y={...Y,status:q.status}}X(),N.signal.throwIfAborted(),this.knownSessions.set($,Y);let L=this.sessions.get($);if(L)L.status=Y.status,L.busy=!1,L.endedAt=void 0;this.publishSnapshot($,!1,"status")}finally{z()}}if(Y.status==="provisioning"){let N=new AbortController,z=this.trackProvisioningController($,N);try{if(await this.options.api.waitUntilReady($,N.signal,({phase:F})=>{Y.metadata.provisioningPhase=F,this.notify("chat_session_status",{sessionId:$,status:"provisioning",phase:F})}),this.disposed)throw Error("Cloud session manager was disposed");if(Y=await this.refreshKnownSession($)??Y,N.signal.throwIfAborted(),Y.status==="provisioning")Y.status="ready";let L=this.sessions.get($);if(L?.status==="provisioning")L.status="idle",L.busy=!1,L.endedAt=void 0}catch(L){if(L instanceof _&&L.code==="session_failed"){if(Y.status="failed",Y.metadata.statusReason=L.detail,Y.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set($,Y);let F=this.sessions.get($);if(F)F.status="error";this.notify("chat_session_status",{sessionId:$,status:"error"})}throw L}finally{z()}}if(X(),Y.status==="failed")throw new _("session_failed",Y.metadata.statusReason||"The cloud sandbox could not be prepared.");if(E(Y))throw new _("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set($,this.sessions.get($)??this.stateFromRecord(Y));let W,K=0,G=this.createHubClient({url:A6(this.options.apiBaseUrl,$),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${$}-${G6()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:U,cwd:U,resolveConnectionHeaders:async()=>{X();let N=K>0;if(K+=1,W)W.connected=!1,W.reconnecting=N,this.publishSnapshot($);if(N){let L=W;if(L&&!L.disposed){L.transcriptKnown=!1,L.innerSessionId=void 0;let F=(async()=>{if(await this.resolveInnerSession($,L),L.innerSessionId)await this.rehydrateAfterTransportDrop($,L)})().catch(()=>this.disposeConnectionIfSessionGone($,L)).finally(()=>{if(L.reconnectResolution===F)L.reconnectResolution=void 0,L.connected=L.transcriptKnown,this.publishSnapshot($)});L.reconnectResolution=F}}let z=await this.options.getAuthToken();if(!z?.trim())throw new _("authentication_required","Sign in to Cline to reconnect this cloud session.");return X(),{Authorization:`Bearer ${z.trim()}`}}});W={generation:Z,remote:Y,client:G,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},W.unsubscribe=G.subscribe(()=>{},{sessionId:Y.metadata.taskId?.trim()||$}),this.connections.set($,W);try{if(await G.connect(),W.connected=!0,this.publishSnapshot($),this.assertSessionActive($,W),await this.resolveInnerSession($,W,Boolean(J.handoffSeed)),this.assertSessionActive($,W),J.handoffSeed&&W.innerSessionId)await this.assertHandoffConnectionReusable(W,J.handoffSeed);if(J.createInner&&!W.innerSessionId)await this.createInnerSession(W,J.handoffSeed);return this.assertSessionActive($,W),W}catch(N){if(m0(N)&&!this.disposed&&!W.disposed&&!this.deletingSessions.has($))throw N;if(this.connections.get($)===W)this.connections.delete($);if(W.disposed=!0,W.unsubscribe(),!this.disposed&&Z===(this.sessionGenerations.get($)??0))this.clearPendingApprovals($);throw await G.dispose().catch(()=>{return}),N}})().finally(()=>{if(this.connectionPromises.get($)===j)this.connectionPromises.delete($)});return this.connectionPromises.set($,j),await j}async resolveInnerSession($,J,Z=!1){if(this.assertSessionActive($,J),J.innerSessionId)return;let X=J.remote.metadata.taskId?.trim(),Q;if(X)try{let Y=await J.client.command("session.get",{sessionId:X},X);this.assertSessionActive($,J),Q=Y.payload?.session&&typeof Y.payload.session==="object"&&!Array.isArray(Y.payload.session)?Y.payload.session:void 0}catch(Y){if(!A0(Y))throw Y}else{let Y=await J.client.command("session.list",{limit:100});this.assertSessionActive($,J),Q=V0(Y.payload).filter(Y0).sort((W,K)=>y0(K)-y0(W))[0]}let V=String(Q?.sessionId??"").trim();if(!V||!Q){if(!Z&&!this.pendingInitialTasks.has($))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}if(J.remote.sandboxType==="resumable"||J.remote.metadata.sandboxType==="resumable")await this.restoreSavedInnerSession(J,V,Q),this.assertSessionActive($,J);this.pendingInitialTasks.delete($),J.innerSessionId=V,this.subscribeToInnerSession($,J);let j=g0(Q);if(j)this.applyModel(J,j);await this.ensureAttached(J)}async restoreSavedInnerSession($,J,Z){let X=()=>$.client.command("session.update_connection",{sessionId:J,updates:{}},J);try{await X();return}catch(F){if(!(A0(F)||F instanceof Error&&F.code==="command_failed"&&F.message===`session not found: ${J}`))throw F}this.assertSessionActive($.remote.id,$);let Q=await $.client.command("session.messages",{},J);this.assertSessionActive($.remote.id,$);let V=Q.payload?.messages;if(!Array.isArray(V)||V.length===0)throw Error("The saved conversation is empty or unavailable.");let j=Z.metadata??{},Y=Z.runtimeOptions??{},W=this.sessions.get($.remote.id)?.config,K=Object.hasOwn(j,"thinking")?j.thinking:W?.thinking,G=Object.hasOwn(j,"reasoningEffort")?j.reasoningEffort:W?.reasoningEffort,N=typeof j.autoApproveTools==="boolean"?j.autoApproveTools:W?.autoApproveTools,z=Z.cwd??Z.workspaceRoot??U,L=Z.workspaceRoot??U;try{let F=await $.client.command("session.create",{workspaceRoot:L,cwd:z,initialMessages:V,metadata:{...j,interactive:!0},sessionConfig:{sessionId:J,providerId:j.provider??"cline",modelId:j.model??j.modelId??$.remote.metadata.modelId,workspaceRoot:L,cwd:z,systemPrompt:Y.systemPrompt??j.systemPrompt??"",mode:Y.mode??j.mode??"act",...typeof K==="boolean"?{thinking:K}:{},...typeof G==="string"?{reasoningEffort:G}:{},...j.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:Y,...typeof N==="boolean"?{toolPolicies:{"*":{autoApprove:N}}}:{}});if(this.assertSessionActive($.remote.id,$),(F.payload?.session?.sessionId??F.payload?.sessionId)!==J)throw Error("Cloud Hub did not restore the requested session.")}catch(F){if(F?.code!=="session_already_exists")throw F;this.assertSessionActive($.remote.id,$),await X()}}async assertHandoffConnectionReusable($,J){let Z=await $.client.command("session.list",{limit:100});this.assertSessionActive($.remote.id,$);let X=V0(Z.payload).filter(Y0),[Q]=X;if(X.length!==1||String(Q?.sessionId??"").trim()!==$.innerSessionId||n1(Q)!==J.sourceSessionId)throw new _("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.")}async createInnerSession($,J){if(this.assertSessionActive($.remote.id,$),$.innerSessionCreation){if(await $.innerSessionCreation,J)await this.assertHandoffConnectionReusable($,J);return}let Z=(async()=>{if(J&&await this.adoptExistingHandoffSession($,J)){this.unconfirmedInnerCreates.delete($.remote.id);return}if(J?.recoverOnly||this.unconfirmedInnerCreates.has($.remote.id))throw new _("request_failed","Cloud conversation creation is still unconfirmed. Wait for it to appear before trying again.");await this.createInnerSessionOnce($,J)})().finally(()=>{$.innerSessionCreation=void 0});return $.innerSessionCreation=Z,await Z}async adoptExistingHandoffSession($,J){let Z=await $.client.command("session.list",{limit:100});this.assertSessionActive($.remote.id,$);let X=V0(Z.payload).filter(Y0);if(X.length===0)return!1;let[Q]=X,V=String(Q?.sessionId??"").trim();if(X.length!==1||!V||n1(Q)!==J.sourceSessionId)throw new _("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return $.innerSessionId=V,this.subscribeToInnerSession($.remote.id,$),this.applySessionModel($,Q),await this.ensureAttached($),!0}async createInnerSessionOnce($,J){let Z=$.remote.metadata.modelId?.trim();if(!Z)throw Error("Cloud session is missing its model id");let X=this.sessions.get($.remote.id),Q=p0(J?.workspaceRelativePath),V=J?.mode??"act";try{await J?.onSeeding?.(),this.assertSessionActive($.remote.id,$)}catch(F){if(J)throw new c0(F);throw F}let j=`cline/${($.remote.metadata.taskId?.trim()||$.remote.id).slice(-8).toLowerCase()}`,Y=$.remote.sandboxType==="resumable"||$.remote.metadata.sandboxType==="resumable",W=`${s1}
7
+ ${g}${y}`)}let i;try{i=await t.symbolicBranch()}catch(u){let g=K(u)===1,y=V(u),w=g?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new _(g?"detached_head":"git_command_failed",y?`${w} (${y})`:w,{cause:u})}if(!i)throw new _("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[a,r,d]=await Promise.all([O(()=>t.branchRemote(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),O(()=>t.branchMergeRef(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),O(t.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!a||a==="."||!r.startsWith("refs/heads/"))throw new _("missing_upstream",`Branch ${i} has no remote branch upstream. Push it with -u before handing off.`);let l=r.slice(11),f=a;if(!Xe(a))try{f=await t.remoteUrl(a)}catch{throw new _("missing_upstream","Could not resolve the upstream remote.")}let c=Xe(f);if(!c)throw new _("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let h;try{h=await t.remoteRefs(a,r)}catch(u){let g=K(u)===2,y=g?`The upstream branch ${l} was not found. Push it before handing off.`:"Could not verify the remote branch. Check your network and GitHub authentication, then try again.";throw new _(g?"remote_branch_missing":"git_command_failed",y)}let p=dn(h,l);if(!p)throw new _("remote_branch_missing",`The upstream branch ${l} was not found. Push it before handing off.`);if(p.toLowerCase()!==d.toLowerCase())throw new _("unpushed_commits",`Local HEAD does not match the upstream branch ${l}. Push the current commit before handing off.`);return{repoUrl:c,branch:l,headSha:d,...s?{workspaceRelativePath:s}:{}}}function le(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function E(e){if(typeof e!=="string")return;return e.trim()||void 0}function un(e){return typeof e==="string"&&e.length>0?e:void 0}function ln(e){let t=E(e.repoUrl),n=E(e.branch),s=E(e.headSha),o=E(e.modelId);if(!t||!n||!s||!o)throw Error("Cloud handoff fingerprint fields cannot be empty.");let i=E(e.organizationId),a=un(e.workspaceRelativePath),r=e.mode;return{repoUrl:t,branch:n,headSha:s,modelId:o,...i?{organizationId:i}:{},...a?{workspaceRelativePath:a}:{},...r?{mode:r}:{}}}function Do(e,t){return e!==void 0&&t!==void 0&&e.repoUrl===t.repoUrl&&e.branch===t.branch&&e.headSha.toLowerCase()===t.headSha.toLowerCase()&&e.modelId===t.modelId&&e.organizationId===t.organizationId&&e.workspaceRelativePath===t.workspaceRelativePath&&e.mode===t.mode}function pn(e){let t=le(e);if(!t||typeof t.repoUrl!=="string"||typeof t.branch!=="string"||typeof t.headSha!=="string"||typeof t.modelId!=="string")return;try{return ln({repoUrl:t.repoUrl,branch:t.branch,headSha:t.headSha,modelId:t.modelId,...typeof t.organizationId==="string"?{organizationId:t.organizationId}:{},...typeof t.workspaceRelativePath==="string"?{workspaceRelativePath:t.workspaceRelativePath}:{},...t.mode==="plan"||t.mode==="yolo"||t.mode==="zen"?{mode:t.mode}:{}})}catch{return}}function Lo(e){let t=le(le(e)?.handoff);if(!t)return;let n=E(t.toCloudSessionId),s=E(t.handedOffAt),o=t.status;if(!n||!s||o!=="pending"&&o!=="complete")return;let i=E(t.innerSessionId),a=E(t.dashboardUrl),r=pn(t.fingerprint);return{toCloudSessionId:n,handedOffAt:s,status:o,...i?{innerSessionId:i}:{},...a?{dashboardUrl:a}:{},...r?{fingerprint:r}:{}}}function Bo(e,t){return{...e??{},handoff:t}}function qo(e){let{handoff:t,cloudHandoffIntent:n,cloudHandoffSeedDispatched:s,...o}=e??{};return o}function No(e,t){let n=t.trim();if(!n)throw Error("Cloud session id cannot be empty.");let s=new URL("/agents",e);return s.searchParams.set("sessionId",n),s.toString()}function Ze(e){return e.map((t)=>{let n=t&&typeof t==="object"?t:{};return{role:n.role,content:n.content}})}function pe(e,t){return e.length===t.length&&JSON.stringify(Ze(e))===JSON.stringify(Ze(t))}class fe extends Error{constructor(e,t){super(`Cloud transcript verification failed (local ${e} messages, cloud ${t}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as fn}from"node:crypto";import{decodeJwtPayload as hn}from"@cline/shared";var mn=610000,gn=3000,B=15000,yn="CLOUD_SESSION_ERROR:",nt="__cline_create_request__:";function st(e){return(e.trim().split(`
8
+ `)[0]??"").trim().slice(0,72)}class m extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${yn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class ot extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function ge(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function bn(e){return`${nt}${e}`.slice(0,255)}function et(e){return e?.startsWith(nt)===!0}function ye(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function he(e){let t=hn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function tt(e){return new Promise((t,n)=>{if(e.aborted){n(e.reason);return}let s=()=>{clearTimeout(o),n(e.reason)},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},gn);e.addEventListener("abort",s,{once:!0})})}function wn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function me(e,t,n,s){let o=wn(t,`Cloud session request failed (${e})`);if(e===401)return new m("authentication_required",o);if(e===404)return new m("session_not_found",o);if(e===410)return new m("session_expired",o);if(e===412)return new m("github_not_connected",o,s??`${ge(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new m("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,e);return new m("request_failed",o,void 0,e)}class vn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=ge(e.apiBaseUrl),this.appBaseUrl=ge(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??mn}async request(e,t={},n,s,o){let i=!1,a;while(!0){let r;try{r=typeof s==="string"?s:await this.options.getAuthToken()}catch(f){if(a)throw me(401,void 0,this.appBaseUrl,n);throw f}if(!r?.trim())throw new m("authentication_required","Sign in to Cline before starting a cloud session.");if(r.trim()===a)throw new m("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?he(r.trim())!==s.subject:r.trim()!==s.token)throw new m("authentication_required","The signed-in account changed during cloud session creation.");s.token=r.trim()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),l=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,a=r.trim();continue}throw me(d.status,l,this.appBaseUrl,n)}return l?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&et(i.title)?void 0:i.title,repoContext:i.repoContext&&typeof i.repoContext==="object"?i.repoContext:{},metadata:{...i.metadata&&typeof i.metadata==="object"?i.metadata:{},...!n&&et(i.title)?{createRequestTitle:i.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let o=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:o.flatMap((i)=>{let a=Number(i.id),r=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(a)||a<=0||!r)return[];let d=String(i.name??"").trim();return[{id:a,name:d,fullName:String(i.full_name??(d||r)).trim(),url:r,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof m&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new m("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,a=n.query?.trim(),r=n.cursor?.trim();if(a)i.set("query",a);if(r)i.set("cursor",r);let d=i.size>0?`${o}?${i}`:o;try{let l=await this.request(d),f=Array.isArray(l)?l:Array.isArray(l?.items)?l.items:[],c=a?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let p=String(h.name??"").trim();return p&&(!Array.isArray(l)||!c||p.toLowerCase().includes(c))?[p]:[]}),nextToken:Array.isArray(l)?"":String(l?.nextToken??"").trim()}}catch(l){if(l instanceof m&&l.code==="session_not_found")return{available:!1,branches:[]};throw l}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new m("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new m("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:he(t)},s=bn(e.requestId?.trim()||fn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new m("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),a=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let p=new m(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(u){if(!(u instanceof m&&(u.code==="session_not_found"||u.code==="session_expired")))throw AggregateError([p,u],"The unusable recovered cloud handoff workspace could not be removed.")}if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.delete(o);throw await e.handoff?.onOuterSessionRemoved?.(c.id),p}await e.handoff?.onOuterSessionCreated(c.id,{created:!1});let h={sessionId:c.id,status:c.status,sandboxUrl:c.sandboxUrl,cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,h);return h};if(o){let c=await i();if(c.length>1)throw new m("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await a(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(p){if(p instanceof m&&(p.code==="session_not_found"||p.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(o),this.unconfirmedHandoffCreates.delete(o);throw p}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:n.token}}if(this.unconfirmedHandoffCreates.has(o))throw new m("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let r=new AbortController,d=setTimeout(()=>r.abort(),this.createTimeoutMs),l,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:r.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new m("request_failed","The cloud session service returned no session id.");l=h,await this.persistHandoffOuterSession(e,h,n,o);let p={sessionId:h,status:c.status?.trim()||"provisioning",sandboxUrl:c.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,p);return p}catch(c){if(l)throw c;let h=!f||c instanceof m&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new ot(c);if(r.signal.aborted||!(c instanceof m)||c instanceof m&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let u=[];try{u=await i()}catch(y){if(e.handoff)throw AggregateError([c,y],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(u.length>1)throw new m("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let g=u[0];if(g){if(e.handoff)return await a(g);return{sessionId:g.id,status:g.status,sandboxUrl:g.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof m&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject:he(s)}:void 0;while(!t.aborted){let i;try{i=await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:AbortSignal.any([t,AbortSignal.timeout(B)])},void 0,o)}catch(r){if(t.aborted)throw r;if(r instanceof m&&r.code!=="request_failed")throw r;await tt(t);continue}let a=i?.status?.trim().toLowerCase();if(n?.({phase:ye(i?.phase)}),a==="ready"||a==="active")return;if(a==="failed")throw new m("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(a!=="provisioning")throw new m("request_failed","The cloud session service returned an unexpected provisioning status.");await tt(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof m)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new m("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw me(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new m("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as go}from"node:crypto";import{posix as ce}from"node:path";import{createSessionId as Bs,ensureLoopbackProxyBypass as Lt,isHubProtocolCompatible as qs,resolveClineBuildEnv as Ns,resolveHubCommandTimeoutMs as $s}from"@cline/shared";import Ws from"ws";var it="session_not_found";class Q extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function be(e){return e instanceof Q||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as ss}from"node:child_process";import{closeSync as os,mkdirSync as is,openSync as rs,readFileSync as as,unlinkSync as ds}from"node:fs";import{basename as cs,dirname as us,join as ls}from"node:path";import{fileURLToPath as ps}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fs,isBunEmbeddedModulePath as hs,isHubDaemonProcess as ms,resolveClineBuildEnv as Et,withResolvedClineBuildEnv as gs}from"@cline/shared";import{createHash as Sn,randomBytes as kn}from"node:crypto";import{mkdir as Ce,open as rt,readFile as lt,rename as Rn,rm as Se,writeFile as _n}from"node:fs/promises";import{dirname as pt,join as ke}from"node:path";import{ensureLoopbackProxyBypass as An,isHubProtocolCompatible as Pn}from"@cline/shared";import{resolveClineDataDir as q,resolveClineDir as oi}from"@cline/shared/storage";var we={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.87",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 Tn="CLINE_HUB_DISCOVERY_PATH",En="CLINE_HUB_BUILD_ID",xn="CLINE_HUB_BUILD_EPOCH_MS",Hn=30000,In=15000,at=100;function Mn(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function On(e){return Sn("sha256").update(e).digest("hex").slice(0,12)}function Un(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function dt(e){return new Promise((t)=>setTimeout(t,e))}function Dn(e){return`${e}.lock`}async function Ln(e){try{let t=JSON.parse(await lt(ke(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function ve(e){await Se(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[En]?.trim();if(e)return e;return"sdk-v1-71d450ce63d4ccfbee8c3fde214c303c75deda3ef2e2520df90f72906f88be4f".trim()||`source-${String(we.version)}`}function Bn(){let e=Number(process.env[xn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1790659791239)?1790659791239:void 0}function Y(e,t=U()){let n=Pn(e);if(!n.compatible)return n;let s=e.buildId?.trim();if(!s)return{compatible:!1,reason:"missing_build"};if(s!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ct(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ut(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((s)=>Number(s));if(n.length===0||n.some((s)=>!Number.isInteger(s)||s<0))return;return n}function qn(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let s=e[n]??0,o=t[n]??0;if(s!==o)return s<o?-1:1}return 0}function ft(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=ct(e.buildEpochMs),i=ct(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let a=ut(e.coreVersion),r=ut(t.coreVersion);if(a&&r){let d=qn(a,r);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function ht(){return{buildId:U(),buildEpochMs:Bn(),coreVersion:String(we.version)}}function X(e,t){let n=t?.self??ht(),s=Y(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return ft(n,e)<=0}function mt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${On(e)}`,n=process.env[Tn]?.trim()||ke(q(),"locks","hub","owners",`${Mn(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e){try{let t=JSON.parse(await lt(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function gt(e,t){await bt(e,async()=>{let n=pt(e);await Ce(n,{recursive:!0});let s=`${e}.${process.pid}.${kn(6).toString("hex")}.tmp`,o;try{o=await rt(s,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
9
+ `,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await Rn(s,e);let i;try{i=await rt(n,"r"),await i.sync()}catch{}finally{await i?.close().catch(()=>{return})}}catch(i){throw await o?.close().catch(()=>{return}),await Se(s,{force:!0}).catch(()=>{return}),i}})}async function D(e){await bt(e,async()=>{await Se(e,{force:!0}).catch(()=>{return})})}async function yt(e,t,n){let s=Dn(e);await Ce(pt(s),{recursive:!0});let o=Date.now()+In;while(!0){try{await Ce(s,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let r=await Ln(s);if(!r){if(Date.now()>=o){await ve(s);continue}await dt(at);continue}let d=Date.now()-Date.parse(r.acquiredAt);if(!Un(r.pid)||d>Hn){await ve(s);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${s}`);await dt(at);continue}try{return await _n(ke(s,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
10
+ `,"utf8"),await n()}finally{await ve(s)}}}function bt(e,t){return yt(`${e}.mutation`,"discovery mutation",t)}function wt(e,t){return yt(e,"startup",t)}async function Z(e,t){An();try{let n=await fetch(t?.authToken?Nn(e):Ct(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let s=await n.json();if(typeof s.protocolVersion!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string")return;return{protocolVersion:s.protocolVersion,minClientProtocolVersion:typeof s.minClientProtocolVersion==="string"?s.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof s.maxClientProtocolVersion==="string"?s.maxClientProtocolVersion:void 0,capabilities:Array.isArray(s.capabilities)?s.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof s.coreVersion==="string"?s.coreVersion:void 0,buildId:typeof s.buildId==="string"?s.buildId:void 0,buildEpochMs:typeof s.buildEpochMs==="number"?s.buildEpochMs:void 0,host:s.host,port:s.port,url:s.url,hubId:typeof s.hubId==="string"?s.hubId:void 0,authToken:typeof s.authToken==="string"?s.authToken:void 0,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:typeof s.startedAt==="string"?s.startedAt:void 0,updatedAt:typeof s.updatedAt==="string"?s.updatedAt:void 0}}catch{return}}function vt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Ct(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function Nn(e){let t=new URL(Ct(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as $n,CLINE_HUB_PORT as Wn,resolveClineBuildEnv as jn}from"@cline/shared";var Fn="CLINE_HUB_HOST",zn="CLINE_HUB_PORT",Gn="CLINE_HUB_PATHNAME",Jn="127.0.0.1",Vn=Wn,Kn="/hub";function St(e){return jn(e)==="development"?$n:Vn}function Qn(e={}){return(e.env??process.env)[Fn]?.trim()||Jn}function Yn(e={}){let n=(e.env??process.env)[zn]?.trim();if(!n)return St(e);let s=Number.parseInt(n,10);if(!Number.isInteger(s)||s<1||s>65535)return St(e);return s}function Xn(e={}){return(e.env??process.env)[Gn]?.trim()||Kn}function kt(e={},t={}){return{host:e.host??Qn(t),port:e.port??Yn(t),pathname:e.pathname??Xn(t)}}import{join as Zn}from"node:path";var es="shared:cline",ts="CLINE_HUB_DISCOVERY_PATH",ns="hub-production";function N(e=es){return mt(`${e}@${U()}`)}function ee(){return{ownerId:ns,discoveryPath:process.env[ts]?.trim()||Zn(q(),"locks","hub","production.json")}}var Rt=15000,ys=200,_t=3000,bs=100,ws=[100,250,500,1000,2000],vs="--cline-hub-daemon",Cs=3,Ss=60000,At=new Map;function ks(e,t=Date.now()){let n=At.get(e);if(!n||t-n.windowStartedAt>Ss)return At.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Cs}function Rs(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function _s(){try{let e=ls(q(),"logs","hub-daemon.log");return is(us(e),{recursive:!0}),{fd:rs(e,"a"),logPath:e}}catch{return}}function As(){return Et()==="production"?ee():N()}function W(e){return X(e)}function Ps(e){try{let t=JSON.parse(as(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function Re(e){try{ds(`${e}.superseded`)}catch{}}function Pt(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function j(e,t){try{return await Z(e,{authToken:t})}catch{return}}async function Tt(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await j(e))?.url)return!0;await new Promise((o)=>setTimeout(o,bs))}return!1}async function Ae(e,t){if(!ks(e.url))return!1;await F(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Ht(e.url,e.authToken).catch(()=>!1);let n=await Tt(e.url,_t);if(!n&&e.pid&&Ts(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Tt(e.url,_t)}if(n)await D(t).catch(()=>{return});return n}function Ts(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Es(e){try{return(await Pe(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function _e(e,t){if(W(e))return"reusable";let n=await F(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await Es(e)){if(n)await F(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let s=await Ae(e,t);if(!s&&n)await F(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return s?"retired":"failed"}async function xs(e){if(Et()!=="production")return;let t=N();if(t.discoveryPath===e.discoveryPath)return;let n=await I(t.discoveryPath);if(n?.url)await Ae(n,t.discoveryPath);else await D(t.discoveryPath).catch(()=>{return})}function Hs(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return ps(new URL(`./entry.${e}`,import.meta.url))}function Is(e,t){if(hs(e))return[vs];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function Ms(e,t){let n=Hs(),s=process.execPath?.trim();if(!s)throw Error("unable to resolve runtime executable for hub daemon");let o=cs(s).toLowerCase().includes("bun"),i=Is(n,o);return{launcher:s,args:[...i,"--cwd",e,...Rs(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...gs(process.env),CLINE_NO_INTERACTIVE:"1",[fs]:"1"}}}function Os(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function Us(e,t={}){if(ms())return;let n=Ms(e,t),s=_s();try{ss(n.launcher,n.args,{detached:!0,stdio:s?["ignore",s.fd,s.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(s)os(s.fd)}}async function Ds(e,t={}){for(let n=0;;n++)try{Us(e,t);return}catch(s){let o=ws[n];if(!Os(s)||o===void 0)throw s;await new Promise((i)=>setTimeout(i,o))}}async function Ls(e,t,n={}){let s=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=kt(n),i=vt(o.host,o.port,o.pathname),a=(u)=>{if(!s)te(u.url,u.authToken);return u};await xs(e).catch(()=>{return});let r=await I(e.discoveryPath),d=r?.url?void 0:Ps(e.discoveryPath),l=!1;if(r?.url){let u=r.authToken;if(!u)l=!0,await Ae(r,e.discoveryPath);else{let g=await j(r.url,u);if(g?.url&&W(g)&&await x(g.url,{authToken:u}))return Re(e.discoveryPath),a({url:g.url,authToken:u});if(g?.url){if(await _e({...g,authToken:u},e.discoveryPath)==="deferred_busy"&&await x(g.url,{authToken:u}))return a({url:g.url,authToken:u})}else await D(e.discoveryPath).catch(()=>{return})}}let f=await j(i);if(f?.url){let u=Pt(f,r??d,i);if(W(f)){let y=[f.authToken,r?.authToken,d?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0);for(let v of y){if(!await x(f.url,{authToken:v}))continue;let A={hubId:f.hubId??`repaired-${f.port}`,protocolVersion:f.protocolVersion,minClientProtocolVersion:f.minClientProtocolVersion,maxClientProtocolVersion:f.maxClientProtocolVersion,capabilities:f.capabilities,coreVersion:f.coreVersion,buildId:f.buildId,authToken:v,host:f.host,port:f.port,url:f.url,pid:f.pid??r?.pid??d?.pid,startedAt:f.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await gt(e.discoveryPath,A)}catch{}return Re(e.discoveryPath),a({url:f.url,authToken:v})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${l?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let g=await _e(u,e.discoveryPath);if(g==="deferred_busy"){for(let y of[u.authToken,r?.authToken].filter((w)=>typeof w==="string"&&w.trim().length>0))if(await x(f.url,{authToken:y}))return a({url:f.url,authToken:y});if(n.allowPortFallback!==!0&&o.port!==0)throw Error(`An older Cline Hub is running at ${i} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(g==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let h=n.allowPortFallback===!0&&o.port!==0?{...o,port:0}:o;await Ds(t,{...h,manageConnectors:n.manageConnectors});let p=Date.now()+Rt;while(Date.now()<p){let u=await I(e.discoveryPath);if(u?.url&&u.authToken){let y=await j(u.url,u.authToken);if(y?.url&&W(y)&&await x(y.url,{authToken:u.authToken}))return Re(e.discoveryPath),a({url:y.url,authToken:u.authToken})}let g=await j(i);if(g?.url&&!W(g)){let y=Pt(g,u??d,i),w=await _e(y,e.discoveryPath);if(w==="deferred_busy"&&u?.authToken&&await x(g.url,{authToken:u.authToken}))return a({url:g.url,authToken:u.authToken});if(w==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((y)=>setTimeout(y,ys))}throw Error(`Timed out after ${Rt}ms waiting for detached hub startup.`)}async function xt(e,t={}){let n=As();return await wt(n.discoveryPath,async()=>Ls(n,e,t))}function js(){return Ns()==="production"?ee():N()}function Fs(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Bt(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return Bt(e.data);return String(e)}function zs(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function It(e){let t=e,n=zs(t.reason);return new k("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Ee,{closeCode:t.code,closeReason:n||void 0})}function Mt(e,t){if(e instanceof k)return e;if(e instanceof Error)return new k("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new k("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new k("hub_connect_failed",n);let s=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new k("hub_connect_failed",s?`Failed to connect to hub at ${t.toString()} (${s} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var Te="*",ne=8000,Gs="cline-hub-auth.",qt=new Map,Nt=new Set,Js=3000;var Ee="Hub connection closed",Vs=250,Ks=5000,Ot=0.5;class k extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Qs(e){return e instanceof k}class xe extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function Ie(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let s=Me(e.toString());return s?qt.get(s):void 0}function Ys(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function Me(e){if(!Ys(e))return;let t=new URL($t(e));return t.search="",t.hash="",t.toString()}function Ut(e){let t=Me(e);return!!t&&Nt.has(t)}function te(e,t){let n=Me(e);if(n){if(Nt.add(n),t?.trim())qt.set(n,t)}return e}class z{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 k("hub_connection_closed",Ee);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||Ie(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,s=this.openSocket(e,t,n),o;this.connectPromise=s.then(async(a)=>{if(o=a,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{a.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let r of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(r));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(a){if(this.connectPromise===i)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=Mt(a,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw a}}async openSocket(e,t,n){let s=this.options.resolveConnectionHeaders,o;if(s){let d;try{o=await Promise.race([Promise.resolve().then(()=>s()),new Promise((l,f)=>{d=setTimeout(()=>{f(new k("hub_connect_timeout",`Timed out resolving hub connection headers after ${ne}ms`))},ne)})])}catch(l){let f=l instanceof k?l:new k("hub_connect_failed",l instanceof Error?l.message:String(l));if(n===this.connectGeneration)this.lastCloseError=f;throw f}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new k("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let i=o?new Ws(e.toString(),{headers:{...o}}):new(Fs())(e.toString(),t?[`${Gs}${t}`]:void 0);this.socket=i;let a=!1,r=new Promise((d,l)=>{let f=!1,c=setTimeout(()=>{if(f)return;f=!0,a=!0;let h=new k("hub_connect_timeout",`Timed out connecting to hub after ${ne}ms`);if(this.socket===i)this.lastCloseError=h,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}l(h)},ne);i.addEventListener("open",()=>{if(f)return;f=!0,clearTimeout(c),d()}),i.addEventListener("error",(h)=>{if(f)return;f=!0,clearTimeout(c);let p=Mt(h,e);if(this.socket===i)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;l(p)}),i.addEventListener("close",(h)=>{if(f)return;f=!0,clearTimeout(c);let p=a?this.lastCloseError:It(h);if(this.socket===i){if(!a)this.lastCloseError=p,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}l(p)})});return i.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(Bt(d)))}),i.addEventListener("close",(d)=>{if(this.socket!==i)return;if(!a)this.lastCloseError=It(d),this.sawSocketClose=!0;this.registered=!1;for(let l of this.pendingReplies.values())l.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await r,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,s={listener:e,sessionId:n};return this.listeners.add(s),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(s))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,s){let o=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,s)}catch(a){if(!i||o>=1||!await this.recoverLocalHubTransport(a))throw a;o+=1}}async commandOnce(e,t,n,s,o=!0){if(o)await this.connect();s?.beforeDispatch?.();let i=Bs("hubreq_");s?.onDispatch?.(i);let a=$s(e,s?.timeoutMs),r=new Promise((l,f)=>{let c=a===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;f(new xe(e,"hub_command_timeout",`Hub command ${e} timed out after ${a}ms (hub=${this.currentUrl}, requestId=${i}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},a);this.pendingReplies.set(i,{resolve:(h)=>{if(c)clearTimeout(c);l(h)},reject:(h)=>{if(c)clearTimeout(c);f(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:a,payload:t}})}catch(l){throw this.pendingReplies.delete(i),l}let d=await r;if(!d.ok){if(d.error?.code===it){let l=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Q(l,d.error.message)}throw new xe(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Ut(this.currentUrl)||!Qs(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Dt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let e=Math.min(Vs*2**this.reconnectAttempt,Ks),t=Math.round(e*(1-Ot)+Math.random()*e*Ot);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Ut(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Dt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new k("hub_connection_closed",Ee);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new k("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),s=(this.subscriptionCounts.get(n)??0)+t;if(s<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,s),t>0&&s===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??Te}subscriptionSessionIdFromKey(e){return e===Te?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let s of[Te,n]){if(!s||!this.subscriptionCounts.has(s))continue;let o=this.lastEventSequenceByKey.get(s)??0;if(t>o)this.lastEventSequenceByKey.set(s,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function $t(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function x(e,t){let n=new z({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function He(e,t){let n=$t(e),s=await Z(n,{authToken:t?.authToken});if(!s)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=U(),i=Y(s,o);if(!i.compatible&&!X(s))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!qs(s).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await x(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function Xs(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,s=new Set;for(let o of t){if(!o||typeof o!=="object")continue;let i=o.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let a of i){let r=a&&typeof a==="object"?a.clientId:void 0;if(typeof r==="string"&&r.trim())s.add(r)}}return{activeSessionCount:n,participantClientCount:s.size}}async function Pe(e,t,n){let s=new z({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await s.command("session.list",{limit:500},void 0,{timeoutMs:Js});return Xs(o.payload)}finally{await s.dispose().catch(()=>{return})}}async function Zs(e,t,n){try{return(await Pe(e,t,n)).activeSessionCount===0}catch{return!1}}async function eo(e,t){let n=`${e.discoveryPath}.superseded`,s=await I(n);if(!s?.url||!s.authToken)return;let o=await He(s.url,{authToken:s.authToken});if(o.status!=="compatible")return;if(await Zs(o.url,s.authToken,t))return;return te(o.url,s.authToken)}async function to(e={}){if(e.endpoint?.trim()){let o=await He(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=js(),n=await I(t.discoveryPath);if(!n?.url)return await eo(t,e);let s=await He(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(s.status==="compatible")return te(s.url,n.authToken);if(s.status==="protocol_mismatch")await D(t.discoveryPath).catch(()=>{return});return}async function Dt(e={}){let t=await to(e);if(t&&await x(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await xt(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function F(e,t,n,s){Lt();let o=new URL(e),i=t?.trim()||Ie(o);if(o.protocol==="ws:")o.protocol="http:";else if(o.protocol==="wss:")o.protocol="https:";if(o.pathname="/drain",o.hash="",n)o.searchParams.set("reason",n);if(s?.off)o.searchParams.set("off","1");return(await fetch(o,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function Ht(e,t){Lt();let n=new URL(e),s=t?.trim()||Ie(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:s?{authorization:`Bearer ${s}`}:void 0})).ok}function no(e,t){if(!e||typeof e!=="object")return;let n=e,s=typeof n.id==="string"?n.id.trim():"";if(!s)return;let o=typeof n.display_name==="string"?n.display_name.trim():typeof n.displayName==="string"?n.displayName.trim():"",i=typeof n.name==="string"?n.name.trim():"";return{id:s,name:o||i||s,catalogId:t}}function Oe(e,t){return Array.isArray(e)?e.flatMap((n)=>{let s=no(n,t);return s?[s]:[]}):[]}async function Wt(e,t={}){let n=e.trim(),s=n.length;while(s>0&&n[s-1]==="/")s--;let o=n.slice(0,s),i=async(g)=>{let y=await(t.fetchImpl??fetch)(`${o}${g}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!y.ok)throw Error(`HTTP ${y.status}`);return await y.json()},a,r;try{[a,r]=await Promise.all([i("/api/v1/ai/cline/models"),i("/api/v1/ai/cline/recommended-models")])}catch(g){throw Error("Could not load the cloud model catalog.",{cause:g})}let d=a&&typeof a==="object"?a:void 0,l=Oe(Array.isArray(a)?a:d?.data,"cline"),f=r&&typeof r==="object"?r:void 0,c=f?.data&&typeof f.data==="object"?f.data:f,h=Oe(c?.clinePass,"cline-pass"),p=Oe(c?.clineCloud,"cline-cloud"),u=new Set;return[...t.isOrganizationSession?[]:h,...p,...l].filter((g)=>{if(u.has(g.id))return!1;return u.add(g.id),!0})}import{formatDisplayUserInput as jt}from"@cline/shared";var so=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function oo(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function io(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function ro(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function ao(e){if(typeof e.content==="string")return{hasAttachment:!1,text:e.content};if(!Array.isArray(e.content))return{hasAttachment:!1,text:"unknown"};let t=!1,n=!1,s=[];for(let o of e.content){if(!o||typeof o!=="object"||Array.isArray(o))continue;let i=o;if(i.type==="text"&&typeof i.text==="string")s.push(i.text);else if(i.type==="tool_result"||i.type==="tool-result")n=!0;else if(i.type==="file"||i.type==="image")t=!0}return{hasAttachment:t&&!n,text:s.join(`
11
+ `)}}function co(e){let t=jt(e);return t.startsWith("[TASK RESUMPTION]")||t==="The user approved switching to act mode. Continue with the approved plan now."}function uo(e){if(oo(e.role)!=="user")return 0;let t=io(e),n=typeof t?.kind==="string"?t.kind:void 0,s=ro(t);if(n==="compaction"||n==="compaction_summary")return s??1;if(s!==void 0)return s;if(n&&so.has(n))return 0;let o=ao(e);if(!o.hasAttachment&&!jt(o.text))return 0;if(!o.hasAttachment&&co(o.text))return 0;return 1}function Ft(e){return uo(e)>0}function ie(e){return Array.isArray(e?.sessions)?e.sessions.filter((t)=>Boolean(t)&&typeof t==="object"&&!Array.isArray(t)):[]}function Ue(e){let t=e.updatedAt;return typeof t==="number"?t:Date.parse(String(t??""))||0}function De(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return String(t?.model??e?.model??"").trim()}function re(e){let t=e.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return!String(t?.parentSessionId??e.parentSessionId??"").trim()}function Vt(e,t="text"){if(!e||typeof e!=="object"||Array.isArray(e))return"";let n=e.content;if(typeof n==="string")return t==="text"?n.trim():"";if(!Array.isArray(n))return"";return n.map((s)=>s&&typeof s==="object"&&!Array.isArray(s)?t==="thinking"&&s.type==="redacted_thinking"?"[redacted]":String(s[t]??""):"").join("").trim()}function se(e){let t=e.trim(),n=t.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(n?n[1]:t).trim()}function G(e,t,n){let s=se(n);return e.filter((o)=>Boolean(o)&&typeof o==="object"&&!Array.isArray(o)&&String(o.role??"").toLowerCase()==="user"&&(s!==""||Ft(o))&&se(Vt(o))===s).length+t.filter((o)=>se(o.prompt)===s).length}function Le(e){return e.flatMap((t)=>{if(t.event!=="session.pending_prompt_submitted")return[];let n=t.payload?.prompt&&typeof t.payload.prompt==="object"&&!Array.isArray(t.payload.prompt)?t.payload.prompt:void 0,s=String(n?.id??"").trim();if(!s)return[];return[{id:s,prompt:String(n?.prompt??""),steer:n?.delivery==="steer",attachmentCount:typeof n?.attachmentCount==="number"?n.attachmentCount:0,userImages:Array.isArray(n?.userImages)?n.userImages.filter((o)=>typeof o==="string"):void 0}]})}var lo=new Set(["run.completed","run.aborted","run.failed"]),po=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function zt(e,t){return e.filter((n)=>Boolean(n)&&typeof n==="object"&&!Array.isArray(n)&&String(n.role??"").toLowerCase()==="assistant").map((n)=>Vt(n,t)).filter(Boolean)}function Gt(e,t,n="text"){let s=new Map;for(let o of zt(t,n))s.set(o,(s.get(o)??0)+1);return zt(e,n).filter((o)=>{let i=s.get(o)??0;if(i===0)return!0;if(i===1)s.delete(o);else s.set(o,i-1);return!1})}function oe(e,t,n=new Set){if(!e||typeof e!=="object")return n;if(Array.isArray(e)){for(let i of e)oe(i,t,n);return n}let s=e,o=t==="tool_use"?s.id:s.tool_use_id;if(s.type===t&&typeof o==="string")n.add(o);for(let i of Object.values(s))oe(i,t,n);return n}function Jt(e,t="assistant"){let n="",s="";for(let o of e)if(o.event===`${t}.delta`)s+=t==="reasoning"&&o.payload?.redacted&&!o.payload?.text?"[redacted]":typeof o.payload?.text==="string"?o.payload.text:"";else if(o.event===`${t}.finished`){let i=o.payload?.[t==="assistant"?"text":"reasoning"],a=typeof i==="string"&&i?i:s;if(a)n=a;s=""}return(n||s).trim()}function Kt(e,t,n={}){let s=n.queueSnapshotApplied!==!1,o=Gt(t,n.baselineMessages??[]),i=Gt(t,n.baselineMessages??[],"thinking"),a=oe(t,"tool_use"),r=oe(t,"tool_result"),d=new Set(e.slice(0,n.messagesSnapshotEventCutoff??e.length)),l=new Set,f=new Map;for(let y of e.slice(0,n.messagesSnapshotEventCutoff??e.length)){let w=Le([y])[0];if(!w)continue;let v=se(w.prompt),A=f.get(v)??Math.max(0,G(t,[],v)-G(n.baselineMessages??[],[],v));if(f.set(v,Math.max(0,A-1)),A>0)l.add(y)}let h=[...s?e.slice(n.queueSnapshotEventCutoff??e.length):e].reverse().find((y)=>y.event==="session.pending_prompts"),p=[],u=[],g=(y)=>{if(u.length===0)return;let w=u.filter((P)=>d.has(P)),v=(P)=>{if(!y)return-1;let S=[...w].reverse().findIndex((tn)=>tn.event===`${P}.finished`),L=S<0?-1:w.length-1-S;return L>=0||u.at(-1)?.event==="run.aborted"?L:w.length-1},A=v("assistant"),H=v("reasoning"),b=Jt(w.slice(0,A+1)),R=b?o.findIndex((P)=>P.endsWith(b)):-1,M=R>=0;if(M)o.splice(R,1);let J=Jt(w.slice(0,H+1),"reasoning"),ue=J?i.findIndex((P)=>P.endsWith(J)):-1;if(ue>=0)i.splice(ue,1);for(let[P,S]of u.entries()){if(l.has(S)){p.push({...S,payload:{...S.payload,transcriptReflected:!0}});continue}if(d.has(S)&&po.has(S.event)&&(S.event.startsWith("reasoning.")?ue>=0&&P<=H:M&&P<=A))continue;if(S.event==="session.pending_prompts"&&S!==h)continue;if(d.has(S)&&S.event.startsWith("tool.")){let L=String(S.payload?.toolCallId??"").trim();if(r.has(L)||S.event==="tool.started"&&a.has(L))continue}p.push(S)}u=[]};for(let y of e)if(u.push(y),lo.has(y.event))g(!0);return g(!1),p}import{formatDisplayUserInput as fo}from"@cline/shared";function ae(e){let t=structuredClone(e),n=(s)=>{if(!s||typeof s!=="object"||Object.isFrozen(s))return;for(let o of Object.values(s))n(o);Object.freeze(s)};return n(t),t}function de(e){let t=e?.trim();return t?fo(t).slice(0,120):void 0}function Be(e){if(typeof e==="string")return e;if(Array.isArray(e)){let t=[];for(let n of e){if(typeof n==="string"){if(n.trim())t.push(n);continue}if(!n||typeof n!=="object")continue;let s=n,o=typeof s.type==="string"?s.type:"",i=o==="text"?String(s.text??""):o==="thinking"?String(s.thinking??""):o==="tool_use"?`[tool] ${String(s.name??"tool_call")}`:o==="tool_result"?`[tool_result]
12
+ ${Be(s.content)}`:o==="image"?"[image]":o==="redacted_thinking"?"[redacted_thinking]":typeof s.text==="string"?s.text:"";if(i.trim())t.push(i)}return t.join(`
13
+ `)}if(e&&typeof e==="object"){let t=e;if(typeof t.text==="string")return t.text}return""}function ho(e){let t=de(e??void 0);if(!t)return;return t.split(`
14
+ `)[0]?.trim().slice(0,70)||void 0}function mo(e){for(let t of["user","assistant"])for(let n of e){if(!n||typeof n!=="object")continue;let s=n;if(s.role!==t)continue;let o=de(Be(s.content));if(!o)continue;return o.split(`
15
+ `)[0]?.trim().slice(0,70)||void 0}return}function qe(e){let t=e.metadata&&typeof e.metadata==="object"?de(e.metadata.title):void 0;if(t)return t.slice(0,70);let n=ho(e.prompt);if(n)return n;let s=e.messages?mo(e.messages):void 0;if(s)return s;return`Session ${e.sessionId.slice(-6)}`}function Qt(e,t,n,s){let o=t.payload??{},i=()=>{let r=n.get(s);if(r===void 0||!e.messages[r]||e.messages[r]?.role!=="assistant")r=e.messages.length,e.messages.push({role:"assistant",content:[]}),n.set(s,r);let d=e.messages[r];if(!Array.isArray(d.content))d.content=[];return d.content},a=(r,d,l)=>{let f=i(),c=f.at(-1);if(c?.type===r)c[d]=`${c[d]??""}${l}`;else f.push({type:r,[d]:l})};switch(t.event){case"assistant.delta":if(typeof o.text==="string")a("text","text",o.text);return;case"reasoning.delta":if(typeof o.text==="string"&&o.text)a("thinking","thinking",o.text);else if(o.redacted===!0)i().push({type:"redacted_thinking",data:""});return;case"assistant.finished":n.delete(s);return;case"assistant.media":if(o.media)i().push({type:"media",media:structuredClone(o.media)});return;case"tool.started":{let r=String(o.toolCallId??"");if(r&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((l)=>l.type==="tool_use"&&l.id===r)))i().push({type:"tool_use",id:r,name:String(o.toolName??"tool"),input:structuredClone(o.input??{})});return}case"tool.finished":{let r=String(o.toolCallId??"");if(r&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((l)=>l.type==="tool_result"&&l.tool_use_id===r)))e.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:r,content:typeof o.output==="string"?o.output:JSON.stringify(o.output??""),is_error:Boolean(o.error)}]}),n.delete(s);return}case"usage.updated":e.usage=structuredClone(o.totals??o.delta??{});return;case"session.pending_prompts":{let r=Array.isArray(o.prompts)?o.prompts:[];e.promptsInQueue=r.map((d)=>({id:String(d.id??""),prompt:String(d.prompt??""),steer:d.delivery==="steer",attachmentCount:typeof d.attachmentCount==="number"?d.attachmentCount:0,userImages:Array.isArray(d.userImages)?d.userImages.filter((l)=>typeof l==="string"):void 0})).filter((d)=>d.id&&(d.prompt||d.attachmentCount));return}case"session.pending_prompt_submitted":{let r=o.prompt,d=String(r?.id??"");if(!d||e.lastQueuedPromptStartId===d)return;if(e.lastQueuedPromptStartId=d,e.promptsInQueue=e.promptsInQueue.filter((l)=>l.id!==d),o.transcriptReflected!==!0)e.messages.push({role:"user",content:[{type:"text",text:String(r?.prompt??"")}]});e.busy=!0,e.status="running",e.endedAt=void 0,n.delete(s);return}case"run.started":case"session.attached":case"session.updated":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;let r=o.session,d=typeof r?.status==="string"?r.status:t.event==="run.started"?"running":e.status,l=d==="pending"?"running":d;if(t.event==="session.updated"&&l==="running"&&e.endedAt!==void 0&&!e.busy)return;let f=e.busy;if(e.status=l,e.busy=l==="running",t.event==="run.started"){if(!f)n.delete(s);e.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;e.status=typeof o.reason==="string"?o.reason:t.event==="run.failed"?"error":t.event==="run.aborted"?"aborted":"completed",e.busy=!1,e.endedAt=Date.now(),n.delete(s);return}}}function Ne(e){return e instanceof Error&&e.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String(e.code))}function $e(e,t){return e instanceof Error&&e.name==="HubCommandError"&&e.code==="hub_command_timeout"&&(!t||e.command===t)}var C="/workspace",yo=30000,bo=2000,wo=2000,Yt="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.";function We(e){if(!e)return C;if(ce.isAbsolute(e)||e.includes("\\")||e.split("/").some((n)=>!n||n==="."||n===".."))throw new m("request_failed","The handoff workspace path must stay inside the repository.");let t=ce.join(C,e);if(!t.startsWith(`${C}/`))throw new m("request_failed","The handoff workspace path must stay inside the repository.");return t}function Je(e){let t=e.metadata.cwd;return typeof t==="string"&&ce.normalize(t)===t&&(t===C||t.startsWith(`${C}/`))?t:C}function Xt(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0,n=t?.handoff&&typeof t.handoff==="object"?t.handoff:void 0;return String(n?.sourceSessionId??"").trim()}class ze extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud conversation creation was not dispatched.",{cause:e});this.name="CloudHandoffSeedRejectedError"}}class Ge extends m{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"}}class en extends Error{constructor(){super("The cloud session was created, but its transcript was not persisted. This cloud runtime cannot durably seed handoff transcripts and must use @cline/core 0.0.72 or newer. Updating the cloud runtime or pod is required; retrying /cloud against this same pod will not help.");this.name="CloudHandoffSeedUnsupportedError"}}function T(e){let t=e.expiredAt?Date.parse(e.expiredAt):Number.NaN;return Number.isFinite(t)&&t<=Date.now()}function vo(e){return e.trim().startsWith("ses-")}function Co(e,t){let n=new URL(`/api/v1/session/${encodeURIComponent(t)}`,e);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.toString()}function je(e){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:e.metadata.modelId??"",modelId:e.metadata.modelId??"",repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",cwd:Je(e),workspaceRoot:C},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse(e.createdAt)||Date.now(),endedAt:T(e)&&e.expiredAt?Date.parse(e.expiredAt):void 0,status:e.status,attachedViaHub:!0}}function Fe(e,t,n){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:t,provider:"cline",model:e.metadata.modelId??"",repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",cwd:Je(e),workspaceRoot:C,...n?.trim()?{prompt:n.trim()}:{},metadata:{origin:"cloud",repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function Zt(e){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:e.status,provider:"cline",model:e.metadata.modelId??"",cwd:Je(e),workspaceRoot:C,repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",startedAt:e.createdAt,...e.lastActivityAt?{lastActivityAt:e.lastActivityAt}:{},endedAt:T(e)?e.expiredAt??void 0:e.status==="failed"?e.lastActivityAt??e.createdAt:void 0,updatedAt:e.updatedAt,...e.title?.trim()?{title:e.title.trim()}:{},metadata:{...e.title?.trim()?{title:e.title.trim()}:{},origin:"cloud",...e.metadata.provisioningPhase?{provisioningPhase:e.metadata.provisioningPhase}:{},repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function So(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function ko(e,t){let n=[...e??[]],s=new Set(n.map((o)=>o.id));for(let o of t)if(!s.has(o.id))n.push(o);return n}class Ro{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;unconfirmedInnerCreates=new Set;createRequests=new Map;provisioningControllers=new Map;sendAbortTokens=new Map;titleWrites=new Map;deletingSessions=new Set;createHubClient;constructor(e){this.options=e;this.pendingInitialTasks=e.pendingInitialTasks??new Map,this.createHubClient=e.createHubClient??((t)=>new z(t))}restoreCreationOptions(e,t){if(this.restoredOptions.set(e,structuredClone(t)),this.pendingInitialTasks.has(e))this.pendingInitialTasks.set(e,{...this.pendingInitialTasks.get(e),...structuredClone(t)});let n=this.sessions.get(e);if(n)Object.assign(n.config,structuredClone(t))}seedSessionState(e,t){if(!this.sessions.has(e))this.sessions.set(e,structuredClone(t))}stateFromRecord(e){let t=je(e);return Object.assign(t.config,this.pendingInitialTasks.get(e.id),this.restoredOptions.get(e.id)),t}getSnapshot(e){let t=this.knownSessions.get(e),n=this.sessions.get(e)??(t?this.stateFromRecord(t):void 0);if(!n)return;let s=this.connections.get(e);return ae({...n,sessionId:e,record:t,approvals:Array.from(this.approvals.values()).filter((o)=>o.item.sessionId===e).map((o)=>o.item),connectionState:this.detachedSessions.has(e)||this.disposed?"detached":s?.reconnectResolution||s?.rehydrationPromise?"reconnecting":s?s.connected?"connected":s.reconnecting?"reconnecting":"connecting":this.connectionPromises.has(e)?"connecting":"detached",transcriptKnown:s?.transcriptKnown??Boolean(t&&T(t))})}subscribe(e,t){let n=(s)=>{if(!t||s.sessionId===t)e(s)};return this.listeners.add(n),()=>{this.listeners.delete(n)}}publish(e){let t=e.type==="snapshot"?Object.freeze(e):ae(e);for(let n of this.listeners)try{n(t)}catch(s){this.options.logger?.error?.("Cloud session subscriber failed",{error:s})}}publishSnapshot(e,t=!1,n){this.cancelScheduledSnapshot(e);let s=this.getSnapshot(e);if(s)this.publish({type:"snapshot",sessionId:e,snapshot:s,replace:t,cause:n});else this.publish({type:"removed",sessionId:e})}snapshotTimers=new Map;cancelScheduledSnapshot(e){clearTimeout(this.snapshotTimers.get(e)),this.snapshotTimers.delete(e)}scheduleSnapshot(e){if(this.disposed||this.detachedSessions.has(e)||this.snapshotTimers.has(e))return;let t=setTimeout(()=>this.publishSnapshot(e),100);t.unref?.(),this.snapshotTimers.set(e,t)}notify(e,t){let n=String(t.sessionId??"");if(e==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:n,message:String(t.message??"Cloud synchronization failed")});else this.publishSnapshot(n,e==="cloud_session_rehydrated",e==="chat_session_status"?"status":e==="chat_session_ended"?"ended":e==="tool_approval_state"?"approvals":void 0)}applyLiveEvent(e,t){let n=this.sessions.get(e);if(n)Qt(n,t,this.streamingMessages,e)}async respondApproval(e,t,n){this.assertSessionActive(e);let s=this.approvals.get(`${e}:${t}`);if(!s){if(!this.connections.has(e))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new m("request_failed","This approval was already resolved or is no longer available.")}await s.resolve(n)}async detach(e){this.detachedSessions.add(e),this.sessionGenerations.set(e,(this.sessionGenerations.get(e)??0)+1),this.connectionPromises.delete(e),this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud viewer detached")),await this.disposeConnection(e),this.publishSnapshot(e)}isCloudSession(e){return vo(e)||this.knownSessions.has(e)||this.connections.has(e)||this.sessions.get(e)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord(e){let t=this.knownSessions.get(e);return t?Zt(t):void 0}async getCrossScopeDiscoveryRecord(e){let t=this.getCachedDiscoveryRecord(e);if(!t)return;try{let s=(await this.options.api.status(e)).status?.trim();return s?{...t,status:s}:t}catch(n){if(n instanceof m&&(n.code==="session_not_found"||n.code==="session_expired")){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e);return}return t}}async list(){if(this.disposed)throw Error("Cloud session controller was disposed");let e=await this.resolveActiveOrganizationId(),t=(await this.options.api.list(e)).map((s)=>this.preserveConnectedRuntimeModel(s));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=t;for(let s of t)this.knownSessions.set(s.id,s),this.unlistedSessions.delete(s.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(s)=>this.getCrossScopeDiscoveryRecord(s)));let n=await Promise.all(t.map(async(s)=>{if(s.status!=="provisioning")return s;let o=await this.options.api.status(s.id).catch(()=>{return}),i=o?.status?.trim();if(!i)return s;return{...s,status:i,metadata:{...s.metadata,...ye(o?.phase)?{provisioningPhase:o?.phase}:{},...o?.statusReason?.trim()?{statusReason:o.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let s of n){this.knownSessions.set(s.id,s);let o=this.sessions.get(s.id);if(o?.status==="provisioning"&&s.status!=="provisioning")o.status=s.status;let i=this.connections.get(s.id);if(i)i.remote=s;let a=T(s);if(a||s.status==="failed"||s.status==="suspended"){if(o)o.busy=!1,o.status=a?"expired":s.status,o.endedAt=a?Date.parse(s.expiredAt??"")||Date.now():Math.max(o.endedAt??0,Date.parse(s.lastActivityAt??s.createdAt)||0)||void 0;if(i)this.disposeConnection(s.id).catch(()=>{return})}}this.lastListedSessions=n;for(let s of n)if(this.sessions.has(s.id))this.publishSnapshot(s.id);return ae(n)}async handoffTargetExists(e){try{return await this.options.api.status(e),!0}catch(t){if(t instanceof m&&(t.code==="session_not_found"||t.code==="session_expired"))return!1;throw t}}preserveConnectedRuntimeModel(e){let t=this.connections.get(e.id)?.remote.metadata,n=t?.cwd??this.knownSessions.get(e.id)?.metadata.cwd;return{...e,metadata:{...e.metadata,...t?.modelId?{modelId:t.modelId}:{},...n?{cwd:n}:{}}}}async resolveActiveOrganizationId(e){return await this.options.getActiveOrganizationId?.(e)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listModels(){if(this.disposed)throw Error("Cloud session manager was disposed");let e=await this.resolveActiveOrganizationId({fresh:!0}),t=await Wt(this.options.apiBaseUrl,{isOrganizationSession:Boolean(e)});if(this.disposed)throw Error("Cloud session manager was disposed");return t}async prepareHandoffRepository(e){let t=await this.resolveActiveOrganizationId(),n=await this.options.api.listRepositories(t);if(!n.connected)throw new m("github_not_connected","Connect GitHub before handing this session off to cloud.",n.connectUrl);let s=(o)=>o.trim().replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();if(!n.repositories.some((o)=>s(o.url)===s(e)))throw new m("github_not_connected",`The GitHub integration cannot access ${e}. Grant repository access before handing off.`,n.connectUrl);return t?{organizationId:t}:{}}async listBranches(e,t={}){return await this.options.api.listBranches(e,await this.resolveActiveOrganizationId(),t)}async listForDiscovery(e={}){let t=this.discoveryRefresh??this.list().finally(()=>{if(this.discoveryRefresh===t)this.discoveryRefresh=void 0});this.discoveryRefresh=t;let n=this.lastListedSessions;if(e.timeoutMs===void 0)n=await t;else{let i,a=await Promise.race([t.then((r)=>({value:r}),(r)=>{if(!(r instanceof m&&r.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:r});return{value:this.lastListedSessions}}),new Promise((r)=>{i=setTimeout(()=>r({value:this.lastListedSessions}),Math.max(0,e.timeoutMs??0))})]);if(i)clearTimeout(i);n=a.value}return[...new Map([...this.unlistedSessions.values(),...n].map((i)=>[i.id,i])).values()].map((i)=>{let a=Zt(i),r=this.sessions.get(i.id);if(!r)return a;let d=r.title?.trim()||i.title?.trim();return{...a,status:r.status,prompt:r.prompt,endedAt:r.endedAt!==void 0?new Date(r.endedAt).toISOString():a.endedAt,metadata:{...a.metadata??{},title:qe({sessionId:i.id,metadata:d?{title:d}:void 0,prompt:r.prompt,messages:r.messages})}}})}async create(e){let t=e.requestId?.trim();if(!t)return await this.createOnce(e);let n=this.createRequests.get(t);if(n)return await n;let s=this.createOnce(e).finally(()=>{if(this.createRequests.get(t)===s)this.createRequests.delete(t)});return this.createRequests.set(t,s),await s}trackProvisioningController(e,t){let n=this.provisioningControllers.get(e);if(!n)n=new Set,this.provisioningControllers.set(e,n);return n.add(t),()=>{if(n.delete(t),n.size===0)this.provisioningControllers.delete(e)}}abortProvisioningControllers(e,t){let n=this.provisioningControllers.get(e);if(!n?.size)return!1;for(let s of n)s.abort(t);return!0}async waitUntilReady(e){this.detachedSessions.delete(e),this.assertSessionActive(e);let t=new AbortController,n=this.trackProvisioningController(e,t);try{await this.options.api.waitUntilReady(e,AbortSignal.any([t.signal,AbortSignal.timeout(610000)])),t.signal.throwIfAborted(),this.assertSessionActive(e),await this.refreshKnownSession(e)}finally{n()}}async seedHandoff(e,t){We(t.workspaceRelativePath),this.detachedSessions.delete(e);let n=await this.ensureConnection(e,{createInner:!0,handoffSeed:t});if(!n.innerSessionId)throw Error("Cloud Hub did not return an inner session id");return{innerSessionId:n.innerSessionId}}async verifyHandoffTranscript(e,t,n={}){let s=await this.ensureConnection(e),o=s.innerSessionId;if(!o)throw Error("Cloud Hub did not return an inner session id");let i=await s.client.command("session.messages",{sessionId:o},o);this.assertSessionActive(e,s);let a=i.payload?.messages;if(!Array.isArray(a))throw Error("Cloud runtime returned no transcript after seeding.");if(t.length>0&&a.length===0)throw new en;if(!(n.allowAppendedMessages?a.length>=t.length&&pe(t,a.slice(0,t.length)):pe(t,a)))throw new fe(t.length,a.length);s.transcriptKnown=!0;let d=this.sessions.get(e);if(d)d.messages=structuredClone(a),this.authoritativeMessages.set(e,structuredClone(a)),this.streamingMessages.delete(e),this.publishSnapshot(e,!0)}async createOnce(e){if(this.disposed)throw Error("Cloud session manager was disposed");let t=We(e.workspaceRelativePath),n=e.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):e.organizationId??void 0,s=e.handoff,o=!s,i=await this.options.api.create({...e,organizationId:n,...s&&{handoff:{...s,onOuterSessionCreated:async(h,p)=>{o=p?.created===!0,await s.onOuterSessionCreated(h,p)}}}});if(!i?.sessionId?.trim())throw new m("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(o&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(i.sessionId,i.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let a={id:i.sessionId,sandboxType:e.sandboxType,status:i.status,sandboxUrl:i.sandboxUrl,repoContext:{repoUrl:e.repoUrl,...e.branch?.trim()?{branch:e.branch.trim()}:{}},metadata:{modelId:e.modelId,cwd:t},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.knownSessions.set(a.id,a),this.unlistedSessions.set(a.id,a);let{autoApproveTools:r,thinking:d,reasoningEffort:l}=e;this.pendingInitialTasks.set(a.id,{autoApproveTools:r,thinking:d,reasoningEffort:l});let f=this.stateFromRecord(a);f.prompt=e.initialPrompt?.trim()||void 0,f.config.mode=e.mode??"act",this.sessions.set(a.id,f);let c;try{if(e.handoff){let h=await e.handoff.resolveMessages();this.assertSessionActive(a.id),c=(await this.seedHandoff(a.id,{sourceSessionId:e.handoff.sourceSessionId,messages:h,mode:e.mode,workspaceRelativePath:e.workspaceRelativePath,config:{autoApproveTools:e.autoApproveTools,thinking:e.thinking,reasoningEffort:e.reasoningEffort},onSeeding:e.handoff.onSeeding})).innerSessionId}}catch(h){if(this.disposed&&o&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(a.id,i.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw h}return this.assertSessionActive(a.id),this.notify("chat_session_status",{sessionId:a.id,status:f.status}),{sessionId:a.id,origin:"cloud",executionTarget:"cloud",status:a.status,provider:"cline",model:e.modelId,repoUrl:e.repoUrl,branch:e.branch??"",cwd:t,workspaceRoot:C,...c?{innerSessionId:c}:{},...f.prompt?{prompt:f.prompt}:{}}}async deleteProvisionedSessionAfterDispose(e,t,n){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),await this.options.api.delete(e,t).then(()=>n?.(e)).catch((s)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:e,error:s})})}async attach(e,t){let n=this.sessionGenerations.get(e)??0;if(this.detachedSessions.delete(e),t)this.restoreCreationOptions(e,t);let s=await this.ensureKnownSession(e);if(this.assertSessionActive(e),n!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has(e))this.sessions.set(e,this.stateFromRecord(s));if(s.status==="provisioning"||s.status==="failed")return Fe(s,s.status,this.sessions.get(e)?.prompt);if(T(s))return await this.disposeConnection(e),await this.attachExpired(s);let o;try{o=await this.ensureConnection(e)}catch(r){let d=await this.refreshKnownSession(e);if(d&&T(d))return await this.disposeConnection(e),await this.attachExpired(d);throw r}await this.ensureAttached(o);let i=o.remote,a=this.sessions.get(e);return Fe(i,a?.status??i.status,a?.prompt)}async send(e,t,n,s,o){let i=this.sendAbortTokens.get(e),a=this.knownSessions.get(e);if(a&&T(a))throw new m("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let r=await this.ensureConnection(e,{createInner:!0}),d=()=>this.disposed||r.disposed||this.deletingSessions.has(e)||this.sendAbortTokens.get(e)!==i,l=()=>{if(d())throw Error("Cloud session prompt cancelled")};if(l(),await r.reconnectResolution,l(),await this.ensureAttached(r),await r.reconnectResolution,l(),!r.transcriptKnown)await this.rehydrateAfterTransportDrop(e,r);l(),await this.updateModel(r,s),await r.reconnectResolution,l();let f=r.innerSessionId;if(!f)throw Error("Cloud Hub session was not initialized");let c=this.sessions.get(e),h=n??(c?.busy?"queue":void 0),p=G(c?.messages??[],c?.promptsInQueue??[],t),u=h!=="queue"&&h!=="steer",g=c&&h!=="queue"?{role:"user",content:[{type:"text",text:t}]}:void 0;if(c&&g)c.messages=[...c.messages,g];let y=()=>{if(c&&g)c.messages=c.messages.filter((b)=>b!==g),this.publishSnapshot(e)};if(c&&u){let b=c.status!=="running";if(c.busy=!0,c.status="running",c.prompt||=t,b)this.publishSnapshot(e,!1,"status")}let w=this.knownSessions.get(e);if(w&&!w.title?.trim()&&!this.titleWrites.has(e)){let b=st(t);if(b){if(w.title=b,c)c.title=b;let R=this.options.api.updateTitle?.(e,b).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get(e)===R)this.titleWrites.delete(e)});if(R)this.titleWrites.set(e,R)}}let v=new Set,A=!1,H=()=>{if(A||d())return;A=!0,this.publish({type:"prompt_accepted",sessionId:e,prompt:t,delivery:h})};try{let b=await r.client.command("session.send_input",{prompt:t,delivery:h,...o?.length?{attachments:{userImages:o}}:{}},f,{timeoutMs:h==="queue"?yo:null,onDispatch:(M)=>{v.add(M),r.pendingInputs??=new Map,r.pendingInputs.set(M,{clientId:r.client.getClientId(),ownsBusyState:u,accept:H})},beforeDispatch:()=>{if(l(),r.innerSessionId!==f)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.")}});H();let R=h==="queue"||h!=="steer"&&b.payload?.result===void 0;if(R)y();return{sessionId:e,ok:!0,...R?{queued:!0}:{},result:b.payload?.result}}catch(b){if(d())throw y(),b;if(Ne(b)||$e(b,"session.send_input")){let R;try{R=await this.rehydrateAfterTransportDrop(e,r)}catch(J){if(l(),y(),c&&u)c.busy=!1,c.status="error";if(h==="queue")throw new Ge;throw J}if(l(),h==="queue")throw new Ge;if(h==="steer")throw new m("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(G(R.messages,ko(R.prompts,R.submittedPrompts),t)<=p)throw new m("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:e,ok:!0,...h==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:R.status}}if(y(),c&&u)c.busy=!1,c.status="error";throw this.publishSnapshot(e),b}finally{for(let b of v)r.pendingInputs?.delete(b)}}async updateModel(e,t){let n=t?.trim();if(!n||e.remote.metadata.modelId===n)return;let s=e.innerSessionId;if(!s)throw Error("Cloud Hub session was not initialized");await e.client.command("session.update_connection",{sessionId:s,updates:{modelId:n}},s,{beforeDispatch:()=>{if(this.assertSessionActive(e.remote.id,e),e.innerSessionId!==s)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive(e.remote.id,e),this.applyModel(e,n)}applyModel(e,t){e.remote.metadata.modelId=t;let n=this.sessions.get(e.remote.id);if(n)n.config.model=t,n.config.modelId=t}async rehydrateAfterTransportDrop(e,t){if(this.assertSessionActive(e,t),t.rehydrationPromise)return t.rehydrationRerunRequested=!0,await t.rehydrationPromise;let n=(async()=>{let s;do t.rehydrationRerunRequested=!1,s=await this.performTransportRehydration(e,t),this.assertSessionActive(e,t);while(t.rehydrationRerunRequested&&!this.disposed);return s})().finally(()=>{if(t.rehydrationPromise===n)t.rehydrationPromise=void 0,this.publishSnapshot(e)});return t.rehydrationPromise=n,await n}async performTransportRehydration(e,t){this.assertSessionActive(e,t);let n=t.innerSessionId;if(!n)throw Error("Cloud Hub session was not initialized");t.bufferingEvents=!0,t.bufferedEvents=[],t.bufferedEventsDropped=0;try{await this.ensureAttached(t),this.assertSessionActive(e,t);let s=await t.client.command("session.get",{includeSnapshot:!0},n);this.assertSessionActive(e,t);let o=s.payload?.session&&typeof s.payload.session==="object"&&!Array.isArray(s.payload.session)?s.payload.session:void 0;this.applySessionModel(t,o);let i=this.sessions.get(e),a=this.authoritativeMessages.get(e)??[],r=String(o?.status??i?.status??"running").trim(),d=r==="pending"?"running":r;if(d==="running"&&!t.transcriptKnown&&!t.pendingInputs?.size)t.externalRun??={progressHydrated:!0};let l=()=>t.client.command("session.messages",{sessionId:n},n),f=await l().catch((b)=>{if(!$e(b,"session.messages"))throw b;return this.assertSessionActive(e,t),l()});if(this.assertSessionActive(e,t),!Array.isArray(f.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let c=f.payload.messages,h=t.bufferedEventsDropped+t.bufferedEvents.length,p=await t.client.command("session.pending_prompts",{sessionId:n},n).catch(()=>{return});this.assertSessionActive(e,t);let u=t.bufferedEventsDropped+t.bufferedEvents.length;if(i){let b=i.status!==d;if(this.authoritativeMessages.set(e,structuredClone(c)),i.messages=structuredClone(c),this.streamingMessages.delete(e),i.status=d,i.busy=d==="running",b)if(d==="completed"||d==="failed"||d==="aborted")i.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:e,reason:d==="failed"?"error":d});else this.notify("chat_session_status",{sessionId:e,status:d})}let g=p!==void 0&&p.ok!==!1&&Array.isArray(p.payload?.prompts),y=g?this.applyQueueSnapshot(e,p):void 0;t.transcriptKnown=!0;let w=c;this.assertSessionActive(e,t),this.notify("cloud_session_rehydrated",{sessionId:e,status:d,transcriptKnown:!0,messages:w}),this.assertSessionActive(e,t);let v=t.bufferedEvents,A=Le(v),H=Kt(v,c,{queueSnapshotApplied:g,queueSnapshotEventCutoff:Math.max(0,u-t.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,h-t.bufferedEventsDropped),baselineMessages:a});t.bufferedEvents=[],t.bufferingEvents=!1,t.syncFailureNotified=!1;for(let b of H)this.forwardEvent(e,t,b);return{status:d,messages:c,prompts:y,submittedPrompts:A}}catch(s){let o=t.bufferedEvents;t.bufferedEvents=[],t.bufferingEvents=!1,this.assertSessionActive(e,t);for(let i of o)this.forwardEvent(e,t,i);if(!t.syncFailureNotified)t.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:e,message:s instanceof Error?s.message:String(s)});throw s}}async abort(e){if(this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud session prompt cancelled")))return{sessionId:e,ok:!0};let t=await this.ensureConnection(e),n=()=>{if(this.disposed||t.disposed)throw Error("Cloud session connection was disposed")};if(n(),await t.client.connect(),await t.reconnectResolution,n(),await this.resolveInnerSession(e,t),t.innerSessionId){await this.ensureAttached(t),await t.reconnectResolution,n();let o=t.innerSessionId;if(!o)throw Error("Cloud Hub session was not initialized");await t.client.command("run.abort",{sessionId:o},o,{beforeDispatch:()=>{if(n(),t.innerSessionId!==o)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}n();let s=this.sessions.get(e);if(s)s.busy=!1,s.status="aborted";return this.publishSnapshot(e),{sessionId:e,ok:!0}}async pendingPrompts(e){if(this.knownSessions.get(e)?.status==="provisioning")return{sessionId:e,promptsInQueue:[]};if(!(await this.ensureConnection(e)).innerSessionId)return{sessionId:e,promptsInQueue:[]};let n=await this.queueCommand(e,"session.pending_prompts",{});return{sessionId:e,promptsInQueue:this.applyQueueSnapshot(e,n)}}async updatePendingPrompt(e,t,n){let s=await this.queueCommand(e,"session.update_pending_prompt",{promptId:t,...n});return{sessionId:e,updated:s.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot(e,s)}}async removePendingPrompt(e,t){let n=await this.queueCommand(e,"session.remove_pending_prompt",{promptId:t});return{sessionId:e,removed:n.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot(e,n)}}async queueCommand(e,t,n){let s=await this.ensureConnection(e),o=s.innerSessionId;if(!o)throw Error("Cloud Hub session was not initialized");await s.client.connect(),await s.reconnectResolution,await this.ensureAttached(s),await s.reconnectResolution;let i=await s.client.command(t,{sessionId:o,...n},o,{beforeDispatch:()=>{if(this.assertSessionActive(e,s),s.innerSessionId!==o)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive(e,s),i}applyQueueSnapshot(e,t){if(!Array.isArray(t.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let s=t.payload.prompts.map((i)=>({id:typeof i.id==="string"?i.id:"",prompt:typeof i.prompt==="string"?i.prompt:"",steer:i.delivery==="steer",attachmentCount:typeof i.attachmentCount==="number"?i.attachmentCount:0,userImages:Array.isArray(i.userImages)?i.userImages.filter((a)=>typeof a==="string"):void 0})).filter((i)=>i.id),o=this.sessions.get(e);if(o)o.promptsInQueue=s;return this.publishSnapshot(e,!1,"queue"),s}async readMessages(e){let t=this.knownSessions.get(e);if(t?.status==="provisioning"||t?.status==="failed")return[];if(t&&T(t))return await this.loadArchivedMessages(t)??[];try{let n=await this.ensureConnection(e);if(!n.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop(e,n)).messages}catch(n){let s=await this.refreshKnownSession(e)??t;if(s){let o=await this.loadArchivedMessages(s).catch(()=>null);if(o!==null)return o}throw n}}async updateTitle(e,t){let n=this.titleWrites.get(e),s=(async()=>{await n?.catch(()=>{}),this.assertSessionActive(e),await this.options.api.updateTitle(e,t);let o=this.knownSessions.get(e);if(o)o.title=t;let i=this.sessions.get(e);if(i)i.title=t;this.publishSnapshot(e)})();this.titleWrites.set(e,s);try{await s}finally{if(this.titleWrites.get(e)===s)this.titleWrites.delete(e)}}async delete(e){this.deletingSessions.add(e),this.abortProvisioningControllers(e);try{let t=this.connectionPromises.get(e);if(t)await t.catch(()=>{return});await this.disposeConnection(e);try{await this.options.api.delete(e)}catch(n){let s=n instanceof m?n.code:"";if(s!=="session_not_found"&&s!=="session_expired")throw n}this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),this.authoritativeMessages.delete(e),this.restoredOptions.delete(e),this.publish({type:"removed",sessionId:e}),this.sendAbortTokens.delete(e);for(let[n,s]of this.approvals)if(s.item.sessionId===e)this.approvals.delete(n)}finally{this.deletingSessions.delete(e)}}async dispose(){this.disposed=!0;for(let t of this.snapshotTimers.keys())this.cancelScheduledSnapshot(t);this.sendAbortTokens.clear();for(let t of this.provisioningControllers.values())for(let n of t)n.abort();this.provisioningControllers.clear();let e=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[t,n]of this.approvals)if(e.has(n.item.sessionId))this.approvals.delete(t);for(let t of e)this.sessions.delete(t),this.knownSessions.delete(t),this.publish({type:"removed",sessionId:t});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((t)=>this.disposeConnection(t)))}async attachExpired(e){let t=this.sessions.get(e.id)??je(e);return t.busy=!1,t.status="expired",this.sessions.set(e.id,t),await this.loadArchivedMessages(e).catch(()=>{return}),Fe(e,"expired")}async loadArchivedMessages(e){let t=this.sessionGenerations.get(e.id),n=await this.options.api.history(e.id);if(this.assertSessionActive(e.id),this.sessionGenerations.get(e.id)!==t)throw Error("Cloud session attachment changed while loading history");if(n===null)return null;let s=this.sessions.get(e.id)??je(e);return s.messages=structuredClone(n),this.sessions.set(e.id,s),this.authoritativeMessages.set(e.id,structuredClone(s.messages)),this.publishSnapshot(e.id,!0),n}async refreshKnownSession(e){let t=await this.resolveActiveOrganizationId(),n=await this.options.api.list(t).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!n)return this.knownSessions.get(e);for(let s of n)this.knownSessions.set(s.id,s);return n.find((s)=>s.id===e)}async ensureKnownSession(e){let t=this.knownSessions.get(e);if(t)return t;let n=(await this.list()).find((s)=>s.id===e);if(!n)throw new m("session_not_found",`Cloud session ${e} was not found.`);return this.knownSessions.get(e)??structuredClone(n)}assertSessionActive(e,t){if(this.disposed||t?.disposed||this.detachedSessions.has(e)||t?.generation!==void 0&&t.generation!==(this.sessionGenerations.get(e)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has(e))throw new m("session_not_found","This cloud session is being deleted.")}async ensureConnection(e,t={}){let n=this.sessionGenerations.get(e)??0,s=()=>{if(this.assertSessionActive(e),n!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during connection")};s();let o=this.connectionPromises.get(e),i=o?await o:this.connections.get(e);if(i?.remote.status==="suspended")return await this.disposeConnection(e),s(),await this.ensureConnection(e,t);if(i){if(this.assertSessionActive(e,i),await i.reconnectResolution,this.assertSessionActive(e,i),!i.innerSessionId)await i.client.connect(),await i.reconnectResolution,this.assertSessionActive(e,i),await this.resolveInnerSession(e,i,Boolean(t.handoffSeed)),this.assertSessionActive(e,i);if(t.handoffSeed&&i.innerSessionId)await this.assertHandoffConnectionReusable(i,t.handoffSeed);if(t.createInner&&!i.innerSessionId)await this.createInnerSession(i,t.handoffSeed);return this.assertSessionActive(e,i),i}let a=(async()=>{let r=await this.ensureKnownSession(e);if(s(),!this.pendingInitialTasks.has(e)&&(r.sandboxType==="resumable"||r.metadata.sandboxType==="resumable"||r.status==="suspended")){let c=await this.options.api.status(e).catch(async(p)=>{if(!(p instanceof m?p.code==="request_failed"&&(p.status===void 0||p.status===408||p.status===429||p.status>=500):p instanceof TypeError||p instanceof Error&&p.name==="TimeoutError"))throw p;return s(),await this.refreshKnownSession(e).catch(()=>{return})});if(s(),c?.status)r.status=c.status;let h=this.sessions.get(e);if(h?.status==="suspended"&&["provisioning","ready","active"].includes(r.status))h.status=r.status,h.busy=!1,h.endedAt=void 0}if(r.status==="suspended"){let c=new AbortController,h=this.trackProvisioningController(e,c);try{try{r=await this.options.api.resume(e,c.signal)}catch(u){if(!(u instanceof m)||u.status!==409)throw u;s(),c.signal.throwIfAborted();let g=await this.options.api.status(e,{signal:c.signal});if(g.status!=="provisioning"&&g.status!=="ready"&&g.status!=="active")throw u;r={...r,status:g.status}}s(),c.signal.throwIfAborted(),this.knownSessions.set(e,r);let p=this.sessions.get(e);if(p)p.status=r.status,p.busy=!1,p.endedAt=void 0;this.publishSnapshot(e,!1,"status")}finally{h()}}if(r.status==="provisioning"){let c=new AbortController,h=this.trackProvisioningController(e,c);try{if(await this.options.api.waitUntilReady(e,c.signal,({phase:u})=>{r.metadata.provisioningPhase=u,this.notify("chat_session_status",{sessionId:e,status:"provisioning",phase:u})}),this.disposed)throw Error("Cloud session manager was disposed");if(r=await this.refreshKnownSession(e)??r,c.signal.throwIfAborted(),r.status==="provisioning")r.status="ready";let p=this.sessions.get(e);if(p?.status==="provisioning")p.status="idle",p.busy=!1,p.endedAt=void 0}catch(p){if(p instanceof m&&p.code==="session_failed"){if(r.status="failed",r.metadata.statusReason=p.detail,r.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set(e,r);let u=this.sessions.get(e);if(u)u.status="error";this.notify("chat_session_status",{sessionId:e,status:"error"})}throw p}finally{h()}}if(s(),r.status==="failed")throw new m("session_failed",r.metadata.statusReason||"The cloud sandbox could not be prepared.");if(T(r))throw new m("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set(e,this.sessions.get(e)??this.stateFromRecord(r));let d,l=0,f=this.createHubClient({url:Co(this.options.apiBaseUrl,e),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${e}-${go()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:C,cwd:C,resolveConnectionHeaders:async()=>{s();let c=l>0;if(l+=1,d)d.connected=!1,d.reconnecting=c,this.publishSnapshot(e);if(c){let p=d;if(p&&!p.disposed){p.transcriptKnown=!1,p.innerSessionId=void 0;let u=(async()=>{if(await this.resolveInnerSession(e,p),p.innerSessionId)await this.rehydrateAfterTransportDrop(e,p)})().catch(()=>this.disposeConnectionIfSessionGone(e,p)).finally(()=>{if(p.reconnectResolution===u)p.reconnectResolution=void 0,p.connected=p.transcriptKnown,this.publishSnapshot(e)});p.reconnectResolution=u}}let h=await this.options.getAuthToken();if(!h?.trim())throw new m("authentication_required","Sign in to Cline to reconnect this cloud session.");return s(),{Authorization:`Bearer ${h.trim()}`}}});d={generation:n,remote:r,client:f,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},d.unsubscribe=f.subscribe(()=>{},{sessionId:r.metadata.taskId?.trim()||e}),this.connections.set(e,d);try{if(await f.connect(),d.connected=!0,this.publishSnapshot(e),this.assertSessionActive(e,d),await this.resolveInnerSession(e,d,Boolean(t.handoffSeed)),this.assertSessionActive(e,d),t.handoffSeed&&d.innerSessionId)await this.assertHandoffConnectionReusable(d,t.handoffSeed);if(t.createInner&&!d.innerSessionId)await this.createInnerSession(d,t.handoffSeed);return this.assertSessionActive(e,d),d}catch(c){if(Ne(c)&&!this.disposed&&!d.disposed&&!this.deletingSessions.has(e))throw c;if(this.connections.get(e)===d)this.connections.delete(e);if(d.disposed=!0,d.unsubscribe(),!this.disposed&&n===(this.sessionGenerations.get(e)??0))this.clearPendingApprovals(e);throw await f.dispose().catch(()=>{return}),c}})().finally(()=>{if(this.connectionPromises.get(e)===a)this.connectionPromises.delete(e)});return this.connectionPromises.set(e,a),await a}async resolveInnerSession(e,t,n=!1){if(this.assertSessionActive(e,t),t.innerSessionId)return;let s=t.remote.metadata.taskId?.trim(),o;if(s)try{let r=await t.client.command("session.get",{sessionId:s},s);this.assertSessionActive(e,t),o=r.payload?.session&&typeof r.payload.session==="object"&&!Array.isArray(r.payload.session)?r.payload.session:void 0}catch(r){if(!be(r))throw r}else{let r=await t.client.command("session.list",{limit:100});this.assertSessionActive(e,t),o=ie(r.payload).filter(re).sort((d,l)=>Ue(l)-Ue(d))[0]}let i=String(o?.sessionId??"").trim();if(!i||!o){if(!n&&!this.pendingInitialTasks.has(e))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}if(t.remote.sandboxType==="resumable"||t.remote.metadata.sandboxType==="resumable")await this.restoreSavedInnerSession(t,i,o),this.assertSessionActive(e,t);this.pendingInitialTasks.delete(e),t.innerSessionId=i,this.subscribeToInnerSession(e,t);let a=De(o);if(a)this.applyModel(t,a);await this.ensureAttached(t)}async restoreSavedInnerSession(e,t,n){let s=()=>e.client.command("session.update_connection",{sessionId:t,updates:{}},t);try{await s();return}catch(u){if(!(be(u)||u instanceof Error&&u.code==="command_failed"&&u.message===`session not found: ${t}`))throw u}this.assertSessionActive(e.remote.id,e);let o=await e.client.command("session.messages",{},t);this.assertSessionActive(e.remote.id,e);let i=o.payload?.messages;if(!Array.isArray(i)||i.length===0)throw Error("The saved conversation is empty or unavailable.");let a=n.metadata??{},r=n.runtimeOptions??{},d=this.sessions.get(e.remote.id)?.config,l=Object.hasOwn(a,"thinking")?a.thinking:d?.thinking,f=Object.hasOwn(a,"reasoningEffort")?a.reasoningEffort:d?.reasoningEffort,c=typeof a.autoApproveTools==="boolean"?a.autoApproveTools:d?.autoApproveTools,h=n.cwd??n.workspaceRoot??C,p=n.workspaceRoot??C;try{let u=await e.client.command("session.create",{workspaceRoot:p,cwd:h,initialMessages:i,metadata:{...a,interactive:!0},sessionConfig:{sessionId:t,providerId:a.provider??"cline",modelId:a.model??a.modelId??e.remote.metadata.modelId,workspaceRoot:p,cwd:h,systemPrompt:r.systemPrompt??a.systemPrompt??"",mode:r.mode??a.mode??"act",...typeof l==="boolean"?{thinking:l}:{},...typeof f==="string"?{reasoningEffort:f}:{},...a.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:r,...typeof c==="boolean"?{toolPolicies:{"*":{autoApprove:c}}}:{}});if(this.assertSessionActive(e.remote.id,e),(u.payload?.session?.sessionId??u.payload?.sessionId)!==t)throw Error("Cloud Hub did not restore the requested session.")}catch(u){if(u?.code!=="session_already_exists")throw u;this.assertSessionActive(e.remote.id,e),await s()}}async assertHandoffConnectionReusable(e,t){let n=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let s=ie(n.payload).filter(re),[o]=s;if(s.length!==1||String(o?.sessionId??"").trim()!==e.innerSessionId||Xt(o)!==t.sourceSessionId)throw new m("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.")}async createInnerSession(e,t){if(this.assertSessionActive(e.remote.id,e),e.innerSessionCreation){if(await e.innerSessionCreation,t)await this.assertHandoffConnectionReusable(e,t);return}let n=(async()=>{if(t&&await this.adoptExistingHandoffSession(e,t)){this.unconfirmedInnerCreates.delete(e.remote.id);return}if(t?.recoverOnly||this.unconfirmedInnerCreates.has(e.remote.id))throw new m("request_failed","Cloud conversation creation is still unconfirmed. Wait for it to appear before trying again.");await this.createInnerSessionOnce(e,t)})().finally(()=>{e.innerSessionCreation=void 0});return e.innerSessionCreation=n,await n}async adoptExistingHandoffSession(e,t){let n=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let s=ie(n.payload).filter(re);if(s.length===0)return!1;let[o]=s,i=String(o?.sessionId??"").trim();if(s.length!==1||!i||Xt(o)!==t.sourceSessionId)throw new m("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return e.innerSessionId=i,this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,o),await this.ensureAttached(e),!0}async createInnerSessionOnce(e,t){let n=e.remote.metadata.modelId?.trim();if(!n)throw Error("Cloud session is missing its model id");let s=this.sessions.get(e.remote.id),o=We(t?.workspaceRelativePath),i=t?.mode??"act";try{await t?.onSeeding?.(),this.assertSessionActive(e.remote.id,e)}catch(u){if(t)throw new ze(u);throw u}let a=`cline/${(e.remote.metadata.taskId?.trim()||e.remote.id).slice(-8).toLowerCase()}`,r=e.remote.sandboxType==="resumable"||e.remote.metadata.sandboxType==="resumable",d=`${Yt}
16
16
 
17
- Do all work for this task on the branch \`${j}\`: 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. `+(Y?"Commit and push only when the user asks. ":`SAVE YOUR WORK: This sandbox is temporary. Push your progress to origin so it remains available outside the sandbox. The branch \`${j}\` is a backup of your work-in-progress, not a finished deliverable, so commit to it freely even when the work is incomplete. Commit regularly as you complete meaningful steps, using clear, descriptive messages. The first time you commit, push the branch with \`git push -u origin ${j}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks.",K=!1,G=$.client.command("session.create",{workspaceRoot:U,cwd:Q,...J?{initialMessages:J.messages}:{},sessionConfig:{...$.remote.metadata.taskId?.trim()?{sessionId:$.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:Z,workspaceRoot:U,cwd:Q,systemPrompt:J?`${s1}
17
+ Do all work for this task on the branch \`${a}\`: 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. `+(r?"Commit and push only when the user asks. ":`SAVE YOUR WORK: This sandbox is temporary. Push your progress to origin so it remains available outside the sandbox. The branch \`${a}\` is a backup of your work-in-progress, not a finished deliverable, so commit to it freely even when the work is incomplete. Commit regularly as you complete meaningful steps, using clear, descriptive messages. The first time you commit, push the branch with \`git push -u origin ${a}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks.",l=!1,f=e.client.command("session.create",{workspaceRoot:C,cwd:o,...t?{initialMessages:t.messages}:{},sessionConfig:{...e.remote.metadata.taskId?.trim()?{sessionId:e.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:n,workspaceRoot:C,cwd:o,systemPrompt:t?`${Yt}
18
18
 
19
- This session was handed off from a local workspace to a fresh Linux clone of ${$.remote.repoContext.repoUrl??"the repository"}@${$.remote.repoContext.branch??"the selected branch"} at ${U}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(Q===U?"":`
19
+ This session was handed off from a local workspace to a fresh Linux clone of ${e.remote.repoContext.repoUrl??"the repository"}@${e.remote.repoContext.branch??"the selected branch"} at ${C}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(o===C?"":`
20
20
 
21
- Continue from the original repository subdirectory at ${Q}.`):W,mode:V,enableTools:!0,...typeof(J?.config?.thinking??X?.config.thinking)==="boolean"?{thinking:J?.config?.thinking??X?.config.thinking}:{},...typeof(J?.config?.reasoningEffort??X?.config.reasoningEffort)==="string"?{reasoningEffort:J?.config?.reasoningEffort??X?.config.reasoningEffort}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:Z,interactive:!0,...J?{handoff:{from:"local",sourceSessionId:J.sourceSessionId,outerSessionId:$.remote.id}}:{}},runtimeOptions:{mode:V},modelSelection:{provider:"cline",model:Z},toolPolicies:{"*":{autoApprove:(J?.config?.autoApproveTools??X?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive($.remote.id,$),onDispatch:()=>{K=!0}}),N;try{N=await G}catch(F){if(J&&!K)throw new c0(F);if(J&&(I0(F,"session.create")||m0(F)))this.unconfirmedInnerCreates.add($.remote.id);throw F}this.assertSessionActive($.remote.id,$);let z=N.payload?.session&&typeof N.payload.session==="object"?N.payload.session:void 0,L=String(z?.sessionId??N.payload?.sessionId??"").trim();if(!L){if(J)this.unconfirmedInnerCreates.add($.remote.id);throw Error("Cloud Hub did not return an inner session id")}if(this.unconfirmedInnerCreates.delete($.remote.id),this.pendingInitialTasks.delete($.remote.id),$.innerSessionId=L,$.remote.metadata.cwd=Q,X)X.config.cwd=Q,X.config.mode=V;this.subscribeToInnerSession($.remote.id,$),this.applySessionModel($,z),$.transcriptKnown=!J}handleEvent($,J,Z){if(this.disposed||J.disposed)return;if(J.innerSessionId&&Z.sessionId&&Z.sessionId!==J.innerSessionId)return;let X=Z.eventId?.trim();if(X&&!(Z.event==="approval.requested"&&Z.sequence===void 0)){if(J.seenEventIds.has(X))return;J.seenEventIds.add(X);while(J.seenEventIds.size>q6){let Q=J.seenEventIds.values().next().value;if(Q)J.seenEventIds.delete(Q)}}if(J.bufferingEvents){if(J.bufferedEvents.push(Z),J.bufferedEvents.length>_6)J.bufferedEvents.shift(),J.bufferedEventsDropped+=1,this.options.logger?.log("Cloud sync event buffer reached its limit",{sessionId:$,severity:"warn"});return}this.forwardEvent($,J,Z)}forwardEvent($,J,Z){if(this.disposed||J.disposed)return;if(Z.event==="session.attached"||Z.event==="session.updated"||Z.event==="session.created")this.applySessionModel(J,Z.payload?.session);if(Z.event==="approval.requested"){this.handleApprovalRequested($,J,Z);return}if(Z.event==="approval.resolved"){let j=String(Z.payload?.approvalId??"").trim();if(j)this.removeApproval($,j);return}if(Z.event==="run.started"){let j=this.sessions.get($)?.busy,Y=Z.payload?.requestId,W=typeof Y==="string"?J.pendingInputs?.get(Y):void 0;if(W&&Z.payload?.clientId===W.clientId){if(W.accept(),W.ownsBusyState)J.externalRun=void 0}else if(typeof Z.payload?.clientId==="string")J.externalRun??={progressHydrated:Boolean(j)}}let X=J.externalRun,Q=Z.event==="run.completed"||Z.event==="run.failed"||Z.event==="run.aborted",V=X&&!X.progressHydrated&&(Z.event==="assistant.delta"||Z.event==="reasoning.delta"||Z.event==="tool.started");if(X&&(V||Q)){if(X.progressHydrated=!0,Q)J.externalRun=void 0;let j=Boolean(J.rehydrationPromise);if(this.rehydrateAfterTransportDrop($,J).catch((Y)=>{if(this.disposed||J.disposed)return;this.notify("cloud_session_sync_failed",{sessionId:$,message:Y instanceof Error?Y.message:"Cloud transcript refresh failed"})}),!j){J.bufferedEvents.push(Z);return}}if(this.applyLiveEvent($,Z),this.publish({type:"hub_event",sessionId:$,event:{...Z,sessionId:$}}),Z.event==="assistant.delta"||Z.event==="reasoning.delta"||Z.event==="tool.updated")this.scheduleSnapshot($);else this.publishSnapshot($)}handleApprovalRequested($,J,Z){this.storePendingApproval($,J,Z.payload),this.sendApprovalSnapshot($)}storePendingApproval($,J,Z){let X=String(Z?.approvalId??"").trim();if(!X)return;let Q=`${$}:${X}`,V={approvalId:X,requestId:Q,sessionId:$,createdAt:new Date(typeof Z?.createdAt==="number"?Z.createdAt:Date.now()).toISOString(),toolCallId:String(Z?.toolCallId??""),toolName:String(Z?.toolName??"tool"),input:B6(Z?.inputJson),iteration:typeof Z?.iteration==="number"?Z.iteration:void 0,agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0};this.approvals.set(Q,{item:V,resolve:async(j)=>{if(this.disposed||J.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");if(await this.ensureAttached(J),this.disposed||J.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");await J.client.command("approval.respond",{approvalId:X,approved:j.approved,reason:j.reason},J.innerSessionId)}})}removeApproval($,J){this.approvals.delete(`${$}:${J}`),this.sendApprovalSnapshot($)}clearPendingApprovals($){for(let[J,Z]of this.approvals)if(Z.item.sessionId===$)this.approvals.delete(J);this.sendApprovalSnapshot($)}sendApprovalSnapshot($){this.notify("tool_approval_state",{sessionId:$,items:Array.from(this.approvals.values()).filter((J)=>J.item.sessionId===$).map((J)=>J.item)})}async ensureAttached($){if(this.assertSessionActive($.remote.id,$),!$.innerSessionId)return;let J=await $.client.command("session.attach",{sessionId:$.innerSessionId},$.innerSessionId);this.assertSessionActive($.remote.id,$),this.applySessionModel($,J.payload?.session)}subscribeToInnerSession($,J){let Z=J.innerSessionId;if(!Z)return;J.unsubscribe(),this.clearPendingApprovals($),J.unsubscribe=J.client.subscribe((X)=>this.handleEvent($,J,X),{sessionId:Z})}applySessionModel($,J){if(!J||typeof J!=="object"||Array.isArray(J))return;let Z=g0(J);if(Z)this.applyModel($,Z);let X=J,Q=typeof X.cwd==="string"&&N0.normalize(X.cwd)===X.cwd&&(X.cwd===U||X.cwd.startsWith(`${U}/`))?X.cwd:void 0;if(Q){$.remote.metadata.cwd=Q;let Y=this.sessions.get($.remote.id);if(Y)Y.config.cwd=Q}let V=this.sessions.get($.remote.id),j=X.runtimeOptions?.mode;if(V&&(j==="act"||j==="plan"||j==="yolo"||j==="zen"))V.config.mode=j}async disposeConnection($){this.cancelScheduledSnapshot($);let J=this.connections.get($);if(this.connections.delete($),!J)return;J.disposed=!0,J.pendingInputs?.clear(),J.unsubscribe(),this.clearPendingApprovals($),await J.client.dispose()}async disposeConnectionIfSessionGone($,J){if(J.disposed||this.disposed)return;let Z;try{Z=await this.resolveActiveOrganizationId()}catch{return}let X=await this.options.api.list(Z).catch(()=>{return});if(!X||J.disposed)return;let Q=X.find((j)=>j.id===$),V=Q?this.preserveConnectedRuntimeModel(Q):void 0;if(!V){await this.disposeConnection($).catch(()=>{return});return}if(this.knownSessions.set($,V),J.remote=V,V.status==="failed"||V.status==="suspended"){let j=this.sessions.get($);if(j)j.busy=!1,j.status=V.status,j.endedAt=Date.parse(V.updatedAt)||Date.now();await this.disposeConnection($).catch(()=>{return});return}if(E(V))await this.attachExpired(V).catch(()=>{return}),await this.disposeConnection($).catch(()=>{return})}}export{y0 as updatedAt,h0 as submittedPromptsFromEvents,v0 as stringifyMessageContent,g0 as sessionRowModelId,S0 as resolveSessionListTitle,t1 as reconcileBufferedCloudEvents,V0 as readSessionRows,y6 as readCloudHandoffMetadata,f6 as preflightCloudHandoffGit,O0 as parseCloudProvisioningPhase,W0 as normalizeSessionTitle,n0 as normalizeGitHubRemoteUrl,g6 as mergeCloudHandoffMetadata,p1 as loadCloudModels,Y0 as isRootSessionRow,O6 as isCloudOuterSessionId,Z1 as deriveCloudSessionTitle,N2 as createCloudHandoffFingerprint,a as countPromptOccurrences,o1 as cloudSessionToDiscoveryRecord,L0 as cloudHandoffTranscriptsEqual,k6 as cloudHandoffFingerprintsEqual,h6 as clearCloudHandoffMetadata,v6 as buildCloudHandoffDashboardUrl,_ as CloudSessionError,U6 as CloudSessionController,A2 as CloudSessionApi,a0 as CloudQueueUnconfirmedError,G0 as CloudHandoffTranscriptMismatchError,e1 as CloudHandoffSeedUnsupportedError,c0 as CloudHandoffSeedRejectedError,C as CloudHandoffGitPreflightError,X1 as CloudHandoffCreationRejectedError};
21
+ Continue from the original repository subdirectory at ${o}.`):d,mode:i,enableTools:!0,...typeof(t?.config?.thinking??s?.config.thinking)==="boolean"?{thinking:t?.config?.thinking??s?.config.thinking}:{},...typeof(t?.config?.reasoningEffort??s?.config.reasoningEffort)==="string"?{reasoningEffort:t?.config?.reasoningEffort??s?.config.reasoningEffort}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:n,interactive:!0,...t?{handoff:{from:"local",sourceSessionId:t.sourceSessionId,outerSessionId:e.remote.id}}:{}},runtimeOptions:{mode:i},modelSelection:{provider:"cline",model:n},toolPolicies:{"*":{autoApprove:(t?.config?.autoApproveTools??s?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive(e.remote.id,e),onDispatch:()=>{l=!0}}),c;try{c=await f}catch(u){if(t&&!l)throw new ze(u);if(t&&($e(u,"session.create")||Ne(u)))this.unconfirmedInnerCreates.add(e.remote.id);throw u}this.assertSessionActive(e.remote.id,e);let h=c.payload?.session&&typeof c.payload.session==="object"?c.payload.session:void 0,p=String(h?.sessionId??c.payload?.sessionId??"").trim();if(!p){if(t)this.unconfirmedInnerCreates.add(e.remote.id);throw Error("Cloud Hub did not return an inner session id")}if(this.unconfirmedInnerCreates.delete(e.remote.id),this.pendingInitialTasks.delete(e.remote.id),e.innerSessionId=p,e.remote.metadata.cwd=o,s)s.config.cwd=o,s.config.mode=i;this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,h),e.transcriptKnown=!t}handleEvent(e,t,n){if(this.disposed||t.disposed)return;if(t.innerSessionId&&n.sessionId&&n.sessionId!==t.innerSessionId)return;let s=n.eventId?.trim();if(s&&!(n.event==="approval.requested"&&n.sequence===void 0)){if(t.seenEventIds.has(s))return;t.seenEventIds.add(s);while(t.seenEventIds.size>wo){let o=t.seenEventIds.values().next().value;if(o)t.seenEventIds.delete(o)}}if(t.bufferingEvents){if(t.bufferedEvents.push(n),t.bufferedEvents.length>bo)t.bufferedEvents.shift(),t.bufferedEventsDropped+=1,this.options.logger?.log("Cloud sync event buffer reached its limit",{sessionId:e,severity:"warn"});return}this.forwardEvent(e,t,n)}forwardEvent(e,t,n){if(this.disposed||t.disposed)return;if(n.event==="session.attached"||n.event==="session.updated"||n.event==="session.created")this.applySessionModel(t,n.payload?.session);if(n.event==="approval.requested"){this.handleApprovalRequested(e,t,n);return}if(n.event==="approval.resolved"){let a=String(n.payload?.approvalId??"").trim();if(a)this.removeApproval(e,a);return}if(n.event==="run.started"){let a=this.sessions.get(e)?.busy,r=n.payload?.requestId,d=typeof r==="string"?t.pendingInputs?.get(r):void 0;if(d&&n.payload?.clientId===d.clientId){if(d.accept(),d.ownsBusyState)t.externalRun=void 0}else if(typeof n.payload?.clientId==="string")t.externalRun??={progressHydrated:Boolean(a)}}let s=t.externalRun,o=n.event==="run.completed"||n.event==="run.failed"||n.event==="run.aborted",i=s&&!s.progressHydrated&&(n.event==="assistant.delta"||n.event==="reasoning.delta"||n.event==="tool.started");if(s&&(i||o)){if(s.progressHydrated=!0,o)t.externalRun=void 0;let a=Boolean(t.rehydrationPromise);if(this.rehydrateAfterTransportDrop(e,t).catch((r)=>{if(this.disposed||t.disposed)return;this.notify("cloud_session_sync_failed",{sessionId:e,message:r instanceof Error?r.message:"Cloud transcript refresh failed"})}),!a){t.bufferedEvents.push(n);return}}if(this.applyLiveEvent(e,n),this.publish({type:"hub_event",sessionId:e,event:{...n,sessionId:e}}),n.event==="assistant.delta"||n.event==="reasoning.delta"||n.event==="tool.updated")this.scheduleSnapshot(e);else this.publishSnapshot(e)}handleApprovalRequested(e,t,n){this.storePendingApproval(e,t,n.payload),this.sendApprovalSnapshot(e)}storePendingApproval(e,t,n){let s=String(n?.approvalId??"").trim();if(!s)return;let o=`${e}:${s}`,i={approvalId:s,requestId:o,sessionId:e,createdAt:new Date(typeof n?.createdAt==="number"?n.createdAt:Date.now()).toISOString(),toolCallId:String(n?.toolCallId??""),toolName:String(n?.toolName??"tool"),input:So(n?.inputJson),iteration:typeof n?.iteration==="number"?n.iteration:void 0,agentId:typeof n?.agentId==="string"?n.agentId:void 0,conversationId:typeof n?.conversationId==="string"?n.conversationId:void 0};this.approvals.set(o,{item:i,resolve:async(a)=>{if(this.disposed||t.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");if(await this.ensureAttached(t),this.disposed||t.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");await t.client.command("approval.respond",{approvalId:s,approved:a.approved,reason:a.reason},t.innerSessionId)}})}removeApproval(e,t){this.approvals.delete(`${e}:${t}`),this.sendApprovalSnapshot(e)}clearPendingApprovals(e){for(let[t,n]of this.approvals)if(n.item.sessionId===e)this.approvals.delete(t);this.sendApprovalSnapshot(e)}sendApprovalSnapshot(e){this.notify("tool_approval_state",{sessionId:e,items:Array.from(this.approvals.values()).filter((t)=>t.item.sessionId===e).map((t)=>t.item)})}async ensureAttached(e){if(this.assertSessionActive(e.remote.id,e),!e.innerSessionId)return;let t=await e.client.command("session.attach",{sessionId:e.innerSessionId},e.innerSessionId);this.assertSessionActive(e.remote.id,e),this.applySessionModel(e,t.payload?.session)}subscribeToInnerSession(e,t){let n=t.innerSessionId;if(!n)return;t.unsubscribe(),this.clearPendingApprovals(e),t.unsubscribe=t.client.subscribe((s)=>this.handleEvent(e,t,s),{sessionId:n})}applySessionModel(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return;let n=De(t);if(n)this.applyModel(e,n);let s=t,o=typeof s.cwd==="string"&&ce.normalize(s.cwd)===s.cwd&&(s.cwd===C||s.cwd.startsWith(`${C}/`))?s.cwd:void 0;if(o){e.remote.metadata.cwd=o;let r=this.sessions.get(e.remote.id);if(r)r.config.cwd=o}let i=this.sessions.get(e.remote.id),a=s.runtimeOptions?.mode;if(i&&(a==="act"||a==="plan"||a==="yolo"||a==="zen"))i.config.mode=a}async disposeConnection(e){this.cancelScheduledSnapshot(e);let t=this.connections.get(e);if(this.connections.delete(e),!t)return;t.disposed=!0,t.pendingInputs?.clear(),t.unsubscribe(),this.clearPendingApprovals(e),await t.client.dispose()}async disposeConnectionIfSessionGone(e,t){if(t.disposed||this.disposed)return;let n;try{n=await this.resolveActiveOrganizationId()}catch{return}let s=await this.options.api.list(n).catch(()=>{return});if(!s||t.disposed)return;let o=s.find((a)=>a.id===e),i=o?this.preserveConnectedRuntimeModel(o):void 0;if(!i){await this.disposeConnection(e).catch(()=>{return});return}if(this.knownSessions.set(e,i),t.remote=i,i.status==="failed"||i.status==="suspended"){let a=this.sessions.get(e);if(a)a.busy=!1,a.status=i.status,a.endedAt=Date.parse(i.updatedAt)||Date.now();await this.disposeConnection(e).catch(()=>{return});return}if(T(i))await this.attachExpired(i).catch(()=>{return}),await this.disposeConnection(e).catch(()=>{return})}}export{ot as CloudHandoffCreationRejectedError,_ as CloudHandoffGitPreflightError,ze as CloudHandoffSeedRejectedError,en as CloudHandoffSeedUnsupportedError,fe as CloudHandoffTranscriptMismatchError,Ge as CloudQueueUnconfirmedError,vn as CloudSessionApi,Ro as CloudSessionController,m as CloudSessionError,No as buildCloudHandoffDashboardUrl,qo as clearCloudHandoffMetadata,Do as cloudHandoffFingerprintsEqual,pe as cloudHandoffTranscriptsEqual,Zt as cloudSessionToDiscoveryRecord,G as countPromptOccurrences,ln as createCloudHandoffFingerprint,st as deriveCloudSessionTitle,vo as isCloudOuterSessionId,re as isRootSessionRow,Wt as loadCloudModels,Bo as mergeCloudHandoffMetadata,Xe as normalizeGitHubRemoteUrl,de as normalizeSessionTitle,ye as parseCloudProvisioningPhase,Oo as preflightCloudHandoffGit,Lo as readCloudHandoffMetadata,ie as readSessionRows,Kt as reconcileBufferedCloudEvents,qe as resolveSessionListTitle,De as sessionRowModelId,Be as stringifyMessageContent,Le as submittedPromptsFromEvents,Ue as updatedAt};