@cerebriline/core 4.100.247 → 4.100.249

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/assets/prompt-templates/claude.md +9 -0
  2. package/assets/prompt-templates/deepseek.md +9 -0
  3. package/assets/prompt-templates/default.md +49 -1
  4. package/assets/prompt-templates/gemma.md +9 -0
  5. package/assets/prompt-templates/glm.md +9 -0
  6. package/assets/prompt-templates/kimi-k3.md +9 -0
  7. package/assets/prompt-templates/kimi.md +9 -0
  8. package/assets/prompt-templates/minimax.md +12 -1
  9. package/assets/prompt-templates/nemotron.md +9 -0
  10. package/assets/prompt-templates/qwen.md +9 -0
  11. package/assets/skills/media-audio/SKILL.md +55 -0
  12. package/assets/skills/media-images/SKILL.md +102 -0
  13. package/assets/skills/media-video/SKILL.md +53 -0
  14. package/dist/cloud/index.js +16 -16
  15. package/dist/extensions/context/capped-thinking.d.ts +14 -0
  16. package/dist/extensions/context/compaction-shared.d.ts +46 -0
  17. package/dist/extensions/context/continuation-compaction.d.ts +18 -0
  18. package/dist/extensions/tools/icon-generation.d.ts +74 -0
  19. package/dist/extensions/tools/image-generation.d.ts +25 -1
  20. package/dist/extensions/tools/media-tools.d.ts +8 -0
  21. package/dist/extensions/tools/render-image.d.ts +139 -0
  22. package/dist/extensions/tools/transform-image.d.ts +148 -0
  23. package/dist/hub/client/index.d.ts +13 -0
  24. package/dist/hub/daemon/entry.js +576 -572
  25. package/dist/hub/index.js +552 -548
  26. package/dist/index.d.ts +3 -0
  27. package/dist/index.js +1088 -896
  28. package/dist/remote/remote-helper-entry.js +4 -4
  29. package/dist/remote/remote-helper.js +4 -4
  30. package/dist/types/config.d.ts +7 -0
  31. package/package.json +4 -4
@@ -1,21 +1,21 @@
1
- import{execFile as J2}from"node:child_process";import{basename as P4,resolve as Z2}from"node:path";import{promisify as X2}from"node:util";import{processWorkspaceInfo as x4}from"@cerebriline/shared";import i0 from"simple-git";var Q2=X2(J2);function j2($,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 t($){if(!$||typeof $!=="object"||!("stderr"in $))return"";return typeof $.stderr==="string"?$.stderr.trim():""}function r($){if(!$||typeof $!=="object"||!("code"in $))return;return typeof $.code==="number"?$.code:void 0}function t0($){let J=r0($.cwd),Z=$.git??j2,X=async(j)=>(await Z(j,{cwd:J,signal:$.signal})).stdout,Q=async(j)=>(await X(j)).trim();return{async isInsideWorkTree(){try{return await Q(["rev-parse","--is-inside-work-tree"])==="true"}catch(j){if(r(j)===128&&/not a git repository|Kein Git-Repository/i.test(t(j)))return!1;throw j}},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:(j)=>Q(["config","--get",`branch.${j}.remote`]),branchMergeRef:(j)=>Q(["config","--get",`branch.${j}.merge`]),remoteUrl:(j)=>Q(["remote","get-url",j]),remoteRefs:(j,V)=>Q(["ls-remote","--exit-code",j,V])}}function r0($){return Z2($)}class H 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=t(X);throw new H(J,Q?`${Z} (${Q})`:Z,{cause:X})}}function V2($,J){let Z=`refs/heads/${J}`;for(let X of $.split(`
2
- `)){let[Q,j]=X.trim().split(/\s+/,2);if(j===Z&&/^[0-9a-f]{40,64}$/i.test(Q??""))return Q??null}return null}function Y2($){let J=$.replace(/[\r\n]+$/,"").replace(/\/+$/,"");if(!J)return;let Z=J.split("/");if(J.startsWith("/")||Z.some((X)=>!X||X==="."||X===".."))throw new H("git_command_failed","Could not resolve the workspace path relative to the Git repository.");return J}async function f4($){let J=t0($);if(!await y(J.isInsideWorkTree,"not_git_repository","Cloud handoff requires a Git repository."))throw new H("not_git_repository","Cloud handoff requires a Git working tree.");let X=Y2(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 L=Q.split(`
3
- `).filter(Boolean),_=L.slice(0,5).join(`
4
- `),A=L.length>5?`
5
- ...and ${L.length-5} more`:"";throw new H("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
1
+ import{execFile as Z2}from"node:child_process";import{basename as C4,resolve as X2}from"node:path";import{promisify as Q2}from"node:util";import{processWorkspaceInfo as E4}from"@cerebriline/shared";import t0 from"simple-git";var j2=Q2(Z2);function V2($,J){return j2("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 t($){if(!$||typeof $!=="object"||!("stderr"in $))return"";return typeof $.stderr==="string"?$.stderr.trim():""}function r($){if(!$||typeof $!=="object"||!("code"in $))return;return typeof $.code==="number"?$.code:void 0}function r0($){let J=s0($.cwd),Z=$.git??V2,X=async(j)=>(await Z(j,{cwd:J,signal:$.signal})).stdout,Q=async(j)=>(await X(j)).trim();return{async isInsideWorkTree(){try{return await Q(["rev-parse","--is-inside-work-tree"])==="true"}catch(j){if(r(j)===128&&/not a git repository|Kein Git-Repository/i.test(t(j)))return!1;throw j}},remotes:()=>t0({baseDir:J}).getRemotes(!0),displayBranch:async()=>(await t0({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:(j)=>Q(["config","--get",`branch.${j}.remote`]),branchMergeRef:(j)=>Q(["config","--get",`branch.${j}.merge`]),remoteUrl:(j)=>Q(["remote","get-url",j]),remoteRefs:(j,V)=>Q(["ls-remote","--exit-code",j,V])}}function s0($){return X2($)}class C extends Error{code;constructor($,J,Z){super(J,Z);this.code=$;this.name="CloudHandoffGitPreflightError"}}function n0($){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 o0($){let J=$.trim();if(!J)return null;let Z=J.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(Z?.[1]){let X=n0(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=n0(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=t(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,j]=X.trim().split(/\s+/,2);if(j===Z&&/^[0-9a-f]{40,64}$/i.test(Q??""))return Q??null}return null}function W2($){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 b4($){let J=r0($);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=W2(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 K=Q.split(`
3
+ `).filter(Boolean),_=K.slice(0,5).join(`
4
+ `),O=K.length>5?`
5
+ ...and ${K.length-5} more`:"";throw new C("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
6
6
 
7
- ${_}${A}`)}let j;try{j=await J.symbolicBranch()}catch(L){let _=r(L)===1,A=t(L),B=_?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new H(_?"detached_head":"git_command_failed",A?`${B} (${A})`:B,{cause:L})}if(!j)throw new H("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[V,Y,W]=await Promise.all([y(()=>J.branchRemote(j),"missing_upstream",`Branch ${j} has no upstream. Push it with -u before handing off.`),y(()=>J.branchMergeRef(j),"missing_upstream",`Branch ${j} has no upstream. Push it with -u before handing off.`),y(J.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!V||V==="."||!Y.startsWith("refs/heads/"))throw new H("missing_upstream",`Branch ${j} has no remote branch upstream. Push it with -u before handing off.`);let F=Y.slice(11),G=V;if(!n0(V))try{G=await J.remoteUrl(V)}catch{throw new H("missing_upstream","Could not resolve the upstream remote.")}let N=n0(G);if(!N)throw new H("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let z;try{z=await J.remoteRefs(V,Y)}catch(L){let _=r(L)===2,A=_?`The upstream branch ${F} 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 H(_?"remote_branch_missing":"git_command_failed",A)}let K=V2(z,F);if(!K)throw new H("remote_branch_missing",`The upstream branch ${F} was not found. Push it before handing off.`);if(K.toLowerCase()!==W.toLowerCase())throw new H("unpushed_commits",`Local HEAD does not match the upstream branch ${F}. Push the current commit before handing off.`);return{repoUrl:N,branch:F,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 j=T($.organizationId),V=W2($.workspaceRelativePath),Y=$.mode;return{repoUrl:J,branch:Z,headSha:X,modelId:Q,...j?{organizationId:j}:{},...V?{workspaceRelativePath:V}:{},...Y?{mode:Y}:{}}}function k4($,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 y4($){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 j=T(J.innerSessionId),V=T(J.dashboardUrl),Y=F2(J.fingerprint);return{toCloudSessionId:Z,handedOffAt:X,status:Q,...j?{innerSessionId:j}:{},...V?{dashboardUrl:V}:{},...Y?{fingerprint:Y}:{}}}function g4($,J){return{...$??{},handoff:J}}function h4($){let{handoff:J,cloudHandoffIntent:Z,cloudHandoffSeedDispatched:X,...Q}=$??{};return Q}function v4($,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"@cerebriline/shared";var G2=610000,z2=3000,m=15000,_2="CLOUD_SESSION_ERROR:",J1="__cline_create_request__:";function Z1($){return($.trim().split(`
8
- `)[0]??"").trim().slice(0,72)}class q 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 A0($){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 A2($,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=A2(J,`Cloud session request failed (${$})`);if($===401)return new q("authentication_required",Q);if($===404)return new q("session_not_found",Q);if($===410)return new q("session_expired",Q);if($===412)return new q("github_not_connected",Q,X??`${q0(Z)}/dashboard/integrations`);if($===403&&Q.trim().toLowerCase()==="forbidden")return new q("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 q("request_failed",Q,void 0,$)}class O2{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 j=!1,V;while(!0){let Y;try{Y=typeof X==="string"?X:await this.options.getAuthToken()}catch(G){if(V)throw _0(401,void 0,this.appBaseUrl,Z);throw G}if(!Y?.trim())throw new q("authentication_required","Sign in to Cline before starting a cloud session.");if(Y.trim()===V)throw new q("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 q("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(m),headers:{Accept:"application/json",Authorization:`Bearer ${Y.trim()}`,...J.body?{"Content-Type":"application/json"}:{},...J.headers}}),F=W.status===204?void 0:await W.json().catch(()=>{return});if(!W.ok){if(W.status===401&&typeof X==="object"&&!j&&X.subject){j=!0,V=Y.trim();continue}throw _0(W.status,F,this.appBaseUrl,Z)}return F?.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((j)=>{if(!j||typeof j!=="object"||typeof j.id!=="string")return[];return[{...j,title:!Z&&e0(j.title)?void 0:j.title,repoContext:j.repoContext&&typeof j.repoContext==="object"?j.repoContext:{},metadata:{...j.metadata&&typeof j.metadata==="object"?j.metadata:{},...!Z&&e0(j.title)?{createRequestTitle:j.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((j)=>{let V=Number(j.id),Y=String(j.html_url??j.clone_url??"").trim();if(!Number.isSafeInteger(V)||V<=0||!Y)return[];let W=String(j.name??"").trim();return[{id:V,name:W,fullName:String(j.full_name??(W||Y)).trim(),url:Y,defaultBranch:String(j.default_branch??"").trim()}]})}}catch(Q){if(Q instanceof q&&Q.code==="session_not_found")return{connected:!1,connectUrl:Z,repositories:[]};throw Q}}async listBranches($,J,Z={}){if(!Number.isSafeInteger($)||$<=0)throw new q("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`,j=new URLSearchParams,V=Z.query?.trim(),Y=Z.cursor?.trim();if(V)j.set("query",V);if(Y)j.set("cursor",Y);let W=j.size>0?`${Q}?${j}`:Q;try{let F=await this.request(W),G=Array.isArray(F)?F:Array.isArray(F?.items)?F.items:[],N=V?.toLowerCase();return{available:!0,branches:G.flatMap((z)=>{let K=String(z.name??"").trim();return K&&(!Array.isArray(F)||!N||K.toLowerCase().includes(N))?[K]:[]}),nextToken:Array.isArray(F)?"":String(F?.nextToken??"").trim()}}catch(F){if(F instanceof q&&F.code==="session_not_found")return{available:!1,branches:[]};throw F}}async status($,J={}){return await this.request(`/api/v1/session/${encodeURIComponent($)}/status`,{signal:J.signal?AbortSignal.any([J.signal,AbortSignal.timeout(m)]):void 0},void 0,J.authToken)}async create($){if($.handoff&&typeof $.handoff.onCreating!=="function")throw new q("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 q("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 q("request_failed","A stable request id is required for cloud handoff creation.");let j=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())),V=async(N)=>{if(N.status==="failed"||N.expiredAt&&Date.parse(N.expiredAt)<=Date.now()){let K=new q(N.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(N.id,Z)}catch(L){if(!(L instanceof q&&(L.code==="session_not_found"||L.code==="session_expired")))throw AggregateError([K,L],"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),K}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 j();if(N.length>1)throw new q("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(N[0])return await V(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(K){if(K instanceof q&&(K.code==="session_not_found"||K.code==="session_expired"))await $.handoff?.onOuterSessionRemoved?.(z.sessionId),this.completedHandoffCreates.delete(Q),this.unconfirmedHandoffCreates.delete(Q);throw K}return await $.handoff?.onOuterSessionCreated(z.sessionId,{created:!1}),{...z,cleanupAuthToken:Z.token}}if(this.unconfirmedHandoffCreates.has(Q))throw new q("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),F,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 q("request_failed","The cloud session service returned no session id.");F=z,await this.persistHandoffOuterSession($,z,Z,Q);let K={sessionId:z,status:N.status?.trim()||"provisioning",sandboxUrl:N.sandboxUrl?.trim()??"",cleanupAuthToken:Z.token};if(Q)this.unconfirmedHandoffCreates.delete(Q),this.completedHandoffCreates.set(Q,K);return K}catch(N){if(F)throw N;let z=!G||N instanceof q&&(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 q)||N instanceof q&&N.code==="request_failed"&&(N.status===void 0||N.status>=500||N.status===408||N.status===409)){let L=[];try{L=await j()}catch(A){if($.handoff)throw AggregateError([N,A],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(L.length>1)throw new q("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let _=L[0];if(_){if($.handoff)return await V(_);return{sessionId:_.id,status:_.status,sandboxUrl:_.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(j){if(!(j instanceof q&&(j.code==="session_not_found"||j.code==="session_expired")))throw AggregateError([Q,j],`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 j;try{j=await this.request(`/api/v1/session/${encodeURIComponent($)}/status`,{signal:AbortSignal.any([J,AbortSignal.timeout(m)])},void 0,Q)}catch(Y){if(J.aborted)throw Y;if(Y instanceof q&&Y.code!=="request_failed")throw Y;await $1(J);continue}let V=j?.status?.trim().toLowerCase();if(Z?.({phase:A0(j?.phase)}),V==="ready"||V==="active")return;if(V==="failed")throw new q("session_failed",j?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(V!=="provisioning")throw new q("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(m)]):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 q)||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 q("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(m)});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 q("request_failed","Invalid archived session history");return X.messages}}import{randomUUID as G4}from"node:crypto";import{posix as N0}from"node:path";import{createSessionId as h6,ensureLoopbackProxyBypass as h1,isHubProtocolCompatible as v6,resolveClineBuildEnv as S6,resolveHubCommandTimeoutMs as m6}from"@cerebriline/shared";import I6 from"ws";var g={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",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:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var Q1="session_not_found";class s extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function O0($){return $ instanceof s||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}import{spawn as J6}from"node:child_process";import{closeSync as Z6,mkdirSync as X6,openSync as Q6,readFileSync as j6,unlinkSync as V6}from"node:fs";import{basename as Y6,dirname as W6,join as N6}from"node:path";import{fileURLToPath as F6}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as K6,isBunEmbeddedModulePath as L6,isHubDaemonProcess as G6,resolveClineBuildEnv as E1,withResolvedClineBuildEnv as z6}from"@cerebriline/shared";import{createHash as D2,randomBytes as U2}from"node:crypto";import{mkdir as D0,open as j1,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 H2}from"@cerebriline/shared";import{resolveClineDataDir as I,resolveClineDir as J8}from"@cerebriline/shared/storage";var C2="CLINE_HUB_DISCOVERY_PATH",x2="CLINE_HUB_BUILD_ID",E2="CLINE_HUB_BUILD_EPOCH_MS",T2=30000,w2=15000,V1=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 Y1($){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 h(){let $=process.env[x2]?.trim();if($)return $;return"sdk-v1-eaa21cb169ac821d9a60e7382c178ff666d1e71f1d99d93bb7a92a0b758ae6d0".trim()||`source-${String(g.version)}`}function h2(){let $=Number(process.env[E2]);if(Number.isFinite($)&&$>0)return $;return Number.isFinite(1791721996794)?1791721996794:void 0}function n($,J=h()){let Z=H2($);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),j=W1(J.buildEpochMs);if(Q!==void 0&&j!==void 0&&Q!==j)return Q<j?-1:1;let V=N1($.coreVersion),Y=N1(J.coreVersion);if(V&&Y){let W=v2(V,Y);if(W!==0)return W}if(Z&&X&&Z!==X)return Z<X?-1:1;return 0}function G1(){return{buildId:h(),buildEpochMs:h2(),coreVersion:String(g.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[C2]?.trim()||M0(I(),"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,Z){await A1($,async()=>{let X=K1($);await D0(X,{recursive:!0});let Q=`${$}.${process.pid}.${U2(6).toString("hex")}.tmp`,j;try{j=await j1(Q,"wx",384),await j.writeFile(`${JSON.stringify(J,null,2)}
9
- `,{encoding:"utf8"}),await j.sync(),await j.close(),j=void 0,Z?.beforePublish?.(),await M2(Q,$);let V;try{V=await j1(X,"r"),await V.sync()}catch{}finally{await V?.close().catch(()=>{return})}}catch(V){throw await j?.close().catch(()=>{return}),await U0(Q,{force:!0}).catch(()=>{return}),V}})}async function v($){await A1($,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(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let Y=await g2(X);if(!Y){if(Date.now()>=Q){await B0(X);continue}await Y1(V1);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 Y1(V1);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 A1($,J){return q1(`${$}.mutation`,"discovery mutation",J)}function O1($,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"@cerebriline/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",$6="hub-production";function p($=o2){return z1(`${$}@${h()}`)}function $0(){return{ownerId:$6,discoveryPath:process.env[e2]?.trim()||n2(I(),"locks","hub","production.json")}}var R1=15000,_6=200,P1=3000,q6=100,A6=[100,250,500,1000,2000],O6="--cline-hub-daemon",B6=3,D6=60000,H1=new Map;function U6($,J=Date.now()){let Z=H1.get($);if(!Z||J-Z.windowStartedAt>D6)return H1.set($,{count:1,windowStartedAt:J}),!0;return Z.count+=1,Z.count<=B6}function M6($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function R6(){try{let $=N6(I(),"logs","hub-daemon.log");return X6(W6($),{recursive:!0}),{fd:Q6($,"a"),logPath:$}}catch{return}}function P6(){return E1()==="production"?$0():p()}function l($){return o($)}function H6($){try{let J=JSON.parse(j6(`${$}.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{V6(`${$}.superseded`)}catch{}}function C1($,J,Z){if(!J||J.url!==Z)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function u($,J){try{return await e($,{authToken:J})}catch{return}}async function x1($,J){let Z=Date.now()+J;while(Date.now()<Z){if(!(await u($))?.url)return!0;await new Promise((Q)=>setTimeout(Q,q6))}return!1}async function H0($,J){if(!U6($.url))return!1;await c($.url,$.authToken,"retired by newer install").catch(()=>!1),await w1($.url,$.authToken).catch(()=>!1);let Z=await x1($.url,P1);if(!Z&&$.pid&&C6($.pid)){try{process.kill($.pid,"SIGTERM")}catch{}Z=await x1($.url,P1)}if(Z)await v(J).catch(()=>{return});return Z}function C6($){try{return process.kill($,0),!0}catch(J){return J?.code==="EPERM"}}async function x6($){try{return(await C0($.url,$.authToken)).activeSessionCount>0}catch{return!1}}async function P0($,J){if(l($))return"reusable";let Z=await c($.url,$.authToken,"retired by newer install").catch(()=>!1);if(await x6($)){if(Z)await c($.url,$.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let X=await H0($,J);if(!X&&Z)await c($.url,$.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return X?"retired":"failed"}async function E6($){if(E1()!=="production")return;let J=p();if(J.discoveryPath===$.discoveryPath)return;let Z=await b(J.discoveryPath);if(Z?.url)await H0(Z,J.discoveryPath);else await v(J.discoveryPath).catch(()=>{return})}function T6(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return F6(new URL(`./entry.${$}`,import.meta.url))}function w6($,J){if(L6($))return[O6];return[...J&&$.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],$]}function f6($,J){let Z=T6(),X=process.execPath?.trim();if(!X)throw Error("unable to resolve runtime executable for hub daemon");let Q=Y6(X).toLowerCase().includes("bun"),j=w6(Z,Q);return{launcher:X,args:[...j,"--cwd",$,...M6(J),...J.manageConnectors===!1?["--no-connectors"]:[]],cwd:$,env:{...z6(process.env),CLINE_NO_INTERACTIVE:"1",[K6]:"1"}}}function b6($){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 k6($,J={}){if(G6())return;let Z=f6($,J),X=R6();try{J6(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)Z6(X.fd)}}async function y6($,J={}){for(let Z=0;;Z++)try{k6($,J);return}catch(X){let Q=A6[Z];if(!b6(X)||Q===void 0)throw X;await new Promise((j)=>setTimeout(j,Q))}}async function g6($,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),j=B1(Q.host,Q.port,Q.pathname),V=(L)=>{if(!X)J0(L.url,L.authToken);return L};await E6($).catch(()=>{return});let Y=await b($.discoveryPath),W=Y?.url?void 0:H6($.discoveryPath),F=!1;if(Y?.url){let L=Y.authToken;if(!L)F=!0,await H0(Y,$.discoveryPath);else{let _=await u(Y.url,L);if(_?.url&&l(_)&&await w(_.url,{authToken:L}))return R0($.discoveryPath),V({url:_.url,authToken:L});if(_?.url){if(await P0({..._,authToken:L},$.discoveryPath)==="deferred_busy"&&await w(_.url,{authToken:L}))return V({url:_.url,authToken:L})}else await v($.discoveryPath).catch(()=>{return})}}let G=await u(j);if(G?.url){let L=C1(G,Y??W,j);if(l(G)){let A=[G.authToken,Y?.authToken,W?.authToken].filter((D)=>typeof D==="string"&&D.trim().length>0);for(let D of A){if(!await w(G.url,{authToken:D}))continue;let C={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,C)}catch{}return R0($.discoveryPath),V({url:G.url,authToken:D})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${F?" 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 _=await P0(L,$.discoveryPath);if(_==="deferred_busy"){for(let A of[L.authToken,Y?.authToken].filter((B)=>typeof B==="string"&&B.trim().length>0))if(await w(G.url,{authToken:A}))return V({url:G.url,authToken:A});if(Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(_==="failed"&&Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let z=Z.allowPortFallback===!0&&Q.port!==0?{...Q,port:0}:Q;await y6(J,{...z,manageConnectors:Z.manageConnectors});let K=Date.now()+R1;while(Date.now()<K){let L=await b($.discoveryPath);if(L?.url&&L.authToken){let A=await u(L.url,L.authToken);if(A?.url&&l(A)&&await w(A.url,{authToken:L.authToken}))return R0($.discoveryPath),V({url:A.url,authToken:L.authToken})}let _=await u(j);if(_?.url&&!l(_)){let A=C1(_,L??W,j),B=await P0(A,$.discoveryPath);if(B==="deferred_busy"&&L?.authToken&&await w(_.url,{authToken:L.authToken}))return V({url:_.url,authToken:L.authToken});if(B==="failed"&&Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((A)=>setTimeout(A,_6))}throw Error(`Timed out after ${R1}ms waiting for detached hub startup.`)}async function T1($,J={}){let Z=P6();return await O1(Z.discoveryPath,async()=>g6(Z,$,J))}function p6(){return S6()==="production"?$0():p()}function l6(){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 u6($){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=u6(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,c6="cline-hub-auth.",S1=new Map,m1=new Set,a6=3000;var E0="Hub connection closed",d6=250,i6=5000,k1=0.5;class R extends Error{code;details;constructor($,J,Z){super(J);this.code=$;this.details=Z;this.name="HubTransportError"}}function t6($){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 r6($){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(!r6($))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 a{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(V)=>{if(Q=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(g.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let Y of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Y));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(Q&&this.socket===Q){this.lastCloseError=b1(V,$),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{Q.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw V}}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((F,G)=>{W=setTimeout(()=>{G(new R("hub_connect_timeout",`Timed out resolving hub connection headers after ${Z0}ms`))},Z0)})])}catch(F){let G=F instanceof R?F:new R("hub_connect_failed",F instanceof Error?F.message:String(F));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 j=Q?new I6($.toString(),{headers:{...Q}}):new(l6())($.toString(),J?[`${c6}${J}`]:void 0);this.socket=j;let V=!1,Y=new Promise((W,F)=>{let G=!1,N=setTimeout(()=>{if(G)return;G=!0,V=!0;let z=new R("hub_connect_timeout",`Timed out connecting to hub after ${Z0}ms`);if(this.socket===j)this.lastCloseError=z,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}F(z)},Z0);j.addEventListener("open",()=>{if(G)return;G=!0,clearTimeout(N),W()}),j.addEventListener("error",(z)=>{if(G)return;G=!0,clearTimeout(N);let K=b1(z,$);if(this.socket===j)this.lastCloseError=K,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;F(K)}),j.addEventListener("close",(z)=>{if(G)return;G=!0,clearTimeout(N);let K=V?this.lastCloseError:f1(z);if(this.socket===j){if(!V)this.lastCloseError=K,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}F(K)})});return j.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(v1(W)))}),j.addEventListener("close",(W)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=f1(W),this.sawSocketClose=!0;this.registered=!1;for(let F of this.pendingReplies.values())F.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await Y,j}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,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Z,X)}catch(V){if(!j||Q>=1||!await this.recoverLocalHubTransport(V))throw V;Q+=1}}async commandOnce($,J,Z,X,Q=!0){if(Q)await this.connect();X?.beforeDispatch?.();let j=h6("hubreq_");X?.onDispatch?.(j);let V=m6($,X?.timeoutMs),Y=new Promise((F,G)=>{let N=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;G(new T0($,"hub_command_timeout",`Hub command ${$} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(z)=>{if(N)clearTimeout(N);F(z)},reject:(z)=>{if(N)clearTimeout(N);G(z)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:J}})}catch(F){throw this.pendingReplies.delete(j),F}let W=await Y;if(!W.ok){if(W.error?.code===Q1){let F=Z??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new s(F,W.error.message)}throw new T0($,W.error?.code,W.error?.message??`Hub command ${$} failed`)}return W}async recoverLocalHubTransport($){if(!y1(this.currentUrl)||!t6($))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(d6*2**this.reconnectAttempt,i6),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 a({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=h(),j=n(X,Q);if(!j.compatible&&!o(X))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!v6(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 s6($){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 j=Q.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let Y=V&&typeof V==="object"?V.clientId:void 0;if(typeof Y==="string"&&Y.trim())X.add(Y)}}return{activeSessionCount:Z,participantClientCount:X.size}}async function C0($,J,Z){let X=new a({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:a6});return s6(Q.payload)}finally{await X.dispose().catch(()=>{return})}}async function n6($,J,Z){try{return(await C0($,J,Z)).activeSessionCount===0}catch{return!1}}async function o6($,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 n6(Q.url,X.authToken,J))return;return J0(Q.url,X.authToken)}async function e6($={}){if($.endpoint?.trim()){let Q=await w0($.endpoint);return Q.status==="compatible"?Q.url:void 0}let J=p6(),Z=await b(J.discoveryPath);if(!Z?.url)return await o6(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 v(J.discoveryPath).catch(()=>{return});return}async function g1($={}){let J=await e6($);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 c($,J,Z,X){h1();let Q=new URL($),j=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:j?{authorization:`Bearer ${j}`}: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 $4($,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():"",j=typeof Z.name==="string"?Z.name.trim():"";return{id:X,name:Q||j||X,catalogId:J}}function k0($,J){return Array.isArray($)?$.flatMap((Z)=>{let X=$4(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),j=async(_)=>{let A=await(J.fetchImpl??fetch)(`${Q}${_}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!A.ok)throw Error(`HTTP ${A.status}`);return await A.json()},V,Y;try{[V,Y]=await Promise.all([j("/api/v1/ai/cline/models"),j("/api/v1/ai/cline/recommended-models")])}catch(_){throw Error("Could not load the cloud model catalog.",{cause:_})}let W=V&&typeof V==="object"?V:void 0,F=k0(Array.isArray(V)?V: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"),K=k0(N?.clineCloud,"cline-cloud"),L=new Set;return[...J.isOrganizationSession?[]:z,...K,...F].filter((_)=>{if(L.has(_.id))return!1;return L.add(_.id),!0})}import{formatDisplayUserInput as l1}from"@cerebriline/shared";var J4=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function Z4($){switch($){case"user":case"assistant":case"tool":case"system":case"status":case"error":return $;default:return"assistant"}}function X4($){return $.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}function Q4($){let J=$?.userRunSpan;return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:void 0}function j4($){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 j=Q;if(j.type==="text"&&typeof j.text==="string")X.push(j.text);else if(j.type==="tool_result"||j.type==="tool-result")Z=!0;else if(j.type==="file"||j.type==="image")J=!0}return{hasAttachment:J&&!Z,text:X.join(`
11
- `)}}function V4($){let J=l1($);return J.startsWith("[TASK RESUMPTION]")||J==="The user approved switching to act mode. Continue with the approved plan now."}function Y4($){if(Z4($.role)!=="user")return 0;let J=X4($),Z=typeof J?.kind==="string"?J.kind:void 0,X=Q4(J);if(Z==="compaction"||Z==="compaction_summary")return X??1;if(X!==void 0)return X;if(Z&&J4.has(Z))return 0;let Q=j4($);if(!Q.hasAttachment&&!l1(Q.text))return 0;if(!Q.hasAttachment&&V4(Q.text))return 0;return 1}function u1($){return Y4($)>0}function j0($){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 V0($){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 d($,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 W4=new Set(["run.completed","run.aborted","run.failed"]),N4=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 j=X.get(Q)??0;if(j===0)return!0;if(j===1)X.delete(Q);else X.set(Q,j-1);return!1})}function Q0($,J,Z=new Set){if(!$||typeof $!=="object")return Z;if(Array.isArray($)){for(let j of $)Q0(j,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 j of Object.values(X))Q0(j,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 j=Q.payload?.[J==="assistant"?"text":"reasoning"],V=typeof j==="string"&&j?j:X;if(V)Z=V;X=""}return(Z||X).trim()}function t1($,J,Z={}){let X=Z.queueSnapshotApplied!==!1,Q=a1(J,Z.baselineMessages??[]),j=a1(J,Z.baselineMessages??[],"thinking"),V=Q0(J,"tool_use"),Y=Q0(J,"tool_result"),W=new Set($.slice(0,Z.messagesSnapshotEventCutoff??$.length)),F=new Set,G=new Map;for(let A of $.slice(0,Z.messagesSnapshotEventCutoff??$.length)){let B=h0([A])[0];if(!B)continue;let D=X0(B.prompt),C=G.get(D)??Math.max(0,d(J,[],D)-d(Z.baselineMessages??[],[],D));if(G.set(D,Math.max(0,C-1)),C>0)F.add(A)}let z=[...X?$.slice(Z.queueSnapshotEventCutoff??$.length):$].reverse().find((A)=>A.event==="session.pending_prompts"),K=[],L=[],_=(A)=>{if(L.length===0)return;let B=L.filter((x)=>W.has(x)),D=(x)=>{if(!A)return-1;let M=[...B].reverse().findIndex(($2)=>$2.event===`${x}.finished`),S=M<0?-1:B.length-1-M;return S>=0||L.at(-1)?.event==="run.aborted"?S:B.length-1},C=D("assistant"),f=D("reasoning"),O=d1(B.slice(0,C+1)),P=O?Q.findIndex((x)=>x.endsWith(O)):-1,k=P>=0;if(k)Q.splice(P,1);let i=d1(B.slice(0,f+1),"reasoning"),F0=i?j.findIndex((x)=>x.endsWith(i)):-1;if(F0>=0)j.splice(F0,1);for(let[x,M]of L.entries()){if(F.has(M)){K.push({...M,payload:{...M.payload,transcriptReflected:!0}});continue}if(W.has(M)&&N4.has(M.event)&&(M.event.startsWith("reasoning.")?F0>=0&&x<=f:k&&x<=C))continue;if(M.event==="session.pending_prompts"&&M!==z)continue;if(W.has(M)&&M.event.startsWith("tool.")){let S=String(M.payload?.toolCallId??"").trim();if(Y.has(S)||M.event==="tool.started"&&V.has(S))continue}K.push(M)}L=[]};for(let A of $)if(L.push(A),W4.has(A.event))_(!0);return _(!1),K}import{formatDisplayUserInput as F4}from"@cerebriline/shared";function Y0($){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?F4(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:"",j=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(j.trim())J.push(j)}return J.join(`
13
- `)}if($&&typeof $==="object"){let J=$;if(typeof J.text==="string")return J.text}return""}function K4($){let J=W0($??void 0);if(!J)return;return J.split(`
14
- `)[0]?.trim().slice(0,70)||void 0}function L4($){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=K4($.prompt);if(Z)return Z;let X=$.messages?L4($.messages):void 0;if(X)return X;return`Session ${$.sessionId.slice(-6)}`}function r1($,J,Z,X){let Q=J.payload??{},j=()=>{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},V=(Y,W,F)=>{let G=j(),N=G.at(-1);if(N?.type===Y)N[W]=`${N[W]??""}${F}`;else G.push({type:Y,[W]:F})};switch(J.event){case"assistant.delta":if(typeof Q.text==="string")V("text","text",Q.text);return;case"reasoning.delta":if(typeof Q.text==="string"&&Q.text)V("thinking","thinking",Q.text);else if(Q.redacted===!0)j().push({type:"redacted_thinking",data:""});return;case"assistant.finished":Z.delete(X);return;case"assistant.media":if(Q.media)j().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((F)=>F.type==="tool_use"&&F.id===Y)))j().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((F)=>F.type==="tool_result"&&F.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((F)=>typeof F==="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((F)=>F.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,F=W==="pending"?"running":W;if(J.event==="session.updated"&&F==="running"&&$.endedAt!==void 0&&!$.busy)return;let G=$.busy;if($.status=F,$.busy=F==="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",z4=30000,_4=2000,q4=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 q("request_failed","The handoff workspace path must stay inside the repository.");let J=N0.join(U,$);if(!J.startsWith(`${U}/`))throw new q("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 q{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 A4($){return $.trim().startsWith("ses-")}function O4($,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 B4($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function D4($,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 U4{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 a(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 Y0({...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($):Y0($);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 q("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 A4($)||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 q&&(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 $=(V)=>this.sessions.get(V)?.title??this.knownSessions.get(V)?.title,J=new Map([...this.knownSessions.keys(),...this.sessions.keys()].map((V)=>[V,$(V)])),Z=(V)=>{let Y=$(V.id);if(this.titleWrites.has(V.id)||Y!==J.get(V.id))V.title=Y??V.title},X=await this.resolveActiveOrganizationId(),Q=(await this.options.api.list(X)).map((V)=>this.preserveConnectedRuntimeModel(V));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=Q;for(let V of Q)Z(V),this.knownSessions.set(V.id,V),this.unlistedSessions.delete(V.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(V)=>this.getCrossScopeDiscoveryRecord(V)));let j=await Promise.all(Q.map(async(V)=>{if(V.status!=="provisioning")return V;let Y=await this.options.api.status(V.id).catch(()=>{return}),W=Y?.status?.trim();if(!W)return V;return{...V,status:W,metadata:{...V.metadata,...A0(Y?.phase)?{provisioningPhase:Y?.phase}:{},...Y?.statusReason?.trim()?{statusReason:Y.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let V of j){Z(V),this.knownSessions.set(V.id,V);let Y=this.sessions.get(V.id);if(Y)Y.title=V.title;if(Y?.status==="provisioning"&&V.status!=="provisioning")Y.status=V.status;let W=this.connections.get(V.id);if(W)W.remote=V;let F=E(V);if(F||V.status==="failed"||V.status==="suspended"){if(Y)Y.busy=!1,Y.status=F?"expired":V.status,Y.endedAt=F?Date.parse(V.expiredAt??"")||Date.now():Math.max(Y.endedAt??0,Date.parse(V.lastActivityAt??V.createdAt)||0)||void 0;if(W)this.disposeConnection(V.id).catch(()=>{return})}}this.lastListedSessions=j;for(let V of j)if(this.sessions.has(V.id))this.publishSnapshot(V.id);return Y0(j)}async handoffTargetExists($){try{return await this.options.api.status($),!0}catch(J){if(J instanceof q&&(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 q("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 q("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 j,V=await Promise.race([J.then((Y)=>({value:Y}),(Y)=>{if(!(Y instanceof q&&Y.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:Y});return{value:this.lastListedSessions}}),new Promise((Y)=>{j=setTimeout(()=>Y({value:this.lastListedSessions}),Math.max(0,$.timeoutMs??0))})]);if(j)clearTimeout(j);Z=V.value}return[...new Map([...this.unlistedSessions.values(),...Z].map((j)=>[j.id,j])).values()].map((j)=>{let V=o1(j),Y=this.sessions.get(j.id);if(!Y)return V;let W=Y.title?.trim()||j.title?.trim();return{...V,status:Y.status,prompt:Y.prompt,endedAt:Y.endedAt!==void 0?new Date(Y.endedAt).toISOString():V.endedAt,metadata:{...V.metadata??{},title:S0({sessionId:j.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 j=await X.client.command("session.messages",{sessionId:Q},Q);this.assertSessionActive($,X);let V=j.payload?.messages;if(!Array.isArray(V))throw Error("Cloud runtime returned no transcript after seeding.");if(J.length>0&&V.length===0)throw new e1;if(!(Z.allowAppendedMessages?V.length>=J.length&&L0(J,V.slice(0,J.length)):L0(J,V)))throw new G0(J.length,V.length);X.transcriptKnown=!0;let W=this.sessions.get($);if(W)W.messages=structuredClone(V),this.authoritativeMessages.set($,structuredClone(V)),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,j=await this.options.api.create({...$,organizationId:Z,...X&&{handoff:{...X,onOuterSessionCreated:async(z,K)=>{Q=K?.created===!0,await X.onOuterSessionCreated(z,K)}}}});if(!j?.sessionId?.trim())throw new q("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(j.sessionId,j.cleanupAuthToken,$.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let V={id:j.sessionId,sandboxType:$.sandboxType,status:j.status,sandboxUrl:j.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(V.id,V),this.unlistedSessions.set(V.id,V);let{autoApproveTools:Y,thinking:W,reasoningEffort:F}=$;this.pendingInitialTasks.set(V.id,{autoApproveTools:Y,thinking:W,reasoningEffort:F});let G=this.stateFromRecord(V);G.prompt=$.initialPrompt?.trim()||void 0,G.config.mode=$.mode??"act",this.sessions.set(V.id,G);let N;try{if($.handoff){let z=await $.handoff.resolveMessages();this.assertSessionActive(V.id),N=(await this.seedHandoff(V.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(V.id,j.cleanupAuthToken,$.handoff?.onOuterSessionRemoved);throw z}return this.assertSessionActive(V.id),this.notify("chat_session_status",{sessionId:V.id,status:G.status}),{sessionId:V.id,origin:"cloud",executionTarget:"cloud",status:V.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 j=Q.remote,V=this.sessions.get($);return u0(j,V?.status??j.status,V?.prompt)}async send($,J,Z,X,Q){let j=this.sendAbortTokens.get($),V=this.knownSessions.get($);if(V&&E(V))throw new q("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($)!==j,F=()=>{if(W())throw Error("Cloud session prompt cancelled")};if(F(),await Y.reconnectResolution,F(),await this.ensureAttached(Y),await Y.reconnectResolution,F(),!Y.transcriptKnown)await this.rehydrateAfterTransportDrop($,Y);F(),await this.updateModel(Y,X),await Y.reconnectResolution,F();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),K=d(N?.messages??[],N?.promptsInQueue??[],J),L=z!=="queue"&&z!=="steer",_=N&&z!=="queue"?{role:"user",content:[{type:"text",text:J}]}:void 0;if(N&&_)N.messages=[...N.messages,_];let A=()=>{if(N&&_)N.messages=N.messages.filter((O)=>O!==_),this.publishSnapshot($)};if(N&&L){let O=N.status!=="running";if(N.busy=!0,N.status="running",N.prompt||=J,O)this.publishSnapshot($,!1,"status")}let B=this.knownSessions.get($);if(B&&!B.title?.trim()&&!this.titleWrites.has($)){let O=Z1(J);if(O){if(B.title=O,N)N.title=O;let P=this.options.api.updateTitle?.($,O).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get($)===P)this.titleWrites.delete($)});if(P)this.titleWrites.set($,P)}}let D=new Set,C=!1,f=()=>{if(C||W())return;C=!0,this.publish({type:"prompt_accepted",sessionId:$,prompt:J,delivery:z})};try{let O=await Y.client.command("session.send_input",{prompt:J,delivery:z,...Q?.length?{attachments:{userImages:Q}}:{}},G,{timeoutMs:z==="queue"?z4:null,onDispatch:(k)=>{D.add(k),Y.pendingInputs??=new Map,Y.pendingInputs.set(k,{clientId:Y.client.getClientId(),ownsBusyState:L,accept:f})},beforeDispatch:()=>{if(F(),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"&&O.payload?.result===void 0;if(P)A();return{sessionId:$,ok:!0,...P?{queued:!0}:{},result:O.payload?.result}}catch(O){if(W())throw A(),O;if(m0(O)||I0(O,"session.send_input")){let P;try{P=await this.rehydrateAfterTransportDrop($,Y)}catch(i){if(F(),A(),N&&L)N.busy=!1,N.status="error";if(z==="queue")throw new a0;throw i}if(F(),z==="queue")throw new a0;if(z==="steer")throw new q("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(d(P.messages,D4(P.prompts,P.submittedPrompts),J)<=K)throw new q("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(A(),N&&L)N.busy=!1,N.status="error";throw this.publishSnapshot($),O}finally{for(let O of D)Y.pendingInputs?.delete(O)}}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 j=this.sessions.get($),V=this.authoritativeMessages.get($)??[],Y=String(Q?.status??j?.status??"running").trim(),W=Y==="pending"?"running":Y;if(W==="running"&&!J.transcriptKnown&&!J.pendingInputs?.size)J.externalRun??={progressHydrated:!0};let F=()=>J.client.command("session.messages",{sessionId:Z},Z),G=await F().catch((O)=>{if(!I0(O,"session.messages"))throw O;return this.assertSessionActive($,J),F()});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,K=await J.client.command("session.pending_prompts",{sessionId:Z},Z).catch(()=>{return});this.assertSessionActive($,J);let L=J.bufferedEventsDropped+J.bufferedEvents.length;if(j){let O=j.status!==W;if(this.authoritativeMessages.set($,structuredClone(N)),j.messages=structuredClone(N),this.streamingMessages.delete($),j.status=W,j.busy=W==="running",O)if(W==="completed"||W==="failed"||W==="aborted")j.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:$,reason:W==="failed"?"error":W});else this.notify("chat_session_status",{sessionId:$,status:W})}let _=K!==void 0&&K.ok!==!1&&Array.isArray(K.payload?.prompts),A=_?this.applyQueueSnapshot($,K):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,C=h0(D),f=t1(D,N,{queueSnapshotApplied:_,queueSnapshotEventCutoff:Math.max(0,L-J.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,z-J.bufferedEventsDropped),baselineMessages:V});J.bufferedEvents=[],J.bufferingEvents=!1,J.syncFailureNotified=!1;for(let O of f)this.forwardEvent($,J,O);return{status:W,messages:N,prompts:A,submittedPrompts:C}}catch(X){let Q=J.bufferedEvents;J.bufferedEvents=[],J.bufferingEvents=!1,this.assertSessionActive($,J);for(let j of Q)this.forwardEvent($,J,j);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 j=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),j}applyQueueSnapshot($,J){if(!Array.isArray(J.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let X=J.payload.prompts.map((j)=>({id:typeof j.id==="string"?j.id:"",prompt:typeof j.prompt==="string"?j.prompt:"",steer:j.delivery==="steer",attachmentCount:typeof j.attachmentCount==="number"?j.attachmentCount:0,userImages:Array.isArray(j.userImages)?j.userImages.filter((V)=>typeof V==="string"):void 0})).filter((j)=>j.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 j=this.sessions.get($);if(j)j.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 q?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 q("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 q("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($),j=Q?await Q:this.connections.get($);if(j?.remote.status==="suspended")return await this.disposeConnection($),X(),await this.ensureConnection($,J);if(j){if(this.assertSessionActive($,j),await j.reconnectResolution,this.assertSessionActive($,j),!j.innerSessionId)await j.client.connect(),await j.reconnectResolution,this.assertSessionActive($,j),await this.resolveInnerSession($,j,Boolean(J.handoffSeed)),this.assertSessionActive($,j);if(J.handoffSeed&&j.innerSessionId)await this.assertHandoffConnectionReusable(j,J.handoffSeed);if(J.createInner&&!j.innerSessionId)await this.createInnerSession(j,J.handoffSeed);return this.assertSessionActive($,j),j}let V=(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(K)=>{if(!(K instanceof q?K.code==="request_failed"&&(K.status===void 0||K.status===408||K.status===429||K.status>=500):K instanceof TypeError||K instanceof Error&&K.name==="TimeoutError"))throw K;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(L){if(!(L instanceof q)||L.status!==409)throw L;X(),N.signal.throwIfAborted();let _=await this.options.api.status($,{signal:N.signal});if(_.status!=="provisioning"&&_.status!=="ready"&&_.status!=="active")throw L;Y={...Y,status:_.status}}X(),N.signal.throwIfAborted(),this.knownSessions.set($,Y);let K=this.sessions.get($);if(K)K.status=Y.status,K.busy=!1,K.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:L})=>{Y.metadata.provisioningPhase=L,this.notify("chat_session_status",{sessionId:$,status:"provisioning",phase:L})}),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 K=this.sessions.get($);if(K?.status==="provisioning")K.status="idle",K.busy=!1,K.endedAt=void 0}catch(K){if(K instanceof q&&K.code==="session_failed"){if(Y.status="failed",Y.metadata.statusReason=K.detail,Y.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set($,Y);let L=this.sessions.get($);if(L)L.status="error";this.notify("chat_session_status",{sessionId:$,status:"error"})}throw K}finally{z()}}if(X(),Y.status==="failed")throw new q("session_failed",Y.metadata.statusReason||"The cloud sandbox could not be prepared.");if(E(Y))throw new q("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,F=0,G=this.createHubClient({url:O4(this.options.apiBaseUrl,$),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${$}-${G4()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:U,cwd:U,resolveConnectionHeaders:async()=>{X();let N=F>0;if(F+=1,W)W.connected=!1,W.reconnecting=N,this.publishSnapshot($);if(N){let K=W;if(K&&!K.disposed){K.transcriptKnown=!1,K.innerSessionId=void 0;let L=(async()=>{if(await this.resolveInnerSession($,K),K.innerSessionId)await this.rehydrateAfterTransportDrop($,K)})().catch(()=>this.disposeConnectionIfSessionGone($,K)).finally(()=>{if(K.reconnectResolution===L)K.reconnectResolution=void 0,K.connected=K.transcriptKnown,this.publishSnapshot($)});K.reconnectResolution=L}}let z=await this.options.getAuthToken();if(!z?.trim())throw new q("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($)===V)this.connectionPromises.delete($)});return this.connectionPromises.set($,V),await V}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(!O0(Y))throw Y}else{let Y=await J.client.command("session.list",{limit:100});this.assertSessionActive($,J),Q=j0(Y.payload).filter(V0).sort((W,F)=>y0(F)-y0(W))[0]}let j=String(Q?.sessionId??"").trim();if(!j||!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,j,Q),this.assertSessionActive($,J);this.pendingInitialTasks.delete($),J.innerSessionId=j,this.subscribeToInnerSession($,J);let V=g0(Q);if(V)this.applyModel(J,V);await this.ensureAttached(J)}async restoreSavedInnerSession($,J,Z){let X=()=>$.client.command("session.update_connection",{sessionId:J,updates:{}},J);try{await X();return}catch(L){if(!(O0(L)||L instanceof Error&&L.code==="command_failed"&&L.message===`session not found: ${J}`))throw L}this.assertSessionActive($.remote.id,$);let Q=await $.client.command("session.messages",{},J);this.assertSessionActive($.remote.id,$);let j=Q.payload?.messages;if(!Array.isArray(j)||j.length===0)throw Error("The saved conversation is empty or unavailable.");let V=Z.metadata??{},Y=Z.runtimeOptions??{},W=this.sessions.get($.remote.id)?.config,F=Object.hasOwn(V,"thinking")?V.thinking:W?.thinking,G=Object.hasOwn(V,"reasoningEffort")?V.reasoningEffort:W?.reasoningEffort,N=typeof V.autoApproveTools==="boolean"?V.autoApproveTools:W?.autoApproveTools,z=Z.cwd??Z.workspaceRoot??U,K=Z.workspaceRoot??U;try{let L=await $.client.command("session.create",{workspaceRoot:K,cwd:z,initialMessages:j,metadata:{...V,interactive:!0},sessionConfig:{sessionId:J,providerId:V.provider??"cline",modelId:V.model??V.modelId??$.remote.metadata.modelId,workspaceRoot:K,cwd:z,systemPrompt:Y.systemPrompt??V.systemPrompt??"",mode:Y.mode??V.mode??"act",...typeof F==="boolean"?{thinking:F}:{},...typeof G==="string"?{reasoningEffort:G}:{},...V.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:Y,...typeof N==="boolean"?{toolPolicies:{"*":{autoApprove:N}}}:{}});if(this.assertSessionActive($.remote.id,$),(L.payload?.session?.sessionId??L.payload?.sessionId)!==J)throw Error("Cloud Hub did not restore the requested session.")}catch(L){if(L?.code!=="session_already_exists")throw L;this.assertSessionActive($.remote.id,$),await X()}}async assertHandoffConnectionReusable($,J){let Z=await $.client.command("session.list",{limit:100});this.assertSessionActive($.remote.id,$);let X=j0(Z.payload).filter(V0),[Q]=X;if(X.length!==1||String(Q?.sessionId??"").trim()!==$.innerSessionId||n1(Q)!==J.sourceSessionId)throw new q("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 q("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=j0(Z.payload).filter(V0);if(X.length===0)return!1;let[Q]=X,j=String(Q?.sessionId??"").trim();if(X.length!==1||!j||n1(Q)!==J.sourceSessionId)throw new q("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return $.innerSessionId=j,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),j=J?.mode??"act";try{await J?.onSeeding?.(),this.assertSessionActive($.remote.id,$)}catch(A){if(J)throw new c0(A);throw A}let V=`cline/${($.remote.metadata.taskId?.trim()||$.remote.id).slice(-8).toLowerCase()}`,Y=$.remote.sandboxType==="resumable"||$.remote.metadata.sandboxType==="resumable",W=`${s1}
7
+ ${_}${O}`)}let j;try{j=await J.symbolicBranch()}catch(K){let _=r(K)===1,O=t(K),B=_?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new C(_?"detached_head":"git_command_failed",O?`${B} (${O})`:B,{cause:K})}if(!j)throw new C("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[V,Y,W]=await Promise.all([y(()=>J.branchRemote(j),"missing_upstream",`Branch ${j} has no upstream. Push it with -u before handing off.`),y(()=>J.branchMergeRef(j),"missing_upstream",`Branch ${j} has no upstream. Push it with -u before handing off.`),y(J.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!V||V==="."||!Y.startsWith("refs/heads/"))throw new C("missing_upstream",`Branch ${j} has no remote branch upstream. Push it with -u before handing off.`);let F=Y.slice(11),G=V;if(!o0(V))try{G=await J.remoteUrl(V)}catch{throw new C("missing_upstream","Could not resolve the upstream remote.")}let N=o0(G);if(!N)throw new C("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let z;try{z=await J.remoteRefs(V,Y)}catch(K){let _=r(K)===2,O=_?`The upstream branch ${F} 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(_?"remote_branch_missing":"git_command_failed",O)}let L=Y2(z,F);if(!L)throw new C("remote_branch_missing",`The upstream branch ${F} 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 ${F}. Push the current commit before handing off.`);return{repoUrl:N,branch:F,headSha:W,...X?{workspaceRelativePath:X}:{}}}function L0($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function T($){if(typeof $!=="string")return;return $.trim()||void 0}function N2($){return typeof $==="string"&&$.length>0?$:void 0}function F2($){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 j=T($.organizationId),V=N2($.workspaceRelativePath),Y=$.mode;return{repoUrl:J,branch:Z,headSha:X,modelId:Q,...j?{organizationId:j}:{},...V?{workspaceRelativePath:V}:{},...Y?{mode:Y}:{}}}function y4($,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 K2($){let J=L0($);if(!J||typeof J.repoUrl!=="string"||typeof J.branch!=="string"||typeof J.headSha!=="string"||typeof J.modelId!=="string")return;try{return F2({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 g4($){let J=L0(L0($)?.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 j=T(J.innerSessionId),V=T(J.dashboardUrl),Y=K2(J.fingerprint);return{toCloudSessionId:Z,handedOffAt:X,status:Q,...j?{innerSessionId:j}:{},...V?{dashboardUrl:V}:{},...Y?{fingerprint:Y}:{}}}function h4($,J){return{...$??{},handoff:J}}function v4($){let{handoff:J,cloudHandoffIntent:Z,cloudHandoffSeedDispatched:X,...Q}=$??{};return Q}function S4($,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 e0($){return $.map((J)=>{let Z=J&&typeof J==="object"?J:{};return{role:Z.role,content:Z.content}})}function G0($,J){return $.length===J.length&&JSON.stringify(e0($))===JSON.stringify(e0(J))}class z0 extends Error{constructor($,J){super(`Cloud transcript verification failed (local ${$} messages, cloud ${J}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as L2}from"node:crypto";import{decodeJwtPayload as G2}from"@cerebriline/shared";var z2=610000,_2=3000,m=15000,q2="CLOUD_SESSION_ERROR:",Z1="__cline_create_request__:";function X1($){return($.trim().split(`
8
+ `)[0]??"").trim().slice(0,72)}class q extends Error{code;detail;connectUrl;status;constructor($,J,Z,X){super(`${q2}${JSON.stringify({code:$,message:J,connectUrl:Z})}`);this.code=$;this.detail=J;this.connectUrl=Z;this.status=X;this.name="CloudSessionError"}}class Q1 extends Error{constructor($){super($ instanceof Error?$.message:"Cloud handoff creation was rejected.",{cause:$});this.name="CloudHandoffCreationRejectedError"}}function O0($){let J=$.length;while(J>0&&$[J-1]==="/")J--;return $.slice(0,J)}function O2($){return`${Z1}${$}`.slice(0,255)}function $1($){return $?.startsWith(Z1)===!0}function A0($){switch($){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return $;default:return}}function _0($){let J=G2($.replace(/^workos:/,""));return typeof J?.sub==="string"&&J.sub.trim()?J.sub.trim():void 0}function J1($){return new Promise((J,Z)=>{if($.aborted){Z($.reason);return}let X=()=>{clearTimeout(Q),Z($.reason)},Q=setTimeout(()=>{$.removeEventListener("abort",X),J()},_2);$.addEventListener("abort",X,{once:!0})})}function A2($,J){if($&&typeof $==="object"){let Z=$.error;if(typeof Z==="string"&&Z.trim())return Z.trim()}return J}function q0($,J,Z,X){let Q=A2(J,`Cloud session request failed (${$})`);if($===401)return new q("authentication_required",Q);if($===404)return new q("session_not_found",Q);if($===410)return new q("session_expired",Q);if($===412)return new q("github_not_connected",Q,X??`${O0(Z)}/dashboard/integrations`);if($===403&&Q.trim().toLowerCase()==="forbidden")return new q("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 q("request_failed",Q,void 0,$)}class B2{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor($){this.options=$;this.apiBaseUrl=O0($.apiBaseUrl),this.appBaseUrl=O0($.appBaseUrl),this.fetchImpl=$.fetch??fetch,this.createTimeoutMs=$.createTimeoutMs??z2}async request($,J={},Z,X,Q){let j=!1,V;while(!0){let Y;try{Y=typeof X==="string"?X:await this.options.getAuthToken()}catch(G){if(V)throw q0(401,void 0,this.appBaseUrl,Z);throw G}if(!Y?.trim())throw new q("authentication_required","Sign in to Cline before starting a cloud session.");if(Y.trim()===V)throw new q("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof X==="object"){if(X.subject?_0(Y.trim())!==X.subject:Y.trim()!==X.token)throw new q("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(m),headers:{Accept:"application/json",Authorization:`Bearer ${Y.trim()}`,...J.body?{"Content-Type":"application/json"}:{},...J.headers}}),F=W.status===204?void 0:await W.json().catch(()=>{return});if(!W.ok){if(W.status===401&&typeof X==="object"&&!j&&X.subject){j=!0,V=Y.trim();continue}throw q0(W.status,F,this.appBaseUrl,Z)}return F?.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((j)=>{if(!j||typeof j!=="object"||typeof j.id!=="string")return[];return[{...j,title:!Z&&$1(j.title)?void 0:j.title,repoContext:j.repoContext&&typeof j.repoContext==="object"?j.repoContext:{},metadata:{...j.metadata&&typeof j.metadata==="object"?j.metadata:{},...!Z&&$1(j.title)?{createRequestTitle:j.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((j)=>{let V=Number(j.id),Y=String(j.html_url??j.clone_url??"").trim();if(!Number.isSafeInteger(V)||V<=0||!Y)return[];let W=String(j.name??"").trim();return[{id:V,name:W,fullName:String(j.full_name??(W||Y)).trim(),url:Y,defaultBranch:String(j.default_branch??"").trim()}]})}}catch(Q){if(Q instanceof q&&Q.code==="session_not_found")return{connected:!1,connectUrl:Z,repositories:[]};throw Q}}async listBranches($,J,Z={}){if(!Number.isSafeInteger($)||$<=0)throw new q("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`,j=new URLSearchParams,V=Z.query?.trim(),Y=Z.cursor?.trim();if(V)j.set("query",V);if(Y)j.set("cursor",Y);let W=j.size>0?`${Q}?${j}`:Q;try{let F=await this.request(W),G=Array.isArray(F)?F:Array.isArray(F?.items)?F.items:[],N=V?.toLowerCase();return{available:!0,branches:G.flatMap((z)=>{let L=String(z.name??"").trim();return L&&(!Array.isArray(F)||!N||L.toLowerCase().includes(N))?[L]:[]}),nextToken:Array.isArray(F)?"":String(F?.nextToken??"").trim()}}catch(F){if(F instanceof q&&F.code==="session_not_found")return{available:!1,branches:[]};throw F}}async status($,J={}){return await this.request(`/api/v1/session/${encodeURIComponent($)}/status`,{signal:J.signal?AbortSignal.any([J.signal,AbortSignal.timeout(m)]):void 0},void 0,J.authToken)}async create($){if($.handoff&&typeof $.handoff.onCreating!=="function")throw new q("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 q("authentication_required","Sign in to Cline before starting a cloud session.");let Z={token:J,subject:_0(J)},X=O2($.requestId?.trim()||L2()),Q=$.handoff?`${Z.subject??J}/${$.organizationId??""}/${$.requestId?.trim()??""}`:void 0;if($.handoff&&!$.requestId?.trim())throw new q("request_failed","A stable request id is required for cloud handoff creation.");let j=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())),V=async(N)=>{if(N.status==="failed"||N.expiredAt&&Date.parse(N.expiredAt)<=Date.now()){let L=new q(N.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(N.id,Z)}catch(K){if(!(K instanceof q&&(K.code==="session_not_found"||K.code==="session_expired")))throw AggregateError([L,K],"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 j();if(N.length>1)throw new q("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(N[0])return await V(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 q&&(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 q("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),F,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 q("request_failed","The cloud session service returned no session id.");F=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(F)throw N;let z=!G||N instanceof q&&(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 Q1(N);if(Y.signal.aborted||!(N instanceof q)||N instanceof q&&N.code==="request_failed"&&(N.status===void 0||N.status>=500||N.status===408||N.status===409)){let K=[];try{K=await j()}catch(O){if($.handoff)throw AggregateError([N,O],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(K.length>1)throw new q("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let _=K[0];if(_){if($.handoff)return await V(_);return{sessionId:_.id,status:_.status,sandboxUrl:_.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(j){if(!(j instanceof q&&(j.code==="session_not_found"||j.code==="session_expired")))throw AggregateError([Q,j],`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:_0(X)}:void 0;while(!J.aborted){let j;try{j=await this.request(`/api/v1/session/${encodeURIComponent($)}/status`,{signal:AbortSignal.any([J,AbortSignal.timeout(m)])},void 0,Q)}catch(Y){if(J.aborted)throw Y;if(Y instanceof q&&Y.code!=="request_failed")throw Y;await J1(J);continue}let V=j?.status?.trim().toLowerCase();if(Z?.({phase:A0(j?.phase)}),V==="ready"||V==="active")return;if(V==="failed")throw new q("session_failed",j?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(V!=="provisioning")throw new q("request_failed","The cloud session service returned an unexpected provisioning status.");await J1(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(m)]):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 q)||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 q("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(m)});if(Z.status===404)return null;let X=await Z.json().catch(()=>{return});if(!Z.ok)throw q0(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 q("request_failed","Invalid archived session history");return X.messages}}import{randomUUID as z4}from"node:crypto";import{posix as F0}from"node:path";import{createSessionId as v6,ensureLoopbackProxyBypass as S1,isHubProtocolCompatible as S6,resolveClineBuildEnv as m6,resolveHubCommandTimeoutMs as I6}from"@cerebriline/shared";import p6 from"ws";var g={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",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:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var j1="session_not_found";class s extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function B0($){return $ instanceof s||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}import{spawn as Z6}from"node:child_process";import{closeSync as X6,mkdirSync as Q6,openSync as j6,readFileSync as V6,unlinkSync as Y6}from"node:fs";import{basename as W6,dirname as N6,join as F6}from"node:path";import{fileURLToPath as K6}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as L6,isBunEmbeddedModulePath as G6,isHubDaemonProcess as z6,resolveClineBuildEnv as T1,withResolvedClineBuildEnv as _6}from"@cerebriline/shared";import{createHash as U2,randomBytes as M2}from"node:crypto";import{mkdir as U0,open as V1,readFile as K1,rename as R2,rm as M0,writeFile as P2}from"node:fs/promises";import{dirname as L1,join as R0}from"node:path";import{ensureLoopbackProxyBypass as C2,isHubProtocolCompatible as H2}from"@cerebriline/shared";import{resolveClineDataDir as I,resolveClineDir as Z8}from"@cerebriline/shared/storage";var x2="CLINE_HUB_DISCOVERY_PATH",E2="CLINE_HUB_BUILD_ID",T2="CLINE_HUB_BUILD_EPOCH_MS",w2=30000,f2=15000,Y1=100;function b2($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function k2($){return U2("sha256").update($).digest("hex").slice(0,12)}function y2($){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 W1($){return new Promise((J)=>setTimeout(J,$))}function g2($){return`${$}.lock`}async function h2($){try{let J=JSON.parse(await K1(R0($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function D0($){await M0($,{recursive:!0,force:!0}).catch(()=>{return})}function h(){let $=process.env[E2]?.trim();if($)return $;return"sdk-v1-5e5cbbd449b2ed4fe502fdfcac849230ad16119851bcdf43d5731fc082612031".trim()||`source-${String(g.version)}`}function v2(){let $=Number(process.env[T2]);if(Number.isFinite($)&&$>0)return $;return Number.isFinite(1791835710163)?1791835710163:void 0}function n($,J=h()){let Z=H2($);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 N1($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:void 0}function F1($){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 S2($,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 G1($,J){let Z=$.buildId?.trim(),X=J.buildId?.trim();if(Z&&X&&Z===X)return 0;let Q=N1($.buildEpochMs),j=N1(J.buildEpochMs);if(Q!==void 0&&j!==void 0&&Q!==j)return Q<j?-1:1;let V=F1($.coreVersion),Y=F1(J.coreVersion);if(V&&Y){let W=S2(V,Y);if(W!==0)return W}if(Z&&X&&Z!==X)return Z<X?-1:1;return 0}function z1(){return{buildId:h(),buildEpochMs:v2(),coreVersion:String(g.version)}}function o($,J){let Z=J?.self??z1(),X=n($,Z.buildId??"");if(X.compatible)return!0;if(X.reason!=="build_mismatch"&&X.reason!=="missing_build")return!1;return G1(Z,$)<=0}function _1($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${k2($)}`,Z=process.env[x2]?.trim()||R0(I(),"locks","hub","owners",`${b2(J)}.json`);return{ownerId:J,discoveryPath:Z}}async function b($){try{let J=JSON.parse(await K1($,"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 q1($,J,Z){await A1($,async()=>{let X=L1($);await U0(X,{recursive:!0});let Q=`${$}.${process.pid}.${M2(6).toString("hex")}.tmp`,j;try{j=await V1(Q,"wx",384),await j.writeFile(`${JSON.stringify(J,null,2)}
9
+ `,{encoding:"utf8"}),await j.sync(),await j.close(),j=void 0,Z?.beforePublish?.(),await R2(Q,$);let V;try{V=await V1(X,"r"),await V.sync()}catch{}finally{await V?.close().catch(()=>{return})}}catch(V){throw await j?.close().catch(()=>{return}),await M0(Q,{force:!0}).catch(()=>{return}),V}})}async function v($){await A1($,async()=>{await M0($,{force:!0}).catch(()=>{return})})}async function O1($,J,Z){let X=g2($);await U0(L1(X),{recursive:!0});let Q=Date.now()+f2;while(!0){try{await U0(X,{recursive:!1})}catch(j){if((j instanceof Error&&"code"in j?String(j.code):"")!=="EEXIST")throw j;let Y=await h2(X);if(!Y){if(Date.now()>=Q){await D0(X);continue}await W1(Y1);continue}let W=Date.now()-Date.parse(Y.acquiredAt);if(!y2(Y.pid)||W>w2){await D0(X);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub ${J} lock ${X}`);await W1(Y1);continue}try{return await P2(R0(X,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
10
+ `,"utf8"),await Z()}finally{await D0(X)}}}function A1($,J){return O1(`${$}.mutation`,"discovery mutation",J)}function B1($,J){return O1($,"startup",J)}async function e($,J){C2();try{let Z=await fetch(J?.authToken?m2($):U1($),{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 D1($,J,Z="/hub"){return new URL(`ws://${$}:${J}${Z}`).toString()}function U1($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function m2($){let J=new URL(U1($));return J.pathname="/status",J.toString()}import{CLINE_HUB_DEV_PORT as I2,CLINE_HUB_PORT as p2,resolveClineBuildEnv as l2}from"@cerebriline/shared";var u2="CLINE_HUB_HOST",c2="CLINE_HUB_PORT",a2="CLINE_HUB_PATHNAME",d2="127.0.0.1",i2=p2,t2="/hub";function M1($){return l2($)==="development"?I2:i2}function r2($={}){return($.env??process.env)[u2]?.trim()||d2}function s2($={}){let Z=($.env??process.env)[c2]?.trim();if(!Z)return M1($);let X=Number.parseInt(Z,10);if(!Number.isInteger(X)||X<1||X>65535)return M1($);return X}function n2($={}){return($.env??process.env)[a2]?.trim()||t2}function R1($={},J={}){return{host:$.host??r2(J),port:$.port??s2(J),pathname:$.pathname??n2(J)}}import{join as o2}from"node:path";var e2="shared:cline",$6="CLINE_HUB_DISCOVERY_PATH",J6="hub-production";function p($=e2){return _1(`${$}@${h()}`)}function $0(){return{ownerId:J6,discoveryPath:process.env[$6]?.trim()||o2(I(),"locks","hub","production.json")}}var P1=15000,q6=200,C1=3000,O6=100,A6=[100,250,500,1000,2000],B6="--cline-hub-daemon",D6=3,U6=60000,H1=new Map;function M6($,J=Date.now()){let Z=H1.get($);if(!Z||J-Z.windowStartedAt>U6)return H1.set($,{count:1,windowStartedAt:J}),!0;return Z.count+=1,Z.count<=D6}function R6($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function P6(){try{let $=F6(I(),"logs","hub-daemon.log");return Q6(N6($),{recursive:!0}),{fd:j6($,"a"),logPath:$}}catch{return}}function C6(){return T1()==="production"?$0():p()}function l($){return o($)}function H6($){try{let J=JSON.parse(V6(`${$}.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 P0($){try{Y6(`${$}.superseded`)}catch{}}function x1($,J,Z){if(!J||J.url!==Z)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function u($,J){try{return await e($,{authToken:J})}catch{return}}async function E1($,J){let Z=Date.now()+J;while(Date.now()<Z){if(!(await u($))?.url)return!0;await new Promise((Q)=>setTimeout(Q,O6))}return!1}async function H0($,J){if(!M6($.url))return!1;await c($.url,$.authToken,"retired by newer install").catch(()=>!1),await b1($.url,$.authToken).catch(()=>!1);let Z=await E1($.url,C1);if(!Z&&$.pid&&x6($.pid)){try{process.kill($.pid,"SIGTERM")}catch{}Z=await E1($.url,C1)}if(Z)await v(J).catch(()=>{return});return Z}function x6($){try{return process.kill($,0),!0}catch(J){return J?.code==="EPERM"}}async function E6($){try{return(await x0($.url,$.authToken)).activeSessionCount>0}catch{return!1}}async function C0($,J){if(l($))return"reusable";let Z=await c($.url,$.authToken,"retired by newer install").catch(()=>!1);if(await E6($)){if(Z)await c($.url,$.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let X=await H0($,J);if(!X&&Z)await c($.url,$.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return X?"retired":"failed"}async function T6($){if(T1()!=="production")return;let J=p();if(J.discoveryPath===$.discoveryPath)return;let Z=await b(J.discoveryPath);if(Z?.url)await H0(Z,J.discoveryPath);else await v(J.discoveryPath).catch(()=>{return})}function w6(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return K6(new URL(`./entry.${$}`,import.meta.url))}function f6($,J){if(G6($))return[B6];return[...J&&$.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],$]}function b6($,J){let Z=w6(),X=process.execPath?.trim();if(!X)throw Error("unable to resolve runtime executable for hub daemon");let Q=W6(X).toLowerCase().includes("bun"),j=f6(Z,Q);return{launcher:X,args:[...j,"--cwd",$,...R6(J),...J.manageConnectors===!1?["--no-connectors"]:[]],cwd:$,env:{..._6(process.env),CLINE_NO_INTERACTIVE:"1",[L6]:"1"}}}function k6($){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 y6($,J={}){if(z6())return;let Z=b6($,J),X=P6();try{Z6(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)X6(X.fd)}}async function g6($,J={}){for(let Z=0;;Z++)try{y6($,J);return}catch(X){let Q=A6[Z];if(!k6(X)||Q===void 0)throw X;await new Promise((j)=>setTimeout(j,Q))}}async function h6($,J,Z={}){let X=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=R1(Z),j=D1(Q.host,Q.port,Q.pathname),V=(K)=>{if(!X)J0(K.url,K.authToken);else f1(K.url,K.authToken);return K};await T6($).catch(()=>{return});let Y=await b($.discoveryPath),W=Y?.url?void 0:H6($.discoveryPath),F=!1;if(Y?.url){let K=Y.authToken;if(!K)F=!0,await H0(Y,$.discoveryPath);else{let _=await u(Y.url,K);if(_?.url&&l(_)&&await w(_.url,{authToken:K}))return P0($.discoveryPath),V({url:_.url,authToken:K});if(_?.url){if(await C0({..._,authToken:K},$.discoveryPath)==="deferred_busy"&&await w(_.url,{authToken:K}))return V({url:_.url,authToken:K})}else await v($.discoveryPath).catch(()=>{return})}}let G=await u(j);if(G?.url){let K=x1(G,Y??W,j);if(l(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 q1($.discoveryPath,H)}catch{}return P0($.discoveryPath),V({url:G.url,authToken:D})}throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${F?" 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 _=await C0(K,$.discoveryPath);if(_==="deferred_busy"){for(let O of[K.authToken,Y?.authToken].filter((B)=>typeof B==="string"&&B.trim().length>0))if(await w(G.url,{authToken:O}))return V({url:G.url,authToken:O});if(Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An older Cline Hub is running at ${j} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(_==="failed"&&Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let z=Z.allowPortFallback===!0&&Q.port!==0?{...Q,port:0}:Q;await g6(J,{...z,manageConnectors:Z.manageConnectors});let L=Date.now()+P1;while(Date.now()<L){let K=await b($.discoveryPath);if(K?.url&&K.authToken){let O=await u(K.url,K.authToken);if(O?.url&&l(O)&&await w(O.url,{authToken:K.authToken}))return P0($.discoveryPath),V({url:O.url,authToken:K.authToken})}let _=await u(j);if(_?.url&&!l(_)){let O=x1(_,K??W,j),B=await C0(O,$.discoveryPath);if(B==="deferred_busy"&&K?.authToken&&await w(_.url,{authToken:K.authToken}))return V({url:_.url,authToken:K.authToken});if(B==="failed"&&Z.allowPortFallback!==!0&&Q.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((O)=>setTimeout(O,q6))}throw Error(`Timed out after ${P1}ms waiting for detached hub startup.`)}async function w1($,J={}){let Z=C6();return await B1(Z.discoveryPath,async()=>h6(Z,$,J))}function l6(){return m6()==="production"?$0():p()}function u6(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function m1($){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 m1($.data);return String($)}function c6($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function k1($){let J=$,Z=c6(J.reason);return new R("hub_connection_closed",J.code||Z?`Hub connection closed (code=${J.code??0}${Z?`, reason=${Z}`:""})`:T0,{closeCode:J.code,closeReason:Z||void 0})}function y1($,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 E0="*",Z0=8000,a6="cline-hub-auth.",b0=new Map,I1=new Set,d6=3000;var T0="Hub connection closed",i6=250,t6=5000,g1=0.5;class R extends Error{code;details;constructor($,J,Z){super(J);this.code=$;this.details=Z;this.name="HubTransportError"}}function r6($){return $ instanceof R}class w0 extends Error{command;code;constructor($,J,Z){super(Z);this.command=$;this.code=J;this.name="HubCommandError"}}function k0($,J={}){let Z=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Z)return Z;if(J.skipRegistry)return;let X=X0($.toString());return X?b0.get(X):void 0}function s6($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function X0($){if(!s6($))return;let J=new URL(p1($));return J.search="",J.hash="",J.toString()}function h1($){let J=X0($);return!!J&&I1.has(J)}function J0($,J){let Z=X0($);if(Z){if(I1.add(Z),J?.trim())b0.set(Z,J)}return $}function f1($,J){let Z=X0($);if(Z&&J?.trim())b0.set(Z,J)}class a{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",T0);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()||k0($,{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(V)=>{if(Q=V,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(g.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),Z!==this.connectGeneration||this.closedByClient){try{V.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let Y of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Y));this.reconnectAttempt=0});let j=this.connectPromise;try{await j}catch(V){if(this.connectPromise===j)this.connectPromise=void 0;if(Q&&this.socket===Q){this.lastCloseError=y1(V,$),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{Q.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw V}}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((F,G)=>{W=setTimeout(()=>{G(new R("hub_connect_timeout",`Timed out resolving hub connection headers after ${Z0}ms`))},Z0)})])}catch(F){let G=F instanceof R?F:new R("hub_connect_failed",F instanceof Error?F.message:String(F));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 j=Q?new p6($.toString(),{headers:{...Q}}):new(u6())($.toString(),J?[`${a6}${J}`]:void 0);this.socket=j;let V=!1,Y=new Promise((W,F)=>{let G=!1,N=setTimeout(()=>{if(G)return;G=!0,V=!0;let z=new R("hub_connect_timeout",`Timed out connecting to hub after ${Z0}ms`);if(this.socket===j)this.lastCloseError=z,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{j.close()}catch{}F(z)},Z0);j.addEventListener("open",()=>{if(G)return;G=!0,clearTimeout(N),W()}),j.addEventListener("error",(z)=>{if(G)return;G=!0,clearTimeout(N);let L=y1(z,$);if(this.socket===j)this.lastCloseError=L,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;F(L)}),j.addEventListener("close",(z)=>{if(G)return;G=!0,clearTimeout(N);let L=V?this.lastCloseError:k1(z);if(this.socket===j){if(!V)this.lastCloseError=L,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}F(L)})});return j.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(m1(W)))}),j.addEventListener("close",(W)=>{if(this.socket!==j)return;if(!V)this.lastCloseError=k1(W),this.sawSocketClose=!0;this.registered=!1;for(let F of this.pendingReplies.values())F.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await Y,j}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,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Z,X)}catch(V){if(!j||Q>=1||!await this.recoverLocalHubTransport(V))throw V;Q+=1}}async commandOnce($,J,Z,X,Q=!0){if(Q)await this.connect();X?.beforeDispatch?.();let j=v6("hubreq_");X?.onDispatch?.(j);let V=I6($,X?.timeoutMs),Y=new Promise((F,G)=>{let N=V===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(j))return;G(new w0($,"hub_command_timeout",`Hub command ${$} timed out after ${V}ms (hub=${this.currentUrl}, requestId=${j}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},V);this.pendingReplies.set(j,{resolve:(z)=>{if(N)clearTimeout(N);F(z)},reject:(z)=>{if(N)clearTimeout(N);G(z)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:j,clientId:this.clientId,sessionId:Z,timeoutMs:V,payload:J}})}catch(F){throw this.pendingReplies.delete(j),F}let W=await Y;if(!W.ok){if(W.error?.code===j1){let F=Z??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new s(F,W.error.message)}throw new w0($,W.error?.code,W.error?.message??`Hub command ${$} failed`)}return W}async recoverLocalHubTransport($){if(!h1(this.currentUrl)||!r6($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await v1({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(i6*2**this.reconnectAttempt,t6),J=Math.round($*(1-g1)+Math.random()*$*g1);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(!h1(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await v1({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",T0);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 $??E0}subscriptionSessionIdFromKey($){return $===E0?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[E0,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 p1($){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 a({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 f0($,J){let Z=p1($),X=await e(Z,{authToken:J?.authToken});if(!X)return{status:"unreachable",url:Z};if(J?.requireCurrentBuild){let Q=h(),j=n(X,Q);if(!j.compatible&&!o(X))return{status:j.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:Z}}else if(!S6(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 n6($){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 j=Q.participants;if(!Array.isArray(j)||j.length===0)continue;Z+=1;for(let V of j){let Y=V&&typeof V==="object"?V.clientId:void 0;if(typeof Y==="string"&&Y.trim())X.add(Y)}}return{activeSessionCount:Z,participantClientCount:X.size}}async function x0($,J,Z){let X=new a({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:d6});return n6(Q.payload)}finally{await X.dispose().catch(()=>{return})}}async function o6($,J,Z){try{return(await x0($,J,Z)).activeSessionCount===0}catch{return!1}}async function e6($,J){let Z=`${$.discoveryPath}.superseded`,X=await b(Z);if(!X?.url||!X.authToken)return;let Q=await f0(X.url,{authToken:X.authToken});if(Q.status!=="compatible")return;if(await o6(Q.url,X.authToken,J))return;return J0(Q.url,X.authToken)}async function $4($={}){if($.endpoint?.trim()){let Q=await f0($.endpoint);return Q.status==="compatible"?Q.url:void 0}let J=l6(),Z=await b(J.discoveryPath);if(!Z?.url)return await e6(J,$);let X=await f0(Z.url,{authToken:Z.authToken,requireCurrentBuild:!0});if(X.status==="compatible")return J0(X.url,Z.authToken);if(X.status==="protocol_mismatch")await v(J.discoveryPath).catch(()=>{return});return}async function v1($={}){let J=await $4($);if(J&&await w(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;try{return(await w1($.workspaceRoot??process.cwd())).url}catch(Z){$.onStartupError?.(Z);return}}async function c($,J,Z,X){S1();let Q=new URL($),j=J?.trim()||k0(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:j?{authorization:`Bearer ${j}`}:void 0})).ok}async function b1($,J){S1();let Z=new URL($),X=J?.trim()||k0(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 J4($,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():"",j=typeof Z.name==="string"?Z.name.trim():"";return{id:X,name:Q||j||X,catalogId:J}}function y0($,J){return Array.isArray($)?$.flatMap((Z)=>{let X=J4(Z,J);return X?[X]:[]}):[]}async function l1($,J={}){let Z=$.trim(),X=Z.length;while(X>0&&Z[X-1]==="/")X--;let Q=Z.slice(0,X),j=async(_)=>{let O=await(J.fetchImpl??fetch)(`${Q}${_}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!O.ok)throw Error(`HTTP ${O.status}`);return await O.json()},V,Y;try{[V,Y]=await Promise.all([j("/api/v1/ai/cline/models"),j("/api/v1/ai/cline/recommended-models")])}catch(_){throw Error("Could not load the cloud model catalog.",{cause:_})}let W=V&&typeof V==="object"?V:void 0,F=y0(Array.isArray(V)?V:W?.data,"cline"),G=Y&&typeof Y==="object"?Y:void 0,N=G?.data&&typeof G.data==="object"?G.data:G,z=y0(N?.clinePass,"cline-pass"),L=y0(N?.clineCloud,"cline-cloud"),K=new Set;return[...J.isOrganizationSession?[]:z,...L,...F].filter((_)=>{if(K.has(_.id))return!1;return K.add(_.id),!0})}import{formatDisplayUserInput as u1}from"@cerebriline/shared";var Z4=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function X4($){switch($){case"user":case"assistant":case"tool":case"system":case"status":case"error":return $;default:return"assistant"}}function Q4($){return $.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}function j4($){let J=$?.userRunSpan;return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:void 0}function V4($){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 j=Q;if(j.type==="text"&&typeof j.text==="string")X.push(j.text);else if(j.type==="tool_result"||j.type==="tool-result")Z=!0;else if(j.type==="file"||j.type==="image")J=!0}return{hasAttachment:J&&!Z,text:X.join(`
11
+ `)}}function Y4($){let J=u1($);return J.startsWith("[TASK RESUMPTION]")||J==="The user approved switching to act mode. Continue with the approved plan now."}function W4($){if(X4($.role)!=="user")return 0;let J=Q4($),Z=typeof J?.kind==="string"?J.kind:void 0,X=j4(J);if(Z==="compaction"||Z==="compaction_summary")return X??1;if(X!==void 0)return X;if(Z&&Z4.has(Z))return 0;let Q=V4($);if(!Q.hasAttachment&&!u1(Q.text))return 0;if(!Q.hasAttachment&&Y4(Q.text))return 0;return 1}function c1($){return W4($)>0}function V0($){return Array.isArray($?.sessions)?$.sessions.filter((J)=>Boolean(J)&&typeof J==="object"&&!Array.isArray(J)):[]}function g0($){let J=$.updatedAt;return typeof J==="number"?J:Date.parse(String(J??""))||0}function h0($){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 t1($,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 Q0($){let J=$.trim(),Z=J.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(Z?Z[1]:J).trim()}function d($,J,Z){let X=Q0(Z);return $.filter((Q)=>Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)&&String(Q.role??"").toLowerCase()==="user"&&(X!==""||c1(Q))&&Q0(t1(Q))===X).length+J.filter((Q)=>Q0(Q.prompt)===X).length}function v0($){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 N4=new Set(["run.completed","run.aborted","run.failed"]),F4=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function a1($,J){return $.filter((Z)=>Boolean(Z)&&typeof Z==="object"&&!Array.isArray(Z)&&String(Z.role??"").toLowerCase()==="assistant").map((Z)=>t1(Z,J)).filter(Boolean)}function d1($,J,Z="text"){let X=new Map;for(let Q of a1(J,Z))X.set(Q,(X.get(Q)??0)+1);return a1($,Z).filter((Q)=>{let j=X.get(Q)??0;if(j===0)return!0;if(j===1)X.delete(Q);else X.set(Q,j-1);return!1})}function j0($,J,Z=new Set){if(!$||typeof $!=="object")return Z;if(Array.isArray($)){for(let j of $)j0(j,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 j of Object.values(X))j0(j,J,Z);return Z}function i1($,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 j=Q.payload?.[J==="assistant"?"text":"reasoning"],V=typeof j==="string"&&j?j:X;if(V)Z=V;X=""}return(Z||X).trim()}function r1($,J,Z={}){let X=Z.queueSnapshotApplied!==!1,Q=d1(J,Z.baselineMessages??[]),j=d1(J,Z.baselineMessages??[],"thinking"),V=j0(J,"tool_use"),Y=j0(J,"tool_result"),W=new Set($.slice(0,Z.messagesSnapshotEventCutoff??$.length)),F=new Set,G=new Map;for(let O of $.slice(0,Z.messagesSnapshotEventCutoff??$.length)){let B=v0([O])[0];if(!B)continue;let D=Q0(B.prompt),H=G.get(D)??Math.max(0,d(J,[],D)-d(Z.baselineMessages??[],[],D));if(G.set(D,Math.max(0,H-1)),H>0)F.add(O)}let z=[...X?$.slice(Z.queueSnapshotEventCutoff??$.length):$].reverse().find((O)=>O.event==="session.pending_prompts"),L=[],K=[],_=(O)=>{if(K.length===0)return;let B=K.filter((x)=>W.has(x)),D=(x)=>{if(!O)return-1;let M=[...B].reverse().findIndex((J2)=>J2.event===`${x}.finished`),S=M<0?-1:B.length-1-M;return S>=0||K.at(-1)?.event==="run.aborted"?S:B.length-1},H=D("assistant"),f=D("reasoning"),A=i1(B.slice(0,H+1)),P=A?Q.findIndex((x)=>x.endsWith(A)):-1,k=P>=0;if(k)Q.splice(P,1);let i=i1(B.slice(0,f+1),"reasoning"),K0=i?j.findIndex((x)=>x.endsWith(i)):-1;if(K0>=0)j.splice(K0,1);for(let[x,M]of K.entries()){if(F.has(M)){L.push({...M,payload:{...M.payload,transcriptReflected:!0}});continue}if(W.has(M)&&F4.has(M.event)&&(M.event.startsWith("reasoning.")?K0>=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 S=String(M.payload?.toolCallId??"").trim();if(Y.has(S)||M.event==="tool.started"&&V.has(S))continue}L.push(M)}K=[]};for(let O of $)if(K.push(O),N4.has(O.event))_(!0);return _(!1),L}import{formatDisplayUserInput as K4}from"@cerebriline/shared";function W0($){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 N0($){let J=$?.trim();return J?K4(J).slice(0,120):void 0}function S0($){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:"",j=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
+ ${S0(X.content)}`:Q==="image"?"[image]":Q==="redacted_thinking"?"[redacted_thinking]":typeof X.text==="string"?X.text:"";if(j.trim())J.push(j)}return J.join(`
13
+ `)}if($&&typeof $==="object"){let J=$;if(typeof J.text==="string")return J.text}return""}function L4($){let J=N0($??void 0);if(!J)return;return J.split(`
14
+ `)[0]?.trim().slice(0,70)||void 0}function G4($){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=N0(S0(X.content));if(!Q)continue;return Q.split(`
15
+ `)[0]?.trim().slice(0,70)||void 0}return}function m0($){let J=$.metadata&&typeof $.metadata==="object"?N0($.metadata.title):void 0;if(J)return J.slice(0,70);let Z=L4($.prompt);if(Z)return Z;let X=$.messages?G4($.messages):void 0;if(X)return X;return`Session ${$.sessionId.slice(-6)}`}function s1($,J,Z,X){let Q=J.payload??{},j=()=>{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},V=(Y,W,F)=>{let G=j(),N=G.at(-1);if(N?.type===Y)N[W]=`${N[W]??""}${F}`;else G.push({type:Y,[W]:F})};switch(J.event){case"assistant.delta":if(typeof Q.text==="string")V("text","text",Q.text);return;case"reasoning.delta":if(typeof Q.text==="string"&&Q.text)V("thinking","thinking",Q.text);else if(Q.redacted===!0)j().push({type:"redacted_thinking",data:""});return;case"assistant.finished":Z.delete(X);return;case"assistant.media":if(Q.media)j().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((F)=>F.type==="tool_use"&&F.id===Y)))j().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((F)=>F.type==="tool_result"&&F.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((F)=>typeof F==="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((F)=>F.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,F=W==="pending"?"running":W;if(J.event==="session.updated"&&F==="running"&&$.endedAt!==void 0&&!$.busy)return;let G=$.busy;if($.status=F,$.busy=F==="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 I0($){return $ instanceof Error&&$.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String($.code))}function p0($,J){return $ instanceof Error&&$.name==="HubCommandError"&&$.code==="hub_command_timeout"&&(!J||$.command===J)}var U="/workspace",_4=30000,q4=2000,O4=2000,n1="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 l0($){if(!$)return U;if(F0.isAbsolute($)||$.includes("\\")||$.split("/").some((Z)=>!Z||Z==="."||Z===".."))throw new q("request_failed","The handoff workspace path must stay inside the repository.");let J=F0.join(U,$);if(!J.startsWith(`${U}/`))throw new q("request_failed","The handoff workspace path must stay inside the repository.");return J}function i0($){let J=$.metadata.cwd;return typeof J==="string"&&F0.normalize(J)===J&&(J===U||J.startsWith(`${U}/`))?J:U}function o1($){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 a0 extends Error{constructor($){super($ instanceof Error?$.message:"Cloud conversation creation was not dispatched.",{cause:$});this.name="CloudHandoffSeedRejectedError"}}class d0 extends q{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 $2 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 A4($){return $.trim().startsWith("ses-")}function B4($,J){let Z=new URL(`/api/v1/session/${encodeURIComponent(J)}`,$);return Z.protocol=Z.protocol==="https:"?"wss:":"ws:",Z.toString()}function u0($){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:$.metadata.modelId??"",modelId:$.metadata.modelId??"",repoUrl:$.repoContext.repoUrl??"",branch:$.repoContext.branch??"",cwd:i0($),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 c0($,J,Z){return{sessionId:$.id,origin:"cloud",executionTarget:"cloud",status:J,provider:"cline",model:$.metadata.modelId??"",repoUrl:$.repoContext.repoUrl??"",branch:$.repoContext.branch??"",cwd:i0($),workspaceRoot:U,...Z?.trim()?{prompt:Z.trim()}:{},metadata:{origin:"cloud",repoUrl:$.repoContext.repoUrl??"",git:{url:$.repoContext.repoUrl??"",branch:$.repoContext.branch??""}}}}function e1($){return{sessionId:$.id,origin:"cloud",executionTarget:"cloud",status:$.status,provider:"cline",model:$.metadata.modelId??"",cwd:i0($),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 D4($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function U4($,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 M4{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 a(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=u0($);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 W0({...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($):W0($);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)s1(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 q("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 A4($)||this.knownSessions.has($)||this.connections.has($)||this.sessions.get($)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord($){let J=this.knownSessions.get($);return J?e1(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 q&&(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 $=(V)=>this.sessions.get(V)?.title??this.knownSessions.get(V)?.title,J=new Map([...this.knownSessions.keys(),...this.sessions.keys()].map((V)=>[V,$(V)])),Z=(V)=>{let Y=$(V.id);if(this.titleWrites.has(V.id)||Y!==J.get(V.id))V.title=Y??V.title},X=await this.resolveActiveOrganizationId(),Q=(await this.options.api.list(X)).map((V)=>this.preserveConnectedRuntimeModel(V));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=Q;for(let V of Q)Z(V),this.knownSessions.set(V.id,V),this.unlistedSessions.delete(V.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(V)=>this.getCrossScopeDiscoveryRecord(V)));let j=await Promise.all(Q.map(async(V)=>{if(V.status!=="provisioning")return V;let Y=await this.options.api.status(V.id).catch(()=>{return}),W=Y?.status?.trim();if(!W)return V;return{...V,status:W,metadata:{...V.metadata,...A0(Y?.phase)?{provisioningPhase:Y?.phase}:{},...Y?.statusReason?.trim()?{statusReason:Y.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let V of j){Z(V),this.knownSessions.set(V.id,V);let Y=this.sessions.get(V.id);if(Y)Y.title=V.title;if(Y?.status==="provisioning"&&V.status!=="provisioning")Y.status=V.status;let W=this.connections.get(V.id);if(W)W.remote=V;let F=E(V);if(F||V.status==="failed"||V.status==="suspended"){if(Y)Y.busy=!1,Y.status=F?"expired":V.status,Y.endedAt=F?Date.parse(V.expiredAt??"")||Date.now():Math.max(Y.endedAt??0,Date.parse(V.lastActivityAt??V.createdAt)||0)||void 0;if(W)this.disposeConnection(V.id).catch(()=>{return})}}this.lastListedSessions=j;for(let V of j)if(this.sessions.has(V.id))this.publishSnapshot(V.id);return W0(j)}async handoffTargetExists($){try{return await this.options.api.status($),!0}catch(J){if(J instanceof q&&(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 l1(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 q("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 q("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 j,V=await Promise.race([J.then((Y)=>({value:Y}),(Y)=>{if(!(Y instanceof q&&Y.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:Y});return{value:this.lastListedSessions}}),new Promise((Y)=>{j=setTimeout(()=>Y({value:this.lastListedSessions}),Math.max(0,$.timeoutMs??0))})]);if(j)clearTimeout(j);Z=V.value}return[...new Map([...this.unlistedSessions.values(),...Z].map((j)=>[j.id,j])).values()].map((j)=>{let V=e1(j),Y=this.sessions.get(j.id);if(!Y)return V;let W=Y.title?.trim()||j.title?.trim();return{...V,status:Y.status,prompt:Y.prompt,endedAt:Y.endedAt!==void 0?new Date(Y.endedAt).toISOString():V.endedAt,metadata:{...V.metadata??{},title:m0({sessionId:j.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){l0(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 j=await X.client.command("session.messages",{sessionId:Q},Q);this.assertSessionActive($,X);let V=j.payload?.messages;if(!Array.isArray(V))throw Error("Cloud runtime returned no transcript after seeding.");if(J.length>0&&V.length===0)throw new $2;if(!(Z.allowAppendedMessages?V.length>=J.length&&G0(J,V.slice(0,J.length)):G0(J,V)))throw new z0(J.length,V.length);X.transcriptKnown=!0;let W=this.sessions.get($);if(W)W.messages=structuredClone(V),this.authoritativeMessages.set($,structuredClone(V)),this.streamingMessages.delete($),this.publishSnapshot($,!0)}async createOnce($){if(this.disposed)throw Error("Cloud session manager was disposed");let J=l0($.workspaceRelativePath),Z=$.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):$.organizationId??void 0,X=$.handoff,Q=!X,j=await this.options.api.create({...$,organizationId:Z,...X&&{handoff:{...X,onOuterSessionCreated:async(z,L)=>{Q=L?.created===!0,await X.onOuterSessionCreated(z,L)}}}});if(!j?.sessionId?.trim())throw new q("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(j.sessionId,j.cleanupAuthToken,$.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let V={id:j.sessionId,sandboxType:$.sandboxType,status:j.status,sandboxUrl:j.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(V.id,V),this.unlistedSessions.set(V.id,V);let{autoApproveTools:Y,thinking:W,reasoningEffort:F}=$;this.pendingInitialTasks.set(V.id,{autoApproveTools:Y,thinking:W,reasoningEffort:F});let G=this.stateFromRecord(V);G.prompt=$.initialPrompt?.trim()||void 0,G.config.mode=$.mode??"act",this.sessions.set(V.id,G);let N;try{if($.handoff){let z=await $.handoff.resolveMessages();this.assertSessionActive(V.id),N=(await this.seedHandoff(V.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(V.id,j.cleanupAuthToken,$.handoff?.onOuterSessionRemoved);throw z}return this.assertSessionActive(V.id),this.notify("chat_session_status",{sessionId:V.id,status:G.status}),{sessionId:V.id,origin:"cloud",executionTarget:"cloud",status:V.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 c0(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 j=Q.remote,V=this.sessions.get($);return c0(j,V?.status??j.status,V?.prompt)}async send($,J,Z,X,Q){let j=this.sendAbortTokens.get($),V=this.knownSessions.get($);if(V&&E(V))throw new q("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($)!==j,F=()=>{if(W())throw Error("Cloud session prompt cancelled")};if(F(),await Y.reconnectResolution,F(),await this.ensureAttached(Y),await Y.reconnectResolution,F(),!Y.transcriptKnown)await this.rehydrateAfterTransportDrop($,Y);F(),await this.updateModel(Y,X),await Y.reconnectResolution,F();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=d(N?.messages??[],N?.promptsInQueue??[],J),K=z!=="queue"&&z!=="steer",_=N&&z!=="queue"?{role:"user",content:[{type:"text",text:J}]}:void 0;if(N&&_)N.messages=[...N.messages,_];let O=()=>{if(N&&_)N.messages=N.messages.filter((A)=>A!==_),this.publishSnapshot($)};if(N&&K){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=X1(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"?_4:null,onDispatch:(k)=>{D.add(k),Y.pendingInputs??=new Map,Y.pendingInputs.set(k,{clientId:Y.client.getClientId(),ownsBusyState:K,accept:f})},beforeDispatch:()=>{if(F(),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(I0(A)||p0(A,"session.send_input")){let P;try{P=await this.rehydrateAfterTransportDrop($,Y)}catch(i){if(F(),O(),N&&K)N.busy=!1,N.status="error";if(z==="queue")throw new d0;throw i}if(F(),z==="queue")throw new d0;if(z==="steer")throw new q("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(d(P.messages,U4(P.prompts,P.submittedPrompts),J)<=L)throw new q("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&&K)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 j=this.sessions.get($),V=this.authoritativeMessages.get($)??[],Y=String(Q?.status??j?.status??"running").trim(),W=Y==="pending"?"running":Y;if(W==="running"&&!J.transcriptKnown&&!J.pendingInputs?.size)J.externalRun??={progressHydrated:!0};let F=()=>J.client.command("session.messages",{sessionId:Z},Z),G=await F().catch((A)=>{if(!p0(A,"session.messages"))throw A;return this.assertSessionActive($,J),F()});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 K=J.bufferedEventsDropped+J.bufferedEvents.length;if(j){let A=j.status!==W;if(this.authoritativeMessages.set($,structuredClone(N)),j.messages=structuredClone(N),this.streamingMessages.delete($),j.status=W,j.busy=W==="running",A)if(W==="completed"||W==="failed"||W==="aborted")j.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:$,reason:W==="failed"?"error":W});else this.notify("chat_session_status",{sessionId:$,status:W})}let _=L!==void 0&&L.ok!==!1&&Array.isArray(L.payload?.prompts),O=_?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=v0(D),f=r1(D,N,{queueSnapshotApplied:_,queueSnapshotEventCutoff:Math.max(0,K-J.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,z-J.bufferedEventsDropped),baselineMessages:V});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 j of Q)this.forwardEvent($,J,j);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 j=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),j}applyQueueSnapshot($,J){if(!Array.isArray(J.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let X=J.payload.prompts.map((j)=>({id:typeof j.id==="string"?j.id:"",prompt:typeof j.prompt==="string"?j.prompt:"",steer:j.delivery==="steer",attachmentCount:typeof j.attachmentCount==="number"?j.attachmentCount:0,userImages:Array.isArray(j.userImages)?j.userImages.filter((V)=>typeof V==="string"):void 0})).filter((j)=>j.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 j=this.sessions.get($);if(j)j.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 q?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)??u0($);return J.busy=!1,J.status="expired",this.sessions.set($.id,J),await this.loadArchivedMessages($).catch(()=>{return}),c0($,"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)??u0($);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 q("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 q("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($),j=Q?await Q:this.connections.get($);if(j?.remote.status==="suspended")return await this.disposeConnection($),X(),await this.ensureConnection($,J);if(j){if(this.assertSessionActive($,j),await j.reconnectResolution,this.assertSessionActive($,j),!j.innerSessionId)await j.client.connect(),await j.reconnectResolution,this.assertSessionActive($,j),await this.resolveInnerSession($,j,Boolean(J.handoffSeed)),this.assertSessionActive($,j);if(J.handoffSeed&&j.innerSessionId)await this.assertHandoffConnectionReusable(j,J.handoffSeed);if(J.createInner&&!j.innerSessionId)await this.createInnerSession(j,J.handoffSeed);return this.assertSessionActive($,j),j}let V=(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 q?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(K){if(!(K instanceof q)||K.status!==409)throw K;X(),N.signal.throwIfAborted();let _=await this.options.api.status($,{signal:N.signal});if(_.status!=="provisioning"&&_.status!=="ready"&&_.status!=="active")throw K;Y={...Y,status:_.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:K})=>{Y.metadata.provisioningPhase=K,this.notify("chat_session_status",{sessionId:$,status:"provisioning",phase:K})}),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 q&&L.code==="session_failed"){if(Y.status="failed",Y.metadata.statusReason=L.detail,Y.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set($,Y);let K=this.sessions.get($);if(K)K.status="error";this.notify("chat_session_status",{sessionId:$,status:"error"})}throw L}finally{z()}}if(X(),Y.status==="failed")throw new q("session_failed",Y.metadata.statusReason||"The cloud sandbox could not be prepared.");if(E(Y))throw new q("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,F=0,G=this.createHubClient({url:B4(this.options.apiBaseUrl,$),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${$}-${z4()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:U,cwd:U,resolveConnectionHeaders:async()=>{X();let N=F>0;if(F+=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 K=(async()=>{if(await this.resolveInnerSession($,L),L.innerSessionId)await this.rehydrateAfterTransportDrop($,L)})().catch(()=>this.disposeConnectionIfSessionGone($,L)).finally(()=>{if(L.reconnectResolution===K)L.reconnectResolution=void 0,L.connected=L.transcriptKnown,this.publishSnapshot($)});L.reconnectResolution=K}}let z=await this.options.getAuthToken();if(!z?.trim())throw new q("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(I0(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($)===V)this.connectionPromises.delete($)});return this.connectionPromises.set($,V),await V}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(!B0(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,F)=>g0(F)-g0(W))[0]}let j=String(Q?.sessionId??"").trim();if(!j||!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,j,Q),this.assertSessionActive($,J);this.pendingInitialTasks.delete($),J.innerSessionId=j,this.subscribeToInnerSession($,J);let V=h0(Q);if(V)this.applyModel(J,V);await this.ensureAttached(J)}async restoreSavedInnerSession($,J,Z){let X=()=>$.client.command("session.update_connection",{sessionId:J,updates:{}},J);try{await X();return}catch(K){if(!(B0(K)||K instanceof Error&&K.code==="command_failed"&&K.message===`session not found: ${J}`))throw K}this.assertSessionActive($.remote.id,$);let Q=await $.client.command("session.messages",{},J);this.assertSessionActive($.remote.id,$);let j=Q.payload?.messages;if(!Array.isArray(j)||j.length===0)throw Error("The saved conversation is empty or unavailable.");let V=Z.metadata??{},Y=Z.runtimeOptions??{},W=this.sessions.get($.remote.id)?.config,F=Object.hasOwn(V,"thinking")?V.thinking:W?.thinking,G=Object.hasOwn(V,"reasoningEffort")?V.reasoningEffort:W?.reasoningEffort,N=typeof V.autoApproveTools==="boolean"?V.autoApproveTools:W?.autoApproveTools,z=Z.cwd??Z.workspaceRoot??U,L=Z.workspaceRoot??U;try{let K=await $.client.command("session.create",{workspaceRoot:L,cwd:z,initialMessages:j,metadata:{...V,interactive:!0},sessionConfig:{sessionId:J,providerId:V.provider??"cline",modelId:V.model??V.modelId??$.remote.metadata.modelId,workspaceRoot:L,cwd:z,systemPrompt:Y.systemPrompt??V.systemPrompt??"",mode:Y.mode??V.mode??"act",...typeof F==="boolean"?{thinking:F}:{},...typeof G==="string"?{reasoningEffort:G}:{},...V.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:Y,...typeof N==="boolean"?{toolPolicies:{"*":{autoApprove:N}}}:{}});if(this.assertSessionActive($.remote.id,$),(K.payload?.session?.sessionId??K.payload?.sessionId)!==J)throw Error("Cloud Hub did not restore the requested session.")}catch(K){if(K?.code!=="session_already_exists")throw K;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||o1(Q)!==J.sourceSessionId)throw new q("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 q("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,j=String(Q?.sessionId??"").trim();if(X.length!==1||!j||o1(Q)!==J.sourceSessionId)throw new q("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return $.innerSessionId=j,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=l0(J?.workspaceRelativePath),j=J?.mode??"act";try{await J?.onSeeding?.(),this.assertSessionActive($.remote.id,$)}catch(O){if(J)throw new a0(O);throw O}let V=`cline/${($.remote.metadata.taskId?.trim()||$.remote.id).slice(-8).toLowerCase()}`,Y=$.remote.sandboxType==="resumable"||$.remote.metadata.sandboxType==="resumable",W=`${n1}
16
16
 
17
- Do all work for this task on the branch \`${V}\`: 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 \`${V}\` 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 ${V}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks.",F=J?.config?.thinking??X?.config.thinking,G=J?.config?.reasoningEffort??X?.config.reasoningEffort,N=!1,z=$.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 \`${V}\`: 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 \`${V}\` 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 ${V}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks.",F=J?.config?.thinking??X?.config.thinking,G=J?.config?.reasoningEffort??X?.config.reasoningEffort,N=!1,z=$.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?`${n1}
18
18
 
19
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?"":`
20
20
 
21
- Continue from the original repository subdirectory at ${Q}.`):W,mode:j,enableTools:!0,...typeof F==="boolean"?{thinking:F}:{},...typeof G==="string"?{reasoningEffort:G}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:Z,interactive:!0,thinking:F??null,reasoningEffort:F===!1?null:G??null,...J?{handoff:{from:"local",sourceSessionId:J.sourceSessionId,outerSessionId:$.remote.id}}:{}},runtimeOptions:{mode:j},modelSelection:{provider:"cline",model:Z},toolPolicies:{"*":{autoApprove:(J?.config?.autoApproveTools??X?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive($.remote.id,$),onDispatch:()=>{N=!0}}),K;try{K=await z}catch(A){if(J&&!N)throw new c0(A);if(J&&(I0(A,"session.create")||m0(A)))this.unconfirmedInnerCreates.add($.remote.id);throw A}this.assertSessionActive($.remote.id,$);let L=K.payload?.session&&typeof K.payload.session==="object"?K.payload.session:void 0,_=String(L?.sessionId??K.payload?.sessionId??"").trim();if(!_){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=_,$.remote.metadata.cwd=Q,X)X.config.cwd=Q,X.config.mode=j;this.subscribeToInnerSession($.remote.id,$),this.applySessionModel($,L),$.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>q4){let Q=J.seenEventIds.values().next().value;if(Q)J.seenEventIds.delete(Q)}}if(J.bufferingEvents){if(J.bufferedEvents.push(Z),J.bufferedEvents.length>_4)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 V=String(Z.payload?.approvalId??"").trim();if(V)this.removeApproval($,V);return}if(Z.event==="run.started"){let V=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(V)}}let X=J.externalRun,Q=Z.event==="run.completed"||Z.event==="run.failed"||Z.event==="run.aborted",j=X&&!X.progressHydrated&&(Z.event==="assistant.delta"||Z.event==="reasoning.delta"||Z.event==="tool.started");if(X&&(j||Q)){if(X.progressHydrated=!0,Q)J.externalRun=void 0;let V=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"})}),!V){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}`,j={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:B4(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:j,resolve:async(V)=>{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:V.approved,reason:V.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 j=this.sessions.get($.remote.id),V=X.runtimeOptions?.mode;if(j&&(V==="act"||V==="plan"||V==="yolo"||V==="zen"))j.config.mode=V}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((V)=>V.id===$),j=Q?this.preserveConnectedRuntimeModel(Q):void 0;if(!j){await this.disposeConnection($).catch(()=>{return});return}if(this.knownSessions.set($,j),J.remote=j,j.status==="failed"||j.status==="suspended"){let V=this.sessions.get($);if(V)V.busy=!1,V.status=j.status,V.endedAt=Date.parse(j.updatedAt)||Date.now();await this.disposeConnection($).catch(()=>{return});return}if(E(j))await this.attachExpired(j).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,j0 as readSessionRows,y4 as readCloudHandoffMetadata,f4 as preflightCloudHandoffGit,A0 as parseCloudProvisioningPhase,W0 as normalizeSessionTitle,n0 as normalizeGitHubRemoteUrl,g4 as mergeCloudHandoffMetadata,p1 as loadCloudModels,V0 as isRootSessionRow,A4 as isCloudOuterSessionId,Z1 as deriveCloudSessionTitle,N2 as createCloudHandoffFingerprint,d as countPromptOccurrences,o1 as cloudSessionToDiscoveryRecord,L0 as cloudHandoffTranscriptsEqual,k4 as cloudHandoffFingerprintsEqual,h4 as clearCloudHandoffMetadata,v4 as buildCloudHandoffDashboardUrl,q as CloudSessionError,U4 as CloudSessionController,O2 as CloudSessionApi,a0 as CloudQueueUnconfirmedError,G0 as CloudHandoffTranscriptMismatchError,e1 as CloudHandoffSeedUnsupportedError,c0 as CloudHandoffSeedRejectedError,H as CloudHandoffGitPreflightError,X1 as CloudHandoffCreationRejectedError};
21
+ Continue from the original repository subdirectory at ${Q}.`):W,mode:j,enableTools:!0,...typeof F==="boolean"?{thinking:F}:{},...typeof G==="string"?{reasoningEffort:G}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:Z,interactive:!0,thinking:F??null,reasoningEffort:F===!1?null:G??null,...J?{handoff:{from:"local",sourceSessionId:J.sourceSessionId,outerSessionId:$.remote.id}}:{}},runtimeOptions:{mode:j},modelSelection:{provider:"cline",model:Z},toolPolicies:{"*":{autoApprove:(J?.config?.autoApproveTools??X?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive($.remote.id,$),onDispatch:()=>{N=!0}}),L;try{L=await z}catch(O){if(J&&!N)throw new a0(O);if(J&&(p0(O,"session.create")||I0(O)))this.unconfirmedInnerCreates.add($.remote.id);throw O}this.assertSessionActive($.remote.id,$);let K=L.payload?.session&&typeof L.payload.session==="object"?L.payload.session:void 0,_=String(K?.sessionId??L.payload?.sessionId??"").trim();if(!_){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=_,$.remote.metadata.cwd=Q,X)X.config.cwd=Q,X.config.mode=j;this.subscribeToInnerSession($.remote.id,$),this.applySessionModel($,K),$.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>O4){let Q=J.seenEventIds.values().next().value;if(Q)J.seenEventIds.delete(Q)}}if(J.bufferingEvents){if(J.bufferedEvents.push(Z),J.bufferedEvents.length>q4)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 V=String(Z.payload?.approvalId??"").trim();if(V)this.removeApproval($,V);return}if(Z.event==="run.started"){let V=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(V)}}let X=J.externalRun,Q=Z.event==="run.completed"||Z.event==="run.failed"||Z.event==="run.aborted",j=X&&!X.progressHydrated&&(Z.event==="assistant.delta"||Z.event==="reasoning.delta"||Z.event==="tool.started");if(X&&(j||Q)){if(X.progressHydrated=!0,Q)J.externalRun=void 0;let V=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"})}),!V){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}`,j={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:D4(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:j,resolve:async(V)=>{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:V.approved,reason:V.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=h0(J);if(Z)this.applyModel($,Z);let X=J,Q=typeof X.cwd==="string"&&F0.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 j=this.sessions.get($.remote.id),V=X.runtimeOptions?.mode;if(j&&(V==="act"||V==="plan"||V==="yolo"||V==="zen"))j.config.mode=V}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((V)=>V.id===$),j=Q?this.preserveConnectedRuntimeModel(Q):void 0;if(!j){await this.disposeConnection($).catch(()=>{return});return}if(this.knownSessions.set($,j),J.remote=j,j.status==="failed"||j.status==="suspended"){let V=this.sessions.get($);if(V)V.busy=!1,V.status=j.status,V.endedAt=Date.parse(j.updatedAt)||Date.now();await this.disposeConnection($).catch(()=>{return});return}if(E(j))await this.attachExpired(j).catch(()=>{return}),await this.disposeConnection($).catch(()=>{return})}}export{g0 as updatedAt,v0 as submittedPromptsFromEvents,S0 as stringifyMessageContent,h0 as sessionRowModelId,m0 as resolveSessionListTitle,r1 as reconcileBufferedCloudEvents,V0 as readSessionRows,g4 as readCloudHandoffMetadata,b4 as preflightCloudHandoffGit,A0 as parseCloudProvisioningPhase,N0 as normalizeSessionTitle,o0 as normalizeGitHubRemoteUrl,h4 as mergeCloudHandoffMetadata,l1 as loadCloudModels,Y0 as isRootSessionRow,A4 as isCloudOuterSessionId,X1 as deriveCloudSessionTitle,F2 as createCloudHandoffFingerprint,d as countPromptOccurrences,e1 as cloudSessionToDiscoveryRecord,G0 as cloudHandoffTranscriptsEqual,y4 as cloudHandoffFingerprintsEqual,v4 as clearCloudHandoffMetadata,S4 as buildCloudHandoffDashboardUrl,q as CloudSessionError,M4 as CloudSessionController,B2 as CloudSessionApi,d0 as CloudQueueUnconfirmedError,z0 as CloudHandoffTranscriptMismatchError,$2 as CloudHandoffSeedUnsupportedError,a0 as CloudHandoffSeedRejectedError,C as CloudHandoffGitPreflightError,Q1 as CloudHandoffCreationRejectedError};