@cline/core 0.0.91 → 0.0.92-nightly.1791513440
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloud/index.js +14 -14
- package/dist/hub/daemon/entry.js +144 -144
- package/dist/hub/index.js +138 -138
- package/dist/index.d.ts +1 -1
- package/dist/index.js +184 -184
- package/dist/remote/remote-helper-entry.js +1 -1
- package/dist/remote/remote-helper.js +1 -1
- package/dist/services/mcp-install.d.ts +9 -0
- package/package.json +4 -4
package/dist/cloud/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{execFile as nn}from"node:child_process";import{basename as
|
|
2
|
-
`)){let[o
|
|
1
|
+
import{execFile as nn}from"node:child_process";import{basename as Pi,resolve as sn}from"node:path";import{promisify as on}from"node:util";import{processWorkspaceInfo as Ei}from"@cline/shared";import Ve from"simple-git";var rn=on(nn);function an(e,t){return rn("git",e,{cwd:t.cwd,encoding:"utf8",windowsHide:!0,signal:t.signal,timeout:15000,maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND||"ssh -o BatchMode=yes"}})}function K(e){if(!e||typeof e!=="object"||!("stderr"in e))return"";return typeof e.stderr==="string"?e.stderr.trim():""}function Q(e){if(!e||typeof e!=="object"||!("code"in e))return;return typeof e.code==="number"?e.code:void 0}function Ke(e){let t=Qe(e.cwd),n=e.git??an,s=async(o)=>(await n(o,{cwd:t,signal:e.signal})).stdout,i=async(o)=>(await s(o)).trim();return{async isInsideWorkTree(){try{return await i(["rev-parse","--is-inside-work-tree"])==="true"}catch(o){if(Q(o)===128&&/not a git repository|Kein Git-Repository/i.test(K(o)))return!1;throw o}},remotes:()=>Ve({baseDir:t}).getRemotes(!0),displayBranch:async()=>(await Ve({baseDir:t}).branch()).current.trim(),symbolicBranch:()=>i(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>i(["rev-parse","HEAD"]),workspacePrefix:async()=>(await s(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>i(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(o)=>i(["config","--get",`branch.${o}.remote`]),branchMergeRef:(o)=>i(["config","--get",`branch.${o}.merge`]),remoteUrl:(o)=>i(["remote","get-url",o]),remoteRefs:(o,r)=>i(["ls-remote","--exit-code",o,r])}}function Qe(e){return sn(e)}class _ extends Error{code;constructor(e,t,n){super(t,n);this.code=e;this.name="CloudHandoffGitPreflightError"}}function Ye(e){let t=0,n=e.length;while(t<n&&e[t]==="/")t+=1;while(n>t&&e[n-1]==="/")n-=1;let s=e.slice(t,n);return s.toLowerCase().endsWith(".git")?s.slice(0,-4):s}function Xe(e){let t=e.trim();if(!t)return null;let n=t.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(n?.[1]){let s=Ye(n[1]);return s.split("/").length===2?`https://github.com/${s}`:null}try{let s=new URL(t);if(s.hostname.toLowerCase()!=="github.com")return null;if(!new Set(["https:","http:","ssh:","git:"]).has(s.protocol))return null;let i=Ye(s.pathname);return i.split("/").length===2?`https://github.com/${i}`:null}catch{return null}}async function O(e,t,n){try{return await e()}catch(s){let i=K(s);throw new _(t,i?`${n} (${i})`:n,{cause:s})}}function dn(e,t){let n=`refs/heads/${t}`;for(let s of e.split(`
|
|
2
|
+
`)){let[i,o]=s.trim().split(/\s+/,2);if(o===n&&/^[0-9a-f]{40,64}$/i.test(i??""))return i??null}return null}function cn(e){let t=e.replace(/[\r\n]+$/,"").replace(/\/+$/,"");if(!t)return;let n=t.split("/");if(t.startsWith("/")||n.some((s)=>!s||s==="."||s===".."))throw new _("git_command_failed","Could not resolve the workspace path relative to the Git repository.");return t}async function Mi(e){let t=Ke(e);if(!await O(t.isInsideWorkTree,"not_git_repository","Cloud handoff requires a Git repository."))throw new _("not_git_repository","Cloud handoff requires a Git working tree.");let s=cn(await O(t.workspacePrefix,"git_command_failed","Could not resolve the workspace path relative to the Git repository.")),i=await O(t.worktreeStatus,"git_command_failed","Could not inspect the Git worktree.");if(i){let p=i.split(`
|
|
3
3
|
`).filter(Boolean),m=p.slice(0,5).join(`
|
|
4
4
|
`),y=p.length>5?`
|
|
5
5
|
...and ${p.length-5} more`:"";throw new _("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
|
|
6
6
|
|
|
7
|
-
${m}${y}`)}let
|
|
8
|
-
`)[0]??"").trim().slice(0,72)}class g extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${yn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class ot extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function ye(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function bn(e){return`${nt}${e}`.slice(0,255)}function et(e){return e?.startsWith(nt)===!0}function be(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function me(e){let t=hn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function tt(e){return new Promise((t,n)=>{if(e.aborted){n(e.reason);return}let s=()=>{clearTimeout(o),n(e.reason)},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},gn);e.addEventListener("abort",s,{once:!0})})}function wn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function ge(e,t,n,s){let o=wn(t,`Cloud session request failed (${e})`);if(e===401)return new g("authentication_required",o);if(e===404)return new g("session_not_found",o);if(e===410)return new g("session_expired",o);if(e===412)return new g("github_not_connected",o,s??`${ye(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new g("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new g("request_failed",o,void 0,e)}class vn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=ye(e.apiBaseUrl),this.appBaseUrl=ye(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??mn}async request(e,t={},n,s,o){let i=!1,a;while(!0){let r;try{r=typeof s==="string"?s:await this.options.getAuthToken()}catch(f){if(a)throw ge(401,void 0,this.appBaseUrl,n);throw f}if(!r?.trim())throw new g("authentication_required","Sign in to Cline before starting a cloud session.");if(r.trim()===a)throw new g("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?me(r.trim())!==s.subject:r.trim()!==s.token)throw new g("authentication_required","The signed-in account changed during cloud session creation.");s.token=r.trim()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${r.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),u=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,a=r.trim();continue}throw ge(d.status,u,this.appBaseUrl,n)}return u?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&et(i.title)?void 0:i.title,repoContext:i.repoContext&&typeof i.repoContext==="object"?i.repoContext:{},metadata:{...i.metadata&&typeof i.metadata==="object"?i.metadata:{},...!n&&et(i.title)?{createRequestTitle:i.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let o=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:o.flatMap((i)=>{let a=Number(i.id),r=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(a)||a<=0||!r)return[];let d=String(i.name??"").trim();return[{id:a,name:d,fullName:String(i.full_name??(d||r)).trim(),url:r,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof g&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new g("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,a=n.query?.trim(),r=n.cursor?.trim();if(a)i.set("query",a);if(r)i.set("cursor",r);let d=i.size>0?`${o}?${i}`:o;try{let u=await this.request(d),f=Array.isArray(u)?u:Array.isArray(u?.items)?u.items:[],c=a?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let l=String(h.name??"").trim();return l&&(!Array.isArray(u)||!c||l.toLowerCase().includes(c))?[l]:[]}),nextToken:Array.isArray(u)?"":String(u?.nextToken??"").trim()}}catch(u){if(u instanceof g&&u.code==="session_not_found")return{available:!1,branches:[]};throw u}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new g("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new g("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:me(t)},s=bn(e.requestId?.trim()||fn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new g("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),a=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let l=new g(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(p){if(!(p instanceof g&&(p.code==="session_not_found"||p.code==="session_expired")))throw AggregateError([l,p],"The unusable recovered cloud handoff workspace could not be removed.")}if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.delete(o);throw await e.handoff?.onOuterSessionRemoved?.(c.id),l}await e.handoff?.onOuterSessionCreated(c.id,{created:!1});let h={sessionId:c.id,status:c.status,sandboxUrl:c.sandboxUrl,cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,h);return h};if(o){let c=await i();if(c.length>1)throw new g("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await a(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(l){if(l instanceof g&&(l.code==="session_not_found"||l.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(o),this.unconfirmedHandoffCreates.delete(o);throw l}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:n.token}}if(this.unconfirmedHandoffCreates.has(o))throw new g("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let r=new AbortController,d=setTimeout(()=>r.abort(),this.createTimeoutMs),u,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:r.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new g("request_failed","The cloud session service returned no session id.");u=h,await this.persistHandoffOuterSession(e,h,n,o);let l={sessionId:h,status:c.status?.trim()||"provisioning",sandboxUrl:c.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,l);return l}catch(c){if(u)throw c;let h=!f||c instanceof g&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new ot(c);if(r.signal.aborted||!(c instanceof g)||c instanceof g&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let p=[];try{p=await i()}catch(y){if(e.handoff)throw AggregateError([c,y],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(p.length>1)throw new g("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let m=p[0];if(m){if(e.handoff)return await a(m);return{sessionId:m.id,status:m.status,sandboxUrl:m.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof g&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject:me(s)}:void 0;while(!t.aborted){let i;try{i=await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:AbortSignal.any([t,AbortSignal.timeout(B)])},void 0,o)}catch(r){if(t.aborted)throw r;if(r instanceof g&&r.code!=="request_failed")throw r;await tt(t);continue}let a=i?.status?.trim().toLowerCase();if(n?.({phase:be(i?.phase)}),a==="ready"||a==="active")return;if(a==="failed")throw new g("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(a!=="provisioning")throw new g("request_failed","The cloud session service returned an unexpected provisioning status.");await tt(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof g)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new g("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw ge(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new g("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as go}from"node:crypto";import{posix as ue}from"node:path";import{createSessionId as Bs,ensureLoopbackProxyBypass as Lt,isHubProtocolCompatible as qs,resolveClineBuildEnv as Ns,resolveHubCommandTimeoutMs as $s}from"@cline/shared";import Ws from"ws";var q={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.91",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var it="session_not_found";class Y extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function we(e){return e instanceof Y||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as ss}from"node:child_process";import{closeSync as os,mkdirSync as is,openSync as rs,readFileSync as as,unlinkSync as ds}from"node:fs";import{basename as cs,dirname as us,join as ls}from"node:path";import{fileURLToPath as ps}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fs,isBunEmbeddedModulePath as hs,isHubDaemonProcess as ms,resolveClineBuildEnv as Et,withResolvedClineBuildEnv as gs}from"@cline/shared";import{createHash as Sn,randomBytes as kn}from"node:crypto";import{mkdir as Ce,open as rt,readFile as lt,rename as Rn,rm as Se,writeFile as _n}from"node:fs/promises";import{dirname as pt,join as ke}from"node:path";import{ensureLoopbackProxyBypass as Pn,isHubProtocolCompatible as An}from"@cline/shared";import{resolveClineDataDir as N,resolveClineDir as oi}from"@cline/shared/storage";var Tn="CLINE_HUB_DISCOVERY_PATH",En="CLINE_HUB_BUILD_ID",xn="CLINE_HUB_BUILD_EPOCH_MS",Hn=30000,In=15000,at=100;function Mn(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function On(e){return Sn("sha256").update(e).digest("hex").slice(0,12)}function Un(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function dt(e){return new Promise((t)=>setTimeout(t,e))}function Dn(e){return`${e}.lock`}async function Ln(e){try{let t=JSON.parse(await lt(ke(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function ve(e){await Se(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[En]?.trim();if(e)return e;return"sdk-v1-c1bf51469e968bdbb12c455cf79b1394034ae9539bf4942e125ed5b984d0aa30".trim()||`source-${String(q.version)}`}function Bn(){let e=Number(process.env[xn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1791352724833)?1791352724833:void 0}function X(e,t=U()){let n=An(e);if(!n.compatible)return n;let s=e.buildId?.trim();if(!s)return{compatible:!1,reason:"missing_build"};if(s!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ct(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ut(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((s)=>Number(s));if(n.length===0||n.some((s)=>!Number.isInteger(s)||s<0))return;return n}function qn(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let s=e[n]??0,o=t[n]??0;if(s!==o)return s<o?-1:1}return 0}function ft(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=ct(e.buildEpochMs),i=ct(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let a=ut(e.coreVersion),r=ut(t.coreVersion);if(a&&r){let d=qn(a,r);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function ht(){return{buildId:U(),buildEpochMs:Bn(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??ht(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return ft(n,e)<=0}function mt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${On(e)}`,n=process.env[Tn]?.trim()||ke(N(),"locks","hub","owners",`${Mn(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e){try{let t=JSON.parse(await lt(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function gt(e,t){await bt(e,async()=>{let n=pt(e);await Ce(n,{recursive:!0});let s=`${e}.${process.pid}.${kn(6).toString("hex")}.tmp`,o;try{o=await rt(s,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
|
|
9
|
-
`,{encoding:"utf8"}),await
|
|
10
|
-
`,"utf8"),await n()}finally{await ve(s)}}}function bt(e,t){return yt(`${e}.mutation`,"discovery mutation",t)}function wt(e,t){return yt(e,"startup",t)}async function ee(e,t){Pn();try{let n=await fetch(t?.authToken?Nn(e):Ct(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let s=await n.json();if(typeof s.protocolVersion!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string")return;return{protocolVersion:s.protocolVersion,minClientProtocolVersion:typeof s.minClientProtocolVersion==="string"?s.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof s.maxClientProtocolVersion==="string"?s.maxClientProtocolVersion:void 0,capabilities:Array.isArray(s.capabilities)?s.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof s.coreVersion==="string"?s.coreVersion:void 0,buildId:typeof s.buildId==="string"?s.buildId:void 0,buildEpochMs:typeof s.buildEpochMs==="number"?s.buildEpochMs:void 0,host:s.host,port:s.port,url:s.url,hubId:typeof s.hubId==="string"?s.hubId:void 0,authToken:typeof s.authToken==="string"?s.authToken:void 0,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:typeof s.startedAt==="string"?s.startedAt:void 0,updatedAt:typeof s.updatedAt==="string"?s.updatedAt:void 0}}catch{return}}function vt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Ct(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function Nn(e){let t=new URL(Ct(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as $n,CLINE_HUB_PORT as Wn,resolveClineBuildEnv as jn}from"@cline/shared";var Fn="CLINE_HUB_HOST",zn="CLINE_HUB_PORT",Gn="CLINE_HUB_PATHNAME",Jn="127.0.0.1",Vn=Wn,Kn="/hub";function St(e){return jn(e)==="development"?$n:Vn}function Qn(e={}){return(e.env??process.env)[Fn]?.trim()||Jn}function Yn(e={}){let n=(e.env??process.env)[zn]?.trim();if(!n)return St(e);let s=Number.parseInt(n,10);if(!Number.isInteger(s)||s<1||s>65535)return St(e);return s}function Xn(e={}){return(e.env??process.env)[Gn]?.trim()||Kn}function kt(e={},t={}){return{host:e.host??Qn(t),port:e.port??Yn(t),pathname:e.pathname??Xn(t)}}import{join as Zn}from"node:path";var es="shared:cline",ts="CLINE_HUB_DISCOVERY_PATH",ns="hub-production";function W(e=es){return mt(`${e}@${U()}`)}function te(){return{ownerId:ns,discoveryPath:process.env[ts]?.trim()||Zn(N(),"locks","hub","production.json")}}var Rt=15000,ys=200,_t=3000,bs=100,ws=[100,250,500,1000,2000],vs="--cline-hub-daemon",Cs=3,Ss=60000,Pt=new Map;function ks(e,t=Date.now()){let n=Pt.get(e);if(!n||t-n.windowStartedAt>Ss)return Pt.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Cs}function Rs(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function _s(){try{let e=ls(N(),"logs","hub-daemon.log");return is(us(e),{recursive:!0}),{fd:rs(e,"a"),logPath:e}}catch{return}}function Ps(){return Et()==="production"?te():W()}function j(e){return Z(e)}function As(e){try{let t=JSON.parse(as(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function Re(e){try{ds(`${e}.superseded`)}catch{}}function At(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function F(e,t){try{return await ee(e,{authToken:t})}catch{return}}async function Tt(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await F(e))?.url)return!0;await new Promise((o)=>setTimeout(o,bs))}return!1}async function Pe(e,t){if(!ks(e.url))return!1;await z(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Ht(e.url,e.authToken).catch(()=>!1);let n=await Tt(e.url,_t);if(!n&&e.pid&&Ts(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Tt(e.url,_t)}if(n)await D(t).catch(()=>{return});return n}function Ts(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Es(e){try{return(await Ae(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function _e(e,t){if(j(e))return"reusable";let n=await z(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await Es(e)){if(n)await z(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let s=await Pe(e,t);if(!s&&n)await z(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return s?"retired":"failed"}async function xs(e){if(Et()!=="production")return;let t=W();if(t.discoveryPath===e.discoveryPath)return;let n=await I(t.discoveryPath);if(n?.url)await Pe(n,t.discoveryPath);else await D(t.discoveryPath).catch(()=>{return})}function Hs(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return ps(new URL(`./entry.${e}`,import.meta.url))}function Is(e,t){if(hs(e))return[vs];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function Ms(e,t){let n=Hs(),s=process.execPath?.trim();if(!s)throw Error("unable to resolve runtime executable for hub daemon");let o=cs(s).toLowerCase().includes("bun"),i=Is(n,o);return{launcher:s,args:[...i,"--cwd",e,...Rs(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...gs(process.env),CLINE_NO_INTERACTIVE:"1",[fs]:"1"}}}function Os(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function Us(e,t={}){if(ms())return;let n=Ms(e,t),s=_s();try{ss(n.launcher,n.args,{detached:!0,stdio:s?["ignore",s.fd,s.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(s)os(s.fd)}}async function Ds(e,t={}){for(let n=0;;n++)try{Us(e,t);return}catch(s){let o=ws[n];if(!Os(s)||o===void 0)throw s;await new Promise((i)=>setTimeout(i,o))}}async function Ls(e,t,n={}){let s=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=kt(n),i=vt(o.host,o.port,o.pathname),a=(p)=>{if(!s)ne(p.url,p.authToken);return p};await xs(e).catch(()=>{return});let r=await I(e.discoveryPath),d=r?.url?void 0:As(e.discoveryPath),u=!1;if(r?.url){let p=r.authToken;if(!p)u=!0,await Pe(r,e.discoveryPath);else{let m=await F(r.url,p);if(m?.url&&j(m)&&await x(m.url,{authToken:p}))return Re(e.discoveryPath),a({url:m.url,authToken:p});if(m?.url){if(await _e({...m,authToken:p},e.discoveryPath)==="deferred_busy"&&await x(m.url,{authToken:p}))return a({url:m.url,authToken:p})}else await D(e.discoveryPath).catch(()=>{return})}}let f=await F(i);if(f?.url){let p=At(f,r??d,i);if(j(f)){let y=[f.authToken,r?.authToken,d?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0);for(let v of y){if(!await x(f.url,{authToken:v}))continue;let P={hubId:f.hubId??`repaired-${f.port}`,protocolVersion:f.protocolVersion,minClientProtocolVersion:f.minClientProtocolVersion,maxClientProtocolVersion:f.maxClientProtocolVersion,capabilities:f.capabilities,coreVersion:f.coreVersion,buildId:f.buildId,authToken:v,host:f.host,port:f.port,url:f.url,pid:f.pid??r?.pid??d?.pid,startedAt:f.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await gt(e.discoveryPath,P)}catch{}return Re(e.discoveryPath),a({url:f.url,authToken:v})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${u?" 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 m=await _e(p,e.discoveryPath);if(m==="deferred_busy"){for(let y of[p.authToken,r?.authToken].filter((w)=>typeof w==="string"&&w.trim().length>0))if(await x(f.url,{authToken:y}))return a({url:f.url,authToken:y});if(n.allowPortFallback!==!0&&o.port!==0)throw Error(`An older Cline Hub is running at ${i} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(m==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let h=n.allowPortFallback===!0&&o.port!==0?{...o,port:0}:o;await Ds(t,{...h,manageConnectors:n.manageConnectors});let l=Date.now()+Rt;while(Date.now()<l){let p=await I(e.discoveryPath);if(p?.url&&p.authToken){let y=await F(p.url,p.authToken);if(y?.url&&j(y)&&await x(y.url,{authToken:p.authToken}))return Re(e.discoveryPath),a({url:y.url,authToken:p.authToken})}let m=await F(i);if(m?.url&&!j(m)){let y=At(m,p??d,i),w=await _e(y,e.discoveryPath);if(w==="deferred_busy"&&p?.authToken&&await x(m.url,{authToken:p.authToken}))return a({url:m.url,authToken:p.authToken});if(w==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((y)=>setTimeout(y,ys))}throw Error(`Timed out after ${Rt}ms waiting for detached hub startup.`)}async function xt(e,t={}){let n=Ps();return await wt(n.discoveryPath,async()=>Ls(n,e,t))}function js(){return Ns()==="production"?te():W()}function Fs(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Bt(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return Bt(e.data);return String(e)}function zs(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function It(e){let t=e,n=zs(t.reason);return new k("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Ee,{closeCode:t.code,closeReason:n||void 0})}function Mt(e,t){if(e instanceof k)return e;if(e instanceof Error)return new k("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new k("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new k("hub_connect_failed",n);let s=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new k("hub_connect_failed",s?`Failed to connect to hub at ${t.toString()} (${s} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var Te="*",se=8000,Gs="cline-hub-auth.",qt=new Map,Nt=new Set,Js=3000;var Ee="Hub connection closed",Vs=250,Ks=5000,Ot=0.5;class k extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Qs(e){return e instanceof k}class xe extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function Ie(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let s=Me(e.toString());return s?qt.get(s):void 0}function Ys(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function Me(e){if(!Ys(e))return;let t=new URL($t(e));return t.search="",t.hash="",t.toString()}function Ut(e){let t=Me(e);return!!t&&Nt.has(t)}function ne(e,t){let n=Me(e);if(n){if(Nt.add(n),t?.trim())qt.set(n,t)}return e}class G{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new k("hub_connection_closed",Ee);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||Ie(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,s=this.openSocket(e,t,n),o;this.connectPromise=s.then(async(a)=>{if(o=a,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(q.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{a.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let r of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(r));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(a){if(this.connectPromise===i)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=Mt(a,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw a}}async openSocket(e,t,n){let s=this.options.resolveConnectionHeaders,o;if(s){let d;try{o=await Promise.race([Promise.resolve().then(()=>s()),new Promise((u,f)=>{d=setTimeout(()=>{f(new k("hub_connect_timeout",`Timed out resolving hub connection headers after ${se}ms`))},se)})])}catch(u){let f=u instanceof k?u:new k("hub_connect_failed",u instanceof Error?u.message:String(u));if(n===this.connectGeneration)this.lastCloseError=f;throw f}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new k("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let i=o?new Ws(e.toString(),{headers:{...o}}):new(Fs())(e.toString(),t?[`${Gs}${t}`]:void 0);this.socket=i;let a=!1,r=new Promise((d,u)=>{let f=!1,c=setTimeout(()=>{if(f)return;f=!0,a=!0;let h=new k("hub_connect_timeout",`Timed out connecting to hub after ${se}ms`);if(this.socket===i)this.lastCloseError=h,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}u(h)},se);i.addEventListener("open",()=>{if(f)return;f=!0,clearTimeout(c),d()}),i.addEventListener("error",(h)=>{if(f)return;f=!0,clearTimeout(c);let l=Mt(h,e);if(this.socket===i)this.lastCloseError=l,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;u(l)}),i.addEventListener("close",(h)=>{if(f)return;f=!0,clearTimeout(c);let l=a?this.lastCloseError:It(h);if(this.socket===i){if(!a)this.lastCloseError=l,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}u(l)})});return i.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(Bt(d)))}),i.addEventListener("close",(d)=>{if(this.socket!==i)return;if(!a)this.lastCloseError=It(d),this.sawSocketClose=!0;this.registered=!1;for(let u of this.pendingReplies.values())u.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await r,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,s={listener:e,sessionId:n};return this.listeners.add(s),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(s))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,s){let o=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,s)}catch(a){if(!i||o>=1||!await this.recoverLocalHubTransport(a))throw a;o+=1}}async commandOnce(e,t,n,s,o=!0){if(o)await this.connect();s?.beforeDispatch?.();let i=Bs("hubreq_");s?.onDispatch?.(i);let a=$s(e,s?.timeoutMs),r=new Promise((u,f)=>{let c=a===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;f(new xe(e,"hub_command_timeout",`Hub command ${e} timed out after ${a}ms (hub=${this.currentUrl}, requestId=${i}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},a);this.pendingReplies.set(i,{resolve:(h)=>{if(c)clearTimeout(c);u(h)},reject:(h)=>{if(c)clearTimeout(c);f(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:a,payload:t}})}catch(u){throw this.pendingReplies.delete(i),u}let d=await r;if(!d.ok){if(d.error?.code===it){let u=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Y(u,d.error.message)}throw new xe(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Ut(this.currentUrl)||!Qs(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Dt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let e=Math.min(Vs*2**this.reconnectAttempt,Ks),t=Math.round(e*(1-Ot)+Math.random()*e*Ot);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Ut(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Dt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new k("hub_connection_closed",Ee);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new k("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),s=(this.subscriptionCounts.get(n)??0)+t;if(s<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,s),t>0&&s===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??Te}subscriptionSessionIdFromKey(e){return e===Te?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let s of[Te,n]){if(!s||!this.subscriptionCounts.has(s))continue;let o=this.lastEventSequenceByKey.get(s)??0;if(t>o)this.lastEventSequenceByKey.set(s,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function $t(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function x(e,t){let n=new G({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function He(e,t){let n=$t(e),s=await ee(n,{authToken:t?.authToken});if(!s)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=U(),i=X(s,o);if(!i.compatible&&!Z(s))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!qs(s).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await x(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function Xs(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,s=new Set;for(let o of t){if(!o||typeof o!=="object")continue;let i=o.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let a of i){let r=a&&typeof a==="object"?a.clientId:void 0;if(typeof r==="string"&&r.trim())s.add(r)}}return{activeSessionCount:n,participantClientCount:s.size}}async function Ae(e,t,n){let s=new G({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await s.command("session.list",{limit:500},void 0,{timeoutMs:Js});return Xs(o.payload)}finally{await s.dispose().catch(()=>{return})}}async function Zs(e,t,n){try{return(await Ae(e,t,n)).activeSessionCount===0}catch{return!1}}async function eo(e,t){let n=`${e.discoveryPath}.superseded`,s=await I(n);if(!s?.url||!s.authToken)return;let o=await He(s.url,{authToken:s.authToken});if(o.status!=="compatible")return;if(await Zs(o.url,s.authToken,t))return;return ne(o.url,s.authToken)}async function to(e={}){if(e.endpoint?.trim()){let o=await He(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=js(),n=await I(t.discoveryPath);if(!n?.url)return await eo(t,e);let s=await He(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(s.status==="compatible")return ne(s.url,n.authToken);if(s.status==="protocol_mismatch")await D(t.discoveryPath).catch(()=>{return});return}async function Dt(e={}){let t=await to(e);if(t&&await x(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await xt(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function z(e,t,n,s){Lt();let o=new URL(e),i=t?.trim()||Ie(o);if(o.protocol==="ws:")o.protocol="http:";else if(o.protocol==="wss:")o.protocol="https:";if(o.pathname="/drain",o.hash="",n)o.searchParams.set("reason",n);if(s?.off)o.searchParams.set("off","1");return(await fetch(o,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function Ht(e,t){Lt();let n=new URL(e),s=t?.trim()||Ie(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:s?{authorization:`Bearer ${s}`}:void 0})).ok}function no(e,t){if(!e||typeof e!=="object")return;let n=e,s=typeof n.id==="string"?n.id.trim():"";if(!s)return;let o=typeof n.display_name==="string"?n.display_name.trim():typeof n.displayName==="string"?n.displayName.trim():"",i=typeof n.name==="string"?n.name.trim():"";return{id:s,name:o||i||s,catalogId:t}}function Oe(e,t){return Array.isArray(e)?e.flatMap((n)=>{let s=no(n,t);return s?[s]:[]}):[]}async function Wt(e,t={}){let n=e.trim(),s=n.length;while(s>0&&n[s-1]==="/")s--;let o=n.slice(0,s),i=async(m)=>{let y=await(t.fetchImpl??fetch)(`${o}${m}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!y.ok)throw Error(`HTTP ${y.status}`);return await y.json()},a,r;try{[a,r]=await Promise.all([i("/api/v1/ai/cline/models"),i("/api/v1/ai/cline/recommended-models")])}catch(m){throw Error("Could not load the cloud model catalog.",{cause:m})}let d=a&&typeof a==="object"?a:void 0,u=Oe(Array.isArray(a)?a:d?.data,"cline"),f=r&&typeof r==="object"?r:void 0,c=f?.data&&typeof f.data==="object"?f.data:f,h=Oe(c?.clinePass,"cline-pass"),l=Oe(c?.clineCloud,"cline-cloud"),p=new Set;return[...t.isOrganizationSession?[]:h,...l,...u].filter((m)=>{if(p.has(m.id))return!1;return p.add(m.id),!0})}import{formatDisplayUserInput as jt}from"@cline/shared";var so=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function oo(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function io(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function ro(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function ao(e){if(typeof e.content==="string")return{hasAttachment:!1,text:e.content};if(!Array.isArray(e.content))return{hasAttachment:!1,text:"unknown"};let t=!1,n=!1,s=[];for(let o of e.content){if(!o||typeof o!=="object"||Array.isArray(o))continue;let i=o;if(i.type==="text"&&typeof i.text==="string")s.push(i.text);else if(i.type==="tool_result"||i.type==="tool-result")n=!0;else if(i.type==="file"||i.type==="image")t=!0}return{hasAttachment:t&&!n,text:s.join(`
|
|
11
|
-
`)}}function
|
|
12
|
-
${Be(s.content)}`:
|
|
13
|
-
`)}if(e&&typeof e==="object"){let t=e;if(typeof t.text==="string")return t.text}return""}function
|
|
14
|
-
`)[0]?.trim().slice(0,70)||void 0}function
|
|
15
|
-
`)[0]?.trim().slice(0,70)||void 0}return}function qe(e){let t=e.metadata&&typeof e.metadata==="object"?ce(e.metadata.title):void 0;if(t)return t.slice(0,70);let n=ho(e.prompt);if(n)return n;let s=e.messages?mo(e.messages):void 0;if(s)return s;return`Session ${e.sessionId.slice(-6)}`}function Qt(e,t,n,s){let o=t.payload??{},i=()=>{let r=n.get(s);if(r===void 0||!e.messages[r]||e.messages[r]?.role!=="assistant")r=e.messages.length,e.messages.push({role:"assistant",content:[]}),n.set(s,r);let d=e.messages[r];if(!Array.isArray(d.content))d.content=[];return d.content},a=(r,d,u)=>{let f=i(),c=f.at(-1);if(c?.type===r)c[d]=`${c[d]??""}${u}`;else f.push({type:r,[d]:u})};switch(t.event){case"assistant.delta":if(typeof o.text==="string")a("text","text",o.text);return;case"reasoning.delta":if(typeof o.text==="string"&&o.text)a("thinking","thinking",o.text);else if(o.redacted===!0)i().push({type:"redacted_thinking",data:""});return;case"assistant.finished":n.delete(s);return;case"assistant.media":if(o.media)i().push({type:"media",media:structuredClone(o.media)});return;case"tool.started":{let r=String(o.toolCallId??"");if(r&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((u)=>u.type==="tool_use"&&u.id===r)))i().push({type:"tool_use",id:r,name:String(o.toolName??"tool"),input:structuredClone(o.input??{})});return}case"tool.finished":{let r=String(o.toolCallId??"");if(r&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((u)=>u.type==="tool_result"&&u.tool_use_id===r)))e.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:r,content:typeof o.output==="string"?o.output:JSON.stringify(o.output??""),is_error:Boolean(o.error)}]}),n.delete(s);return}case"usage.updated":e.usage=structuredClone(o.totals??o.delta??{});return;case"session.pending_prompts":{let r=Array.isArray(o.prompts)?o.prompts:[];e.promptsInQueue=r.map((d)=>({id:String(d.id??""),prompt:String(d.prompt??""),steer:d.delivery==="steer",attachmentCount:typeof d.attachmentCount==="number"?d.attachmentCount:0,userImages:Array.isArray(d.userImages)?d.userImages.filter((u)=>typeof u==="string"):void 0})).filter((d)=>d.id&&(d.prompt||d.attachmentCount));return}case"session.pending_prompt_submitted":{let r=o.prompt,d=String(r?.id??"");if(!d||e.lastQueuedPromptStartId===d)return;if(e.lastQueuedPromptStartId=d,e.promptsInQueue=e.promptsInQueue.filter((u)=>u.id!==d),o.transcriptReflected!==!0)e.messages.push({role:"user",content:[{type:"text",text:String(r?.prompt??"")}]});e.busy=!0,e.status="running",e.endedAt=void 0,n.delete(s);return}case"run.started":case"session.attached":case"session.updated":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;let r=o.session,d=typeof r?.status==="string"?r.status:t.event==="run.started"?"running":e.status,u=d==="pending"?"running":d;if(t.event==="session.updated"&&u==="running"&&e.endedAt!==void 0&&!e.busy)return;let f=e.busy;if(e.status=u,e.busy=u==="running",t.event==="run.started"){if(!f)n.delete(s);e.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;e.status=typeof o.reason==="string"?o.reason:t.event==="run.failed"?"error":t.event==="run.aborted"?"aborted":"completed",e.busy=!1,e.endedAt=Date.now(),n.delete(s);return}}}function Ne(e){return e instanceof Error&&e.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String(e.code))}function $e(e,t){return e instanceof Error&&e.name==="HubCommandError"&&e.code==="hub_command_timeout"&&(!t||e.command===t)}var C="/workspace",yo=30000,bo=2000,wo=2000,Yt="IMPORTANT: GitHub authentication is handled automatically by the infrastructure. An egress proxy transparently injects credentials into all GitHub traffic. You do NOT need to set up, configure, or manage any tokens, API keys, or credentials, and you must never run `gh auth login` or attempt to authenticate manually. "+"The GitHub CLI (`gh`) is installed and already authenticated — prefer it for GitHub work "+"(`gh pr create`, `gh pr diff`, `gh issue list`, `gh api`, ...). `git` push and pull are authenticated the same way. "+"Simply run the commands normally — credentials are injected transparently.";function We(e){if(!e)return C;if(ue.isAbsolute(e)||e.includes("\\")||e.split("/").some((n)=>!n||n==="."||n===".."))throw new g("request_failed","The handoff workspace path must stay inside the repository.");let t=ue.join(C,e);if(!t.startsWith(`${C}/`))throw new g("request_failed","The handoff workspace path must stay inside the repository.");return t}function Je(e){let t=e.metadata.cwd;return typeof t==="string"&&ue.normalize(t)===t&&(t===C||t.startsWith(`${C}/`))?t:C}function Xt(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0,n=t?.handoff&&typeof t.handoff==="object"?t.handoff:void 0;return String(n?.sourceSessionId??"").trim()}class ze extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud conversation creation was not dispatched.",{cause:e});this.name="CloudHandoffSeedRejectedError"}}class Ge extends g{constructor(){super("request_failed","The connection was interrupted and Cline could not confirm whether this message was queued. Check the cloud session before resending it.");this.name="CloudQueueUnconfirmedError"}}class en extends Error{constructor(){super("The cloud session was created, but its transcript was not persisted. This cloud runtime cannot durably seed handoff transcripts and must use @cline/core 0.0.72 or newer. Updating the cloud runtime or pod is required; retrying /cloud against this same pod will not help.");this.name="CloudHandoffSeedUnsupportedError"}}function T(e){let t=e.expiredAt?Date.parse(e.expiredAt):Number.NaN;return Number.isFinite(t)&&t<=Date.now()}function vo(e){return e.trim().startsWith("ses-")}function Co(e,t){let n=new URL(`/api/v1/session/${encodeURIComponent(t)}`,e);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.toString()}function je(e){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:e.metadata.modelId??"",modelId:e.metadata.modelId??"",repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",cwd:Je(e),workspaceRoot:C},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse(e.createdAt)||Date.now(),endedAt:T(e)&&e.expiredAt?Date.parse(e.expiredAt):void 0,status:e.status,attachedViaHub:!0}}function Fe(e,t,n){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:t,provider:"cline",model:e.metadata.modelId??"",repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",cwd:Je(e),workspaceRoot:C,...n?.trim()?{prompt:n.trim()}:{},metadata:{origin:"cloud",repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function Zt(e){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:e.status,provider:"cline",model:e.metadata.modelId??"",cwd:Je(e),workspaceRoot:C,repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",startedAt:e.createdAt,...e.lastActivityAt?{lastActivityAt:e.lastActivityAt}:{},endedAt:T(e)?e.expiredAt??void 0:e.status==="failed"?e.lastActivityAt??e.createdAt:void 0,updatedAt:e.updatedAt,...e.title?.trim()?{title:e.title.trim()}:{},metadata:{...e.title?.trim()?{title:e.title.trim()}:{},origin:"cloud",...e.metadata.provisioningPhase?{provisioningPhase:e.metadata.provisioningPhase}:{},repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function So(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function ko(e,t){let n=[...e??[]],s=new Set(n.map((o)=>o.id));for(let o of t)if(!s.has(o.id))n.push(o);return n}class Ro{options;sessionGenerations=new Map;sessions=new Map;approvals=new Map;listeners=new Set;detachedSessions=new Set;restoredOptions=new Map;authoritativeMessages=new Map;streamingMessages=new Map;disposed=!1;connections=new Map;connectionPromises=new Map;knownSessions=new Map;unlistedSessions=new Map;pendingInitialTasks;lastListedSessions=[];discoveryRefresh;unconfirmedInnerCreates=new Set;createRequests=new Map;provisioningControllers=new Map;sendAbortTokens=new Map;titleWrites=new Map;deletingSessions=new Set;createHubClient;constructor(e){this.options=e;this.pendingInitialTasks=e.pendingInitialTasks??new Map,this.createHubClient=e.createHubClient??((t)=>new G(t))}restoreCreationOptions(e,t){if(this.restoredOptions.set(e,structuredClone(t)),this.pendingInitialTasks.has(e))this.pendingInitialTasks.set(e,{...this.pendingInitialTasks.get(e),...structuredClone(t)});let n=this.sessions.get(e);if(n)Object.assign(n.config,structuredClone(t))}seedSessionState(e,t){if(!this.sessions.has(e))this.sessions.set(e,structuredClone(t))}stateFromRecord(e){let t=je(e);return Object.assign(t.config,this.pendingInitialTasks.get(e.id),this.restoredOptions.get(e.id)),t}getSnapshot(e){let t=this.knownSessions.get(e),n=this.sessions.get(e)??(t?this.stateFromRecord(t):void 0);if(!n)return;let s=this.connections.get(e);return de({...n,sessionId:e,record:t,approvals:Array.from(this.approvals.values()).filter((o)=>o.item.sessionId===e).map((o)=>o.item),connectionState:this.detachedSessions.has(e)||this.disposed?"detached":s?.reconnectResolution||s?.rehydrationPromise?"reconnecting":s?s.connected?"connected":s.reconnecting?"reconnecting":"connecting":this.connectionPromises.has(e)?"connecting":"detached",transcriptKnown:s?.transcriptKnown??Boolean(t&&T(t))})}subscribe(e,t){let n=(s)=>{if(!t||s.sessionId===t)e(s)};return this.listeners.add(n),()=>{this.listeners.delete(n)}}publish(e){let t=e.type==="snapshot"?Object.freeze(e):de(e);for(let n of this.listeners)try{n(t)}catch(s){this.options.logger?.error?.("Cloud session subscriber failed",{error:s})}}publishSnapshot(e,t=!1,n){this.cancelScheduledSnapshot(e);let s=this.getSnapshot(e);if(s)this.publish({type:"snapshot",sessionId:e,snapshot:s,replace:t,cause:n});else this.publish({type:"removed",sessionId:e})}snapshotTimers=new Map;cancelScheduledSnapshot(e){clearTimeout(this.snapshotTimers.get(e)),this.snapshotTimers.delete(e)}scheduleSnapshot(e){if(this.disposed||this.detachedSessions.has(e)||this.snapshotTimers.has(e))return;let t=setTimeout(()=>this.publishSnapshot(e),100);t.unref?.(),this.snapshotTimers.set(e,t)}notify(e,t){let n=String(t.sessionId??"");if(e==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:n,message:String(t.message??"Cloud synchronization failed")});else this.publishSnapshot(n,e==="cloud_session_rehydrated",e==="chat_session_status"?"status":e==="chat_session_ended"?"ended":e==="tool_approval_state"?"approvals":void 0)}applyLiveEvent(e,t){let n=this.sessions.get(e);if(n)Qt(n,t,this.streamingMessages,e)}async respondApproval(e,t,n){this.assertSessionActive(e);let s=this.approvals.get(`${e}:${t}`);if(!s){if(!this.connections.has(e))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new g("request_failed","This approval was already resolved or is no longer available.")}await s.resolve(n)}async detach(e){this.detachedSessions.add(e),this.sessionGenerations.set(e,(this.sessionGenerations.get(e)??0)+1),this.connectionPromises.delete(e),this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud viewer detached")),await this.disposeConnection(e),this.publishSnapshot(e)}isCloudSession(e){return vo(e)||this.knownSessions.has(e)||this.connections.has(e)||this.sessions.get(e)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord(e){let t=this.knownSessions.get(e);return t?Zt(t):void 0}async getCrossScopeDiscoveryRecord(e){let t=this.getCachedDiscoveryRecord(e);if(!t)return;try{let s=(await this.options.api.status(e)).status?.trim();return s?{...t,status:s}:t}catch(n){if(n instanceof g&&(n.code==="session_not_found"||n.code==="session_expired")){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e);return}return t}}async list(){if(this.disposed)throw Error("Cloud session controller was disposed");let e=await this.resolveActiveOrganizationId(),t=(await this.options.api.list(e)).map((s)=>this.preserveConnectedRuntimeModel(s));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=t;for(let s of t)this.knownSessions.set(s.id,s),this.unlistedSessions.delete(s.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(s)=>this.getCrossScopeDiscoveryRecord(s)));let n=await Promise.all(t.map(async(s)=>{if(s.status!=="provisioning")return s;let o=await this.options.api.status(s.id).catch(()=>{return}),i=o?.status?.trim();if(!i)return s;return{...s,status:i,metadata:{...s.metadata,...be(o?.phase)?{provisioningPhase:o?.phase}:{},...o?.statusReason?.trim()?{statusReason:o.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let s of n){this.knownSessions.set(s.id,s);let o=this.sessions.get(s.id);if(o?.status==="provisioning"&&s.status!=="provisioning")o.status=s.status;let i=this.connections.get(s.id);if(i)i.remote=s;let a=T(s);if(a||s.status==="failed"||s.status==="suspended"){if(o)o.busy=!1,o.status=a?"expired":s.status,o.endedAt=a?Date.parse(s.expiredAt??"")||Date.now():Math.max(o.endedAt??0,Date.parse(s.lastActivityAt??s.createdAt)||0)||void 0;if(i)this.disposeConnection(s.id).catch(()=>{return})}}this.lastListedSessions=n;for(let s of n)if(this.sessions.has(s.id))this.publishSnapshot(s.id);return de(n)}async handoffTargetExists(e){try{return await this.options.api.status(e),!0}catch(t){if(t instanceof g&&(t.code==="session_not_found"||t.code==="session_expired"))return!1;throw t}}preserveConnectedRuntimeModel(e){let t=this.connections.get(e.id)?.remote.metadata,n=t?.cwd??this.knownSessions.get(e.id)?.metadata.cwd;return{...e,metadata:{...e.metadata,...t?.modelId?{modelId:t.modelId}:{},...n?{cwd:n}:{}}}}async resolveActiveOrganizationId(e){return await this.options.getActiveOrganizationId?.(e)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listModels(){if(this.disposed)throw Error("Cloud session manager was disposed");let e=await this.resolveActiveOrganizationId({fresh:!0}),t=await Wt(this.options.apiBaseUrl,{isOrganizationSession:Boolean(e)});if(this.disposed)throw Error("Cloud session manager was disposed");return t}async prepareHandoffRepository(e){let t=await this.resolveActiveOrganizationId(),n=await this.options.api.listRepositories(t);if(!n.connected)throw new g("github_not_connected","Connect GitHub before handing this session off to cloud.",n.connectUrl);let s=(o)=>o.trim().replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();if(!n.repositories.some((o)=>s(o.url)===s(e)))throw new g("github_not_connected",`The GitHub integration cannot access ${e}. Grant repository access before handing off.`,n.connectUrl);return t?{organizationId:t}:{}}async listBranches(e,t={}){return await this.options.api.listBranches(e,await this.resolveActiveOrganizationId(),t)}async listForDiscovery(e={}){let t=this.discoveryRefresh??this.list().finally(()=>{if(this.discoveryRefresh===t)this.discoveryRefresh=void 0});this.discoveryRefresh=t;let n=this.lastListedSessions;if(e.timeoutMs===void 0)n=await t;else{let i,a=await Promise.race([t.then((r)=>({value:r}),(r)=>{if(!(r instanceof g&&r.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:r});return{value:this.lastListedSessions}}),new Promise((r)=>{i=setTimeout(()=>r({value:this.lastListedSessions}),Math.max(0,e.timeoutMs??0))})]);if(i)clearTimeout(i);n=a.value}return[...new Map([...this.unlistedSessions.values(),...n].map((i)=>[i.id,i])).values()].map((i)=>{let a=Zt(i),r=this.sessions.get(i.id);if(!r)return a;let d=r.title?.trim()||i.title?.trim();return{...a,status:r.status,prompt:r.prompt,endedAt:r.endedAt!==void 0?new Date(r.endedAt).toISOString():a.endedAt,metadata:{...a.metadata??{},title:qe({sessionId:i.id,metadata:d?{title:d}:void 0,prompt:r.prompt,messages:r.messages})}}})}async create(e){let t=e.requestId?.trim();if(!t)return await this.createOnce(e);let n=this.createRequests.get(t);if(n)return await n;let s=this.createOnce(e).finally(()=>{if(this.createRequests.get(t)===s)this.createRequests.delete(t)});return this.createRequests.set(t,s),await s}trackProvisioningController(e,t){let n=this.provisioningControllers.get(e);if(!n)n=new Set,this.provisioningControllers.set(e,n);return n.add(t),()=>{if(n.delete(t),n.size===0)this.provisioningControllers.delete(e)}}abortProvisioningControllers(e,t){let n=this.provisioningControllers.get(e);if(!n?.size)return!1;for(let s of n)s.abort(t);return!0}async waitUntilReady(e){this.detachedSessions.delete(e),this.assertSessionActive(e);let t=new AbortController,n=this.trackProvisioningController(e,t);try{await this.options.api.waitUntilReady(e,AbortSignal.any([t.signal,AbortSignal.timeout(610000)])),t.signal.throwIfAborted(),this.assertSessionActive(e),await this.refreshKnownSession(e)}finally{n()}}async seedHandoff(e,t){We(t.workspaceRelativePath),this.detachedSessions.delete(e);let n=await this.ensureConnection(e,{createInner:!0,handoffSeed:t});if(!n.innerSessionId)throw Error("Cloud Hub did not return an inner session id");return{innerSessionId:n.innerSessionId}}async verifyHandoffTranscript(e,t,n={}){let s=await this.ensureConnection(e),o=s.innerSessionId;if(!o)throw Error("Cloud Hub did not return an inner session id");let i=await s.client.command("session.messages",{sessionId:o},o);this.assertSessionActive(e,s);let a=i.payload?.messages;if(!Array.isArray(a))throw Error("Cloud runtime returned no transcript after seeding.");if(t.length>0&&a.length===0)throw new en;if(!(n.allowAppendedMessages?a.length>=t.length&&fe(t,a.slice(0,t.length)):fe(t,a)))throw new he(t.length,a.length);s.transcriptKnown=!0;let d=this.sessions.get(e);if(d)d.messages=structuredClone(a),this.authoritativeMessages.set(e,structuredClone(a)),this.streamingMessages.delete(e),this.publishSnapshot(e,!0)}async createOnce(e){if(this.disposed)throw Error("Cloud session manager was disposed");let t=We(e.workspaceRelativePath),n=e.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):e.organizationId??void 0,s=e.handoff,o=!s,i=await this.options.api.create({...e,organizationId:n,...s&&{handoff:{...s,onOuterSessionCreated:async(h,l)=>{o=l?.created===!0,await s.onOuterSessionCreated(h,l)}}}});if(!i?.sessionId?.trim())throw new g("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(o&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(i.sessionId,i.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let a={id:i.sessionId,sandboxType:e.sandboxType,status:i.status,sandboxUrl:i.sandboxUrl,repoContext:{repoUrl:e.repoUrl,...e.branch?.trim()?{branch:e.branch.trim()}:{}},metadata:{modelId:e.modelId,cwd:t},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.knownSessions.set(a.id,a),this.unlistedSessions.set(a.id,a);let{autoApproveTools:r,thinking:d,reasoningEffort:u}=e;this.pendingInitialTasks.set(a.id,{autoApproveTools:r,thinking:d,reasoningEffort:u});let f=this.stateFromRecord(a);f.prompt=e.initialPrompt?.trim()||void 0,f.config.mode=e.mode??"act",this.sessions.set(a.id,f);let c;try{if(e.handoff){let h=await e.handoff.resolveMessages();this.assertSessionActive(a.id),c=(await this.seedHandoff(a.id,{sourceSessionId:e.handoff.sourceSessionId,messages:h,mode:e.mode,workspaceRelativePath:e.workspaceRelativePath,config:{autoApproveTools:e.autoApproveTools,thinking:e.thinking,reasoningEffort:e.reasoningEffort},onSeeding:e.handoff.onSeeding})).innerSessionId}}catch(h){if(this.disposed&&o&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(a.id,i.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw h}return this.assertSessionActive(a.id),this.notify("chat_session_status",{sessionId:a.id,status:f.status}),{sessionId:a.id,origin:"cloud",executionTarget:"cloud",status:a.status,provider:"cline",model:e.modelId,repoUrl:e.repoUrl,branch:e.branch??"",cwd:t,workspaceRoot:C,...c?{innerSessionId:c}:{},...f.prompt?{prompt:f.prompt}:{}}}async deleteProvisionedSessionAfterDispose(e,t,n){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),await this.options.api.delete(e,t).then(()=>n?.(e)).catch((s)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:e,error:s})})}async attach(e,t){let n=this.sessionGenerations.get(e)??0;if(this.detachedSessions.delete(e),t)this.restoreCreationOptions(e,t);let s=await this.ensureKnownSession(e);if(this.assertSessionActive(e),n!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has(e))this.sessions.set(e,this.stateFromRecord(s));if(s.status==="provisioning"||s.status==="failed")return Fe(s,s.status,this.sessions.get(e)?.prompt);if(T(s))return await this.disposeConnection(e),await this.attachExpired(s);let o;try{o=await this.ensureConnection(e)}catch(r){let d=await this.refreshKnownSession(e);if(d&&T(d))return await this.disposeConnection(e),await this.attachExpired(d);throw r}await this.ensureAttached(o);let i=o.remote,a=this.sessions.get(e);return Fe(i,a?.status??i.status,a?.prompt)}async send(e,t,n,s,o){let i=this.sendAbortTokens.get(e),a=this.knownSessions.get(e);if(a&&T(a))throw new g("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let r=await this.ensureConnection(e,{createInner:!0}),d=()=>this.disposed||r.disposed||this.deletingSessions.has(e)||this.sendAbortTokens.get(e)!==i,u=()=>{if(d())throw Error("Cloud session prompt cancelled")};if(u(),await r.reconnectResolution,u(),await this.ensureAttached(r),await r.reconnectResolution,u(),!r.transcriptKnown)await this.rehydrateAfterTransportDrop(e,r);u(),await this.updateModel(r,s),await r.reconnectResolution,u();let f=r.innerSessionId;if(!f)throw Error("Cloud Hub session was not initialized");let c=this.sessions.get(e),h=n??(c?.busy?"queue":void 0),l=J(c?.messages??[],c?.promptsInQueue??[],t),p=h!=="queue"&&h!=="steer",m=c&&h!=="queue"?{role:"user",content:[{type:"text",text:t}]}:void 0;if(c&&m)c.messages=[...c.messages,m];let y=()=>{if(c&&m)c.messages=c.messages.filter((b)=>b!==m),this.publishSnapshot(e)};if(c&&p){let b=c.status!=="running";if(c.busy=!0,c.status="running",c.prompt||=t,b)this.publishSnapshot(e,!1,"status")}let w=this.knownSessions.get(e);if(w&&!w.title?.trim()&&!this.titleWrites.has(e)){let b=st(t);if(b){if(w.title=b,c)c.title=b;let R=this.options.api.updateTitle?.(e,b).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get(e)===R)this.titleWrites.delete(e)});if(R)this.titleWrites.set(e,R)}}let v=new Set,P=!1,H=()=>{if(P||d())return;P=!0,this.publish({type:"prompt_accepted",sessionId:e,prompt:t,delivery:h})};try{let b=await r.client.command("session.send_input",{prompt:t,delivery:h,...o?.length?{attachments:{userImages:o}}:{}},f,{timeoutMs:h==="queue"?yo:null,onDispatch:(M)=>{v.add(M),r.pendingInputs??=new Map,r.pendingInputs.set(M,{clientId:r.client.getClientId(),ownsBusyState:p,accept:H})},beforeDispatch:()=>{if(u(),r.innerSessionId!==f)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.")}});H();let R=h==="queue"||h!=="steer"&&b.payload?.result===void 0;if(R)y();return{sessionId:e,ok:!0,...R?{queued:!0}:{},result:b.payload?.result}}catch(b){if(d())throw y(),b;if(Ne(b)||$e(b,"session.send_input")){let R;try{R=await this.rehydrateAfterTransportDrop(e,r)}catch(V){if(u(),y(),c&&p)c.busy=!1,c.status="error";if(h==="queue")throw new Ge;throw V}if(u(),h==="queue")throw new Ge;if(h==="steer")throw new g("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(J(R.messages,ko(R.prompts,R.submittedPrompts),t)<=l)throw new g("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:e,ok:!0,...h==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:R.status}}if(y(),c&&p)c.busy=!1,c.status="error";throw this.publishSnapshot(e),b}finally{for(let b of v)r.pendingInputs?.delete(b)}}async updateModel(e,t){let n=t?.trim();if(!n||e.remote.metadata.modelId===n)return;let s=e.innerSessionId;if(!s)throw Error("Cloud Hub session was not initialized");await e.client.command("session.update_connection",{sessionId:s,updates:{modelId:n}},s,{beforeDispatch:()=>{if(this.assertSessionActive(e.remote.id,e),e.innerSessionId!==s)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive(e.remote.id,e),this.applyModel(e,n)}applyModel(e,t){e.remote.metadata.modelId=t;let n=this.sessions.get(e.remote.id);if(n)n.config.model=t,n.config.modelId=t}async rehydrateAfterTransportDrop(e,t){if(this.assertSessionActive(e,t),t.rehydrationPromise)return t.rehydrationRerunRequested=!0,await t.rehydrationPromise;let n=(async()=>{let s;do t.rehydrationRerunRequested=!1,s=await this.performTransportRehydration(e,t),this.assertSessionActive(e,t);while(t.rehydrationRerunRequested&&!this.disposed);return s})().finally(()=>{if(t.rehydrationPromise===n)t.rehydrationPromise=void 0,this.publishSnapshot(e)});return t.rehydrationPromise=n,await n}async performTransportRehydration(e,t){this.assertSessionActive(e,t);let n=t.innerSessionId;if(!n)throw Error("Cloud Hub session was not initialized");t.bufferingEvents=!0,t.bufferedEvents=[],t.bufferedEventsDropped=0;try{await this.ensureAttached(t),this.assertSessionActive(e,t);let s=await t.client.command("session.get",{includeSnapshot:!0},n);this.assertSessionActive(e,t);let o=s.payload?.session&&typeof s.payload.session==="object"&&!Array.isArray(s.payload.session)?s.payload.session:void 0;this.applySessionModel(t,o);let i=this.sessions.get(e),a=this.authoritativeMessages.get(e)??[],r=String(o?.status??i?.status??"running").trim(),d=r==="pending"?"running":r;if(d==="running"&&!t.transcriptKnown&&!t.pendingInputs?.size)t.externalRun??={progressHydrated:!0};let u=()=>t.client.command("session.messages",{sessionId:n},n),f=await u().catch((b)=>{if(!$e(b,"session.messages"))throw b;return this.assertSessionActive(e,t),u()});if(this.assertSessionActive(e,t),!Array.isArray(f.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let c=f.payload.messages,h=t.bufferedEventsDropped+t.bufferedEvents.length,l=await t.client.command("session.pending_prompts",{sessionId:n},n).catch(()=>{return});this.assertSessionActive(e,t);let p=t.bufferedEventsDropped+t.bufferedEvents.length;if(i){let b=i.status!==d;if(this.authoritativeMessages.set(e,structuredClone(c)),i.messages=structuredClone(c),this.streamingMessages.delete(e),i.status=d,i.busy=d==="running",b)if(d==="completed"||d==="failed"||d==="aborted")i.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:e,reason:d==="failed"?"error":d});else this.notify("chat_session_status",{sessionId:e,status:d})}let m=l!==void 0&&l.ok!==!1&&Array.isArray(l.payload?.prompts),y=m?this.applyQueueSnapshot(e,l):void 0;t.transcriptKnown=!0;let w=c;this.assertSessionActive(e,t),this.notify("cloud_session_rehydrated",{sessionId:e,status:d,transcriptKnown:!0,messages:w}),this.assertSessionActive(e,t);let v=t.bufferedEvents,P=Le(v),H=Kt(v,c,{queueSnapshotApplied:m,queueSnapshotEventCutoff:Math.max(0,p-t.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,h-t.bufferedEventsDropped),baselineMessages:a});t.bufferedEvents=[],t.bufferingEvents=!1,t.syncFailureNotified=!1;for(let b of H)this.forwardEvent(e,t,b);return{status:d,messages:c,prompts:y,submittedPrompts:P}}catch(s){let o=t.bufferedEvents;t.bufferedEvents=[],t.bufferingEvents=!1,this.assertSessionActive(e,t);for(let i of o)this.forwardEvent(e,t,i);if(!t.syncFailureNotified)t.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:e,message:s instanceof Error?s.message:String(s)});throw s}}async abort(e){if(this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud session prompt cancelled")))return{sessionId:e,ok:!0};let t=await this.ensureConnection(e),n=()=>{if(this.disposed||t.disposed)throw Error("Cloud session connection was disposed")};if(n(),await t.client.connect(),await t.reconnectResolution,n(),await this.resolveInnerSession(e,t),t.innerSessionId){await this.ensureAttached(t),await t.reconnectResolution,n();let o=t.innerSessionId;if(!o)throw Error("Cloud Hub session was not initialized");await t.client.command("run.abort",{sessionId:o},o,{beforeDispatch:()=>{if(n(),t.innerSessionId!==o)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}n();let s=this.sessions.get(e);if(s)s.busy=!1,s.status="aborted";return this.publishSnapshot(e),{sessionId:e,ok:!0}}async pendingPrompts(e){if(this.knownSessions.get(e)?.status==="provisioning")return{sessionId:e,promptsInQueue:[]};if(!(await this.ensureConnection(e)).innerSessionId)return{sessionId:e,promptsInQueue:[]};let n=await this.queueCommand(e,"session.pending_prompts",{});return{sessionId:e,promptsInQueue:this.applyQueueSnapshot(e,n)}}async updatePendingPrompt(e,t,n){let s=await this.queueCommand(e,"session.update_pending_prompt",{promptId:t,...n});return{sessionId:e,updated:s.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot(e,s)}}async removePendingPrompt(e,t){let n=await this.queueCommand(e,"session.remove_pending_prompt",{promptId:t});return{sessionId:e,removed:n.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot(e,n)}}async queueCommand(e,t,n){let s=await this.ensureConnection(e),o=s.innerSessionId;if(!o)throw Error("Cloud Hub session was not initialized");await s.client.connect(),await s.reconnectResolution,await this.ensureAttached(s),await s.reconnectResolution;let i=await s.client.command(t,{sessionId:o,...n},o,{beforeDispatch:()=>{if(this.assertSessionActive(e,s),s.innerSessionId!==o)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive(e,s),i}applyQueueSnapshot(e,t){if(!Array.isArray(t.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let s=t.payload.prompts.map((i)=>({id:typeof i.id==="string"?i.id:"",prompt:typeof i.prompt==="string"?i.prompt:"",steer:i.delivery==="steer",attachmentCount:typeof i.attachmentCount==="number"?i.attachmentCount:0,userImages:Array.isArray(i.userImages)?i.userImages.filter((a)=>typeof a==="string"):void 0})).filter((i)=>i.id),o=this.sessions.get(e);if(o)o.promptsInQueue=s;return this.publishSnapshot(e,!1,"queue"),s}async readMessages(e){let t=this.knownSessions.get(e);if(t?.status==="provisioning"||t?.status==="failed")return[];if(t&&T(t))return await this.loadArchivedMessages(t)??[];try{let n=await this.ensureConnection(e);if(!n.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop(e,n)).messages}catch(n){let s=await this.refreshKnownSession(e)??t;if(s){let o=await this.loadArchivedMessages(s).catch(()=>null);if(o!==null)return o}throw n}}async updateTitle(e,t){let n=this.titleWrites.get(e),s=(async()=>{await n?.catch(()=>{}),this.assertSessionActive(e),await this.options.api.updateTitle(e,t);let o=this.knownSessions.get(e);if(o)o.title=t;let i=this.sessions.get(e);if(i)i.title=t;this.publishSnapshot(e)})();this.titleWrites.set(e,s);try{await s}finally{if(this.titleWrites.get(e)===s)this.titleWrites.delete(e)}}async delete(e){this.deletingSessions.add(e),this.abortProvisioningControllers(e);try{let t=this.connectionPromises.get(e);if(t)await t.catch(()=>{return});await this.disposeConnection(e);try{await this.options.api.delete(e)}catch(n){let s=n instanceof g?n.code:"";if(s!=="session_not_found"&&s!=="session_expired")throw n}this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),this.authoritativeMessages.delete(e),this.restoredOptions.delete(e),this.publish({type:"removed",sessionId:e}),this.sendAbortTokens.delete(e);for(let[n,s]of this.approvals)if(s.item.sessionId===e)this.approvals.delete(n)}finally{this.deletingSessions.delete(e)}}async dispose(){this.disposed=!0;for(let t of this.snapshotTimers.keys())this.cancelScheduledSnapshot(t);this.sendAbortTokens.clear();for(let t of this.provisioningControllers.values())for(let n of t)n.abort();this.provisioningControllers.clear();let e=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[t,n]of this.approvals)if(e.has(n.item.sessionId))this.approvals.delete(t);for(let t of e)this.sessions.delete(t),this.knownSessions.delete(t),this.publish({type:"removed",sessionId:t});if(this.knownSessions.clear(),this.unlistedSessions.clear(),!this.options.pendingInitialTasks)this.pendingInitialTasks.clear();this.listeners.clear(),await Promise.allSettled(Array.from(this.connections.keys()).map((t)=>this.disposeConnection(t)))}async attachExpired(e){let t=this.sessions.get(e.id)??je(e);return t.busy=!1,t.status="expired",this.sessions.set(e.id,t),await this.loadArchivedMessages(e).catch(()=>{return}),Fe(e,"expired")}async loadArchivedMessages(e){let t=this.sessionGenerations.get(e.id),n=await this.options.api.history(e.id);if(this.assertSessionActive(e.id),this.sessionGenerations.get(e.id)!==t)throw Error("Cloud session attachment changed while loading history");if(n===null)return null;let s=this.sessions.get(e.id)??je(e);return s.messages=structuredClone(n),this.sessions.set(e.id,s),this.authoritativeMessages.set(e.id,structuredClone(s.messages)),this.publishSnapshot(e.id,!0),n}async refreshKnownSession(e){let t=await this.resolveActiveOrganizationId(),n=await this.options.api.list(t).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!n)return this.knownSessions.get(e);for(let s of n)this.knownSessions.set(s.id,s);return n.find((s)=>s.id===e)}async ensureKnownSession(e){let t=this.knownSessions.get(e);if(t)return t;let n=(await this.list()).find((s)=>s.id===e);if(!n)throw new g("session_not_found",`Cloud session ${e} was not found.`);return this.knownSessions.get(e)??structuredClone(n)}assertSessionActive(e,t){if(this.disposed||t?.disposed||this.detachedSessions.has(e)||t?.generation!==void 0&&t.generation!==(this.sessionGenerations.get(e)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has(e))throw new g("session_not_found","This cloud session is being deleted.")}async ensureConnection(e,t={}){let n=this.sessionGenerations.get(e)??0,s=()=>{if(this.assertSessionActive(e),n!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during connection")};s();let o=this.connectionPromises.get(e),i=o?await o:this.connections.get(e);if(i?.remote.status==="suspended")return await this.disposeConnection(e),s(),await this.ensureConnection(e,t);if(i){if(this.assertSessionActive(e,i),await i.reconnectResolution,this.assertSessionActive(e,i),!i.innerSessionId)await i.client.connect(),await i.reconnectResolution,this.assertSessionActive(e,i),await this.resolveInnerSession(e,i,Boolean(t.handoffSeed)),this.assertSessionActive(e,i);if(t.handoffSeed&&i.innerSessionId)await this.assertHandoffConnectionReusable(i,t.handoffSeed);if(t.createInner&&!i.innerSessionId)await this.createInnerSession(i,t.handoffSeed);return this.assertSessionActive(e,i),i}let a=(async()=>{let r=await this.ensureKnownSession(e);if(s(),!this.pendingInitialTasks.has(e)&&(r.sandboxType==="resumable"||r.metadata.sandboxType==="resumable"||r.status==="suspended")){let c=await this.options.api.status(e).catch(async(l)=>{if(!(l instanceof g?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 s(),await this.refreshKnownSession(e).catch(()=>{return})});if(s(),c?.status)r.status=c.status;let h=this.sessions.get(e);if(h?.status==="suspended"&&["provisioning","ready","active"].includes(r.status))h.status=r.status,h.busy=!1,h.endedAt=void 0}if(r.status==="suspended"){let c=new AbortController,h=this.trackProvisioningController(e,c);try{try{r=await this.options.api.resume(e,c.signal)}catch(p){if(!(p instanceof g)||p.status!==409)throw p;s(),c.signal.throwIfAborted();let m=await this.options.api.status(e,{signal:c.signal});if(m.status!=="provisioning"&&m.status!=="ready"&&m.status!=="active")throw p;r={...r,status:m.status}}s(),c.signal.throwIfAborted(),this.knownSessions.set(e,r);let l=this.sessions.get(e);if(l)l.status=r.status,l.busy=!1,l.endedAt=void 0;this.publishSnapshot(e,!1,"status")}finally{h()}}if(r.status==="provisioning"){let c=new AbortController,h=this.trackProvisioningController(e,c);try{if(await this.options.api.waitUntilReady(e,c.signal,({phase:p})=>{r.metadata.provisioningPhase=p,this.notify("chat_session_status",{sessionId:e,status:"provisioning",phase:p})}),this.disposed)throw Error("Cloud session manager was disposed");if(r=await this.refreshKnownSession(e)??r,c.signal.throwIfAborted(),r.status==="provisioning")r.status="ready";let l=this.sessions.get(e);if(l?.status==="provisioning")l.status="idle",l.busy=!1,l.endedAt=void 0}catch(l){if(l instanceof g&&l.code==="session_failed"){if(r.status="failed",r.metadata.statusReason=l.detail,r.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set(e,r);let p=this.sessions.get(e);if(p)p.status="error";this.notify("chat_session_status",{sessionId:e,status:"error"})}throw l}finally{h()}}if(s(),r.status==="failed")throw new g("session_failed",r.metadata.statusReason||"The cloud sandbox could not be prepared.");if(T(r))throw new g("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set(e,this.sessions.get(e)??this.stateFromRecord(r));let d,u=0,f=this.createHubClient({url:Co(this.options.apiBaseUrl,e),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${e}-${go()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:C,cwd:C,resolveConnectionHeaders:async()=>{s();let c=u>0;if(u+=1,d)d.connected=!1,d.reconnecting=c,this.publishSnapshot(e);if(c){let l=d;if(l&&!l.disposed){l.transcriptKnown=!1,l.innerSessionId=void 0;let p=(async()=>{if(await this.resolveInnerSession(e,l),l.innerSessionId)await this.rehydrateAfterTransportDrop(e,l)})().catch(()=>this.disposeConnectionIfSessionGone(e,l)).finally(()=>{if(l.reconnectResolution===p)l.reconnectResolution=void 0,l.connected=l.transcriptKnown,this.publishSnapshot(e)});l.reconnectResolution=p}}let h=await this.options.getAuthToken();if(!h?.trim())throw new g("authentication_required","Sign in to Cline to reconnect this cloud session.");return s(),{Authorization:`Bearer ${h.trim()}`}}});d={generation:n,remote:r,client:f,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},d.unsubscribe=f.subscribe(()=>{},{sessionId:r.metadata.taskId?.trim()||e}),this.connections.set(e,d);try{if(await f.connect(),d.connected=!0,this.publishSnapshot(e),this.assertSessionActive(e,d),await this.resolveInnerSession(e,d,Boolean(t.handoffSeed)),this.assertSessionActive(e,d),t.handoffSeed&&d.innerSessionId)await this.assertHandoffConnectionReusable(d,t.handoffSeed);if(t.createInner&&!d.innerSessionId)await this.createInnerSession(d,t.handoffSeed);return this.assertSessionActive(e,d),d}catch(c){if(Ne(c)&&!this.disposed&&!d.disposed&&!this.deletingSessions.has(e))throw c;if(this.connections.get(e)===d)this.connections.delete(e);if(d.disposed=!0,d.unsubscribe(),!this.disposed&&n===(this.sessionGenerations.get(e)??0))this.clearPendingApprovals(e);throw await f.dispose().catch(()=>{return}),c}})().finally(()=>{if(this.connectionPromises.get(e)===a)this.connectionPromises.delete(e)});return this.connectionPromises.set(e,a),await a}async resolveInnerSession(e,t,n=!1){if(this.assertSessionActive(e,t),t.innerSessionId)return;let s=t.remote.metadata.taskId?.trim(),o;if(s)try{let r=await t.client.command("session.get",{sessionId:s},s);this.assertSessionActive(e,t),o=r.payload?.session&&typeof r.payload.session==="object"&&!Array.isArray(r.payload.session)?r.payload.session:void 0}catch(r){if(!we(r))throw r}else{let r=await t.client.command("session.list",{limit:100});this.assertSessionActive(e,t),o=re(r.payload).filter(ae).sort((d,u)=>Ue(u)-Ue(d))[0]}let i=String(o?.sessionId??"").trim();if(!i||!o){if(!n&&!this.pendingInitialTasks.has(e))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}if(t.remote.sandboxType==="resumable"||t.remote.metadata.sandboxType==="resumable")await this.restoreSavedInnerSession(t,i,o),this.assertSessionActive(e,t);this.pendingInitialTasks.delete(e),t.innerSessionId=i,this.subscribeToInnerSession(e,t);let a=De(o);if(a)this.applyModel(t,a);await this.ensureAttached(t)}async restoreSavedInnerSession(e,t,n){let s=()=>e.client.command("session.update_connection",{sessionId:t,updates:{}},t);try{await s();return}catch(p){if(!(we(p)||p instanceof Error&&p.code==="command_failed"&&p.message===`session not found: ${t}`))throw p}this.assertSessionActive(e.remote.id,e);let o=await e.client.command("session.messages",{},t);this.assertSessionActive(e.remote.id,e);let i=o.payload?.messages;if(!Array.isArray(i)||i.length===0)throw Error("The saved conversation is empty or unavailable.");let a=n.metadata??{},r=n.runtimeOptions??{},d=this.sessions.get(e.remote.id)?.config,u=Object.hasOwn(a,"thinking")?a.thinking:d?.thinking,f=Object.hasOwn(a,"reasoningEffort")?a.reasoningEffort:d?.reasoningEffort,c=typeof a.autoApproveTools==="boolean"?a.autoApproveTools:d?.autoApproveTools,h=n.cwd??n.workspaceRoot??C,l=n.workspaceRoot??C;try{let p=await e.client.command("session.create",{workspaceRoot:l,cwd:h,initialMessages:i,metadata:{...a,interactive:!0},sessionConfig:{sessionId:t,providerId:a.provider??"cline",modelId:a.model??a.modelId??e.remote.metadata.modelId,workspaceRoot:l,cwd:h,systemPrompt:r.systemPrompt??a.systemPrompt??"",mode:r.mode??a.mode??"act",...typeof u==="boolean"?{thinking:u}:{},...typeof f==="string"?{reasoningEffort:f}:{},...a.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:r,...typeof c==="boolean"?{toolPolicies:{"*":{autoApprove:c}}}:{}});if(this.assertSessionActive(e.remote.id,e),(p.payload?.session?.sessionId??p.payload?.sessionId)!==t)throw Error("Cloud Hub did not restore the requested session.")}catch(p){if(p?.code!=="session_already_exists")throw p;this.assertSessionActive(e.remote.id,e),await s()}}async assertHandoffConnectionReusable(e,t){let n=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let s=re(n.payload).filter(ae),[o]=s;if(s.length!==1||String(o?.sessionId??"").trim()!==e.innerSessionId||Xt(o)!==t.sourceSessionId)throw new g("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.")}async createInnerSession(e,t){if(this.assertSessionActive(e.remote.id,e),e.innerSessionCreation){if(await e.innerSessionCreation,t)await this.assertHandoffConnectionReusable(e,t);return}let n=(async()=>{if(t&&await this.adoptExistingHandoffSession(e,t)){this.unconfirmedInnerCreates.delete(e.remote.id);return}if(t?.recoverOnly||this.unconfirmedInnerCreates.has(e.remote.id))throw new g("request_failed","Cloud conversation creation is still unconfirmed. Wait for it to appear before trying again.");await this.createInnerSessionOnce(e,t)})().finally(()=>{e.innerSessionCreation=void 0});return e.innerSessionCreation=n,await n}async adoptExistingHandoffSession(e,t){let n=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let s=re(n.payload).filter(ae);if(s.length===0)return!1;let[o]=s,i=String(o?.sessionId??"").trim();if(s.length!==1||!i||Xt(o)!==t.sourceSessionId)throw new g("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return e.innerSessionId=i,this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,o),await this.ensureAttached(e),!0}async createInnerSessionOnce(e,t){let n=e.remote.metadata.modelId?.trim();if(!n)throw Error("Cloud session is missing its model id");let s=this.sessions.get(e.remote.id),o=We(t?.workspaceRelativePath),i=t?.mode??"act";try{await t?.onSeeding?.(),this.assertSessionActive(e.remote.id,e)}catch(y){if(t)throw new ze(y);throw y}let a=`cline/${(e.remote.metadata.taskId?.trim()||e.remote.id).slice(-8).toLowerCase()}`,r=e.remote.sandboxType==="resumable"||e.remote.metadata.sandboxType==="resumable",d=`${Yt}
|
|
7
|
+
${m}${y}`)}let o;try{o=await t.symbolicBranch()}catch(p){let m=Q(p)===1,y=K(p),w=m?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new _(m?"detached_head":"git_command_failed",y?`${w} (${y})`:w,{cause:p})}if(!o)throw new _("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[r,a,d]=await Promise.all([O(()=>t.branchRemote(o),"missing_upstream",`Branch ${o} has no upstream. Push it with -u before handing off.`),O(()=>t.branchMergeRef(o),"missing_upstream",`Branch ${o} has no upstream. Push it with -u before handing off.`),O(t.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!r||r==="."||!a.startsWith("refs/heads/"))throw new _("missing_upstream",`Branch ${o} has no remote branch upstream. Push it with -u before handing off.`);let u=a.slice(11),f=r;if(!Xe(r))try{f=await t.remoteUrl(r)}catch{throw new _("missing_upstream","Could not resolve the upstream remote.")}let c=Xe(f);if(!c)throw new _("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let h;try{h=await t.remoteRefs(r,a)}catch(p){let m=Q(p)===2,y=m?`The upstream branch ${u} 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 _(m?"remote_branch_missing":"git_command_failed",y)}let l=dn(h,u);if(!l)throw new _("remote_branch_missing",`The upstream branch ${u} was not found. Push it before handing off.`);if(l.toLowerCase()!==d.toLowerCase())throw new _("unpushed_commits",`Local HEAD does not match the upstream branch ${u}. Push the current commit before handing off.`);return{repoUrl:c,branch:u,headSha:d,...s?{workspaceRelativePath:s}:{}}}function pe(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function E(e){if(typeof e!=="string")return;return e.trim()||void 0}function un(e){return typeof e==="string"&&e.length>0?e:void 0}function ln(e){let t=E(e.repoUrl),n=E(e.branch),s=E(e.headSha),i=E(e.modelId);if(!t||!n||!s||!i)throw Error("Cloud handoff fingerprint fields cannot be empty.");let o=E(e.organizationId),r=un(e.workspaceRelativePath),a=e.mode;return{repoUrl:t,branch:n,headSha:s,modelId:i,...o?{organizationId:o}:{},...r?{workspaceRelativePath:r}:{},...a?{mode:a}:{}}}function Ui(e,t){return e!==void 0&&t!==void 0&&e.repoUrl===t.repoUrl&&e.branch===t.branch&&e.headSha.toLowerCase()===t.headSha.toLowerCase()&&e.modelId===t.modelId&&e.organizationId===t.organizationId&&e.workspaceRelativePath===t.workspaceRelativePath&&e.mode===t.mode}function pn(e){let t=pe(e);if(!t||typeof t.repoUrl!=="string"||typeof t.branch!=="string"||typeof t.headSha!=="string"||typeof t.modelId!=="string")return;try{return ln({repoUrl:t.repoUrl,branch:t.branch,headSha:t.headSha,modelId:t.modelId,...typeof t.organizationId==="string"?{organizationId:t.organizationId}:{},...typeof t.workspaceRelativePath==="string"?{workspaceRelativePath:t.workspaceRelativePath}:{},...t.mode==="plan"||t.mode==="yolo"||t.mode==="zen"?{mode:t.mode}:{}})}catch{return}}function Di(e){let t=pe(pe(e)?.handoff);if(!t)return;let n=E(t.toCloudSessionId),s=E(t.handedOffAt),i=t.status;if(!n||!s||i!=="pending"&&i!=="complete")return;let o=E(t.innerSessionId),r=E(t.dashboardUrl),a=pn(t.fingerprint);return{toCloudSessionId:n,handedOffAt:s,status:i,...o?{innerSessionId:o}:{},...r?{dashboardUrl:r}:{},...a?{fingerprint:a}:{}}}function Li(e,t){return{...e??{},handoff:t}}function Bi(e){let{handoff:t,cloudHandoffIntent:n,cloudHandoffSeedDispatched:s,...i}=e??{};return i}function qi(e,t){let n=t.trim();if(!n)throw Error("Cloud session id cannot be empty.");let s=new URL("/agents",e);return s.searchParams.set("sessionId",n),s.toString()}function Ze(e){return e.map((t)=>{let n=t&&typeof t==="object"?t:{};return{role:n.role,content:n.content}})}function fe(e,t){return e.length===t.length&&JSON.stringify(Ze(e))===JSON.stringify(Ze(t))}class he extends Error{constructor(e,t){super(`Cloud transcript verification failed (local ${e} messages, cloud ${t}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as fn}from"node:crypto";import{decodeJwtPayload as hn}from"@cline/shared";var mn=610000,gn=3000,B=15000,yn="CLOUD_SESSION_ERROR:",nt="__cline_create_request__:";function st(e){return(e.trim().split(`
|
|
8
|
+
`)[0]??"").trim().slice(0,72)}class g extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${yn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class it extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function ye(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function bn(e){return`${nt}${e}`.slice(0,255)}function et(e){return e?.startsWith(nt)===!0}function be(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function me(e){let t=hn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function tt(e){return new Promise((t,n)=>{if(e.aborted){n(e.reason);return}let s=()=>{clearTimeout(i),n(e.reason)},i=setTimeout(()=>{e.removeEventListener("abort",s),t()},gn);e.addEventListener("abort",s,{once:!0})})}function wn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function ge(e,t,n,s){let i=wn(t,`Cloud session request failed (${e})`);if(e===401)return new g("authentication_required",i);if(e===404)return new g("session_not_found",i);if(e===410)return new g("session_expired",i);if(e===412)return new g("github_not_connected",i,s??`${ye(n)}/dashboard/integrations`);if(e===403&&i.trim().toLowerCase()==="forbidden")return new g("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new g("request_failed",i,void 0,e)}class vn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=ye(e.apiBaseUrl),this.appBaseUrl=ye(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??mn}async request(e,t={},n,s,i){let o=!1,r;while(!0){let a;try{a=typeof s==="string"?s:await this.options.getAuthToken()}catch(f){if(r)throw ge(401,void 0,this.appBaseUrl,n);throw f}if(!a?.trim())throw new g("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new g("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?me(a.trim())!==s.subject:a.trim()!==s.token)throw new g("authentication_required","The signed-in account changed during cloud session creation.");s.token=a.trim()}i?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),u=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!o&&s.subject){o=!0,r=a.trim();continue}throw ge(d.status,u,this.appBaseUrl,n)}return u?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((o)=>{if(!o||typeof o!=="object"||typeof o.id!=="string")return[];return[{...o,title:!n&&et(o.title)?void 0:o.title,repoContext:o.repoContext&&typeof o.repoContext==="object"?o.repoContext:{},metadata:{...o.metadata&&typeof o.metadata==="object"?o.metadata:{},...!n&&et(o.title)?{createRequestTitle:o.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let i=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:i.flatMap((o)=>{let r=Number(o.id),a=String(o.html_url??o.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(o.name??"").trim();return[{id:r,name:d,fullName:String(o.full_name??(d||a)).trim(),url:a,defaultBranch:String(o.default_branch??"").trim()}]})}}catch(i){if(i instanceof g&&i.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw i}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new g("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),i=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,o=new URLSearchParams,r=n.query?.trim(),a=n.cursor?.trim();if(r)o.set("query",r);if(a)o.set("cursor",a);let d=o.size>0?`${i}?${o}`:i;try{let u=await this.request(d),f=Array.isArray(u)?u:Array.isArray(u?.items)?u.items:[],c=r?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let l=String(h.name??"").trim();return l&&(!Array.isArray(u)||!c||l.toLowerCase().includes(c))?[l]:[]}),nextToken:Array.isArray(u)?"":String(u?.nextToken??"").trim()}}catch(u){if(u instanceof g&&u.code==="session_not_found")return{available:!1,branches:[]};throw u}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new g("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new g("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:me(t)},s=bn(e.requestId?.trim()||fn()),i=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new g("request_failed","A stable request id is required for cloud handoff creation.");let o=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),r=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let l=new g(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(p){if(!(p instanceof g&&(p.code==="session_not_found"||p.code==="session_expired")))throw AggregateError([l,p],"The unusable recovered cloud handoff workspace could not be removed.")}if(i)this.unconfirmedHandoffCreates.delete(i),this.completedHandoffCreates.delete(i);throw await e.handoff?.onOuterSessionRemoved?.(c.id),l}await e.handoff?.onOuterSessionCreated(c.id,{created:!1});let h={sessionId:c.id,status:c.status,sandboxUrl:c.sandboxUrl,cleanupAuthToken:n.token};if(i)this.unconfirmedHandoffCreates.delete(i),this.completedHandoffCreates.set(i,h);return h};if(i){let c=await o();if(c.length>1)throw new g("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await r(c[0]);let h=this.completedHandoffCreates.get(i);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(l){if(l instanceof g&&(l.code==="session_not_found"||l.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(i),this.unconfirmedHandoffCreates.delete(i);throw l}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:n.token}}if(this.unconfirmedHandoffCreates.has(i))throw new g("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(i)}try{await e.handoff?.onCreating()}catch(c){if(i)this.unconfirmedHandoffCreates.delete(i);throw c}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),u,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new g("request_failed","The cloud session service returned no session id.");u=h,await this.persistHandoffOuterSession(e,h,n,i);let l={sessionId:h,status:c.status?.trim()||"provisioning",sandboxUrl:c.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(i)this.unconfirmedHandoffCreates.delete(i),this.completedHandoffCreates.set(i,l);return l}catch(c){if(u)throw c;let h=!f||c instanceof g&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(i&&h)throw this.unconfirmedHandoffCreates.delete(i),new it(c);if(a.signal.aborted||!(c instanceof g)||c instanceof g&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let p=[];try{p=await o()}catch(y){if(e.handoff)throw AggregateError([c,y],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(p.length>1)throw new g("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let m=p[0];if(m){if(e.handoff)return await r(m);return{sessionId:m.id,status:m.status,sandboxUrl:m.sandboxUrl,cleanupAuthToken:n.token}}}else if(i)this.unconfirmedHandoffCreates.delete(i);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(i){try{await this.deleteWithAuth(t,n.token)}catch(o){if(!(o instanceof g&&(o.code==="session_not_found"||o.code==="session_expired")))throw AggregateError([i,o],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),i}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),i=s?{token:s,subject:me(s)}:void 0;while(!t.aborted){let o;try{o=await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:AbortSignal.any([t,AbortSignal.timeout(B)])},void 0,i)}catch(a){if(t.aborted)throw a;if(a instanceof g&&a.code!=="request_failed")throw a;await tt(t);continue}let r=o?.status?.trim().toLowerCase();if(n?.({phase:be(o?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new g("session_failed",o?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new g("request_failed","The cloud session service returned an unexpected provisioning status.");await tt(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof g)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,i]of this.completedHandoffCreates)if(i.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new g("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw ge(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new g("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as mi}from"node:crypto";import{posix as ue}from"node:path";import{createSessionId as Bs,ensureLoopbackProxyBypass as Lt,isHubProtocolCompatible as qs,resolveClineBuildEnv as Ns,resolveHubCommandTimeoutMs as $s}from"@cline/shared";import Ws from"ws";var q={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92-nightly.1791513440",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var ot="session_not_found";class Y extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function we(e){return e instanceof Y||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as ss}from"node:child_process";import{closeSync as is,mkdirSync as os,openSync as rs,readFileSync as as,unlinkSync as ds}from"node:fs";import{basename as cs,dirname as us,join as ls}from"node:path";import{fileURLToPath as ps}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fs,isBunEmbeddedModulePath as hs,isHubDaemonProcess as ms,resolveClineBuildEnv as Et,withResolvedClineBuildEnv as gs}from"@cline/shared";import{createHash as Sn,randomBytes as kn}from"node:crypto";import{mkdir as Ce,open as rt,readFile as lt,rename as Rn,rm as Se,writeFile as _n}from"node:fs/promises";import{dirname as pt,join as ke}from"node:path";import{ensureLoopbackProxyBypass as Pn,isHubProtocolCompatible as An}from"@cline/shared";import{resolveClineDataDir as N,resolveClineDir as so}from"@cline/shared/storage";var Tn="CLINE_HUB_DISCOVERY_PATH",En="CLINE_HUB_BUILD_ID",xn="CLINE_HUB_BUILD_EPOCH_MS",Hn=30000,In=15000,at=100;function Mn(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function On(e){return Sn("sha256").update(e).digest("hex").slice(0,12)}function Un(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function dt(e){return new Promise((t)=>setTimeout(t,e))}function Dn(e){return`${e}.lock`}async function Ln(e){try{let t=JSON.parse(await lt(ke(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function ve(e){await Se(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[En]?.trim();if(e)return e;return"sdk-v1-ef32a5624a2857649ead307ef194e0e055eea5ad5ca3705e3a3731712d5e64a2".trim()||`source-${String(q.version)}`}function Bn(){let e=Number(process.env[xn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1791513463130)?1791513463130:void 0}function X(e,t=U()){let n=An(e);if(!n.compatible)return n;let s=e.buildId?.trim();if(!s)return{compatible:!1,reason:"missing_build"};if(s!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ct(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ut(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((s)=>Number(s));if(n.length===0||n.some((s)=>!Number.isInteger(s)||s<0))return;return n}function qn(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let s=e[n]??0,i=t[n]??0;if(s!==i)return s<i?-1:1}return 0}function ft(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let i=ct(e.buildEpochMs),o=ct(t.buildEpochMs);if(i!==void 0&&o!==void 0&&i!==o)return i<o?-1:1;let r=ut(e.coreVersion),a=ut(t.coreVersion);if(r&&a){let d=qn(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function ht(){return{buildId:U(),buildEpochMs:Bn(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??ht(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return ft(n,e)<=0}function mt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${On(e)}`,n=process.env[Tn]?.trim()||ke(N(),"locks","hub","owners",`${Mn(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e){try{let t=JSON.parse(await lt(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function gt(e,t){await bt(e,async()=>{let n=pt(e);await Ce(n,{recursive:!0});let s=`${e}.${process.pid}.${kn(6).toString("hex")}.tmp`,i;try{i=await rt(s,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
|
|
9
|
+
`,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,await Rn(s,e);let o;try{o=await rt(n,"r"),await o.sync()}catch{}finally{await o?.close().catch(()=>{return})}}catch(o){throw await i?.close().catch(()=>{return}),await Se(s,{force:!0}).catch(()=>{return}),o}})}async function D(e){await bt(e,async()=>{await Se(e,{force:!0}).catch(()=>{return})})}async function yt(e,t,n){let s=Dn(e);await Ce(pt(s),{recursive:!0});let i=Date.now()+In;while(!0){try{await Ce(s,{recursive:!1})}catch(o){if((o instanceof Error&&"code"in o?String(o.code):"")!=="EEXIST")throw o;let a=await Ln(s);if(!a){if(Date.now()>=i){await ve(s);continue}await dt(at);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!Un(a.pid)||d>Hn){await ve(s);continue}if(Date.now()>=i)throw Error(`Timed out waiting for hub ${t} lock ${s}`);await dt(at);continue}try{return await _n(ke(s,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
10
|
+
`,"utf8"),await n()}finally{await ve(s)}}}function bt(e,t){return yt(`${e}.mutation`,"discovery mutation",t)}function wt(e,t){return yt(e,"startup",t)}async function ee(e,t){Pn();try{let n=await fetch(t?.authToken?Nn(e):Ct(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let s=await n.json();if(typeof s.protocolVersion!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string")return;return{protocolVersion:s.protocolVersion,minClientProtocolVersion:typeof s.minClientProtocolVersion==="string"?s.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof s.maxClientProtocolVersion==="string"?s.maxClientProtocolVersion:void 0,capabilities:Array.isArray(s.capabilities)?s.capabilities.filter((i)=>typeof i==="string"):void 0,coreVersion:typeof s.coreVersion==="string"?s.coreVersion:void 0,buildId:typeof s.buildId==="string"?s.buildId:void 0,buildEpochMs:typeof s.buildEpochMs==="number"?s.buildEpochMs:void 0,host:s.host,port:s.port,url:s.url,hubId:typeof s.hubId==="string"?s.hubId:void 0,authToken:typeof s.authToken==="string"?s.authToken:void 0,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:typeof s.startedAt==="string"?s.startedAt:void 0,updatedAt:typeof s.updatedAt==="string"?s.updatedAt:void 0}}catch{return}}function vt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Ct(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function Nn(e){let t=new URL(Ct(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as $n,CLINE_HUB_PORT as Wn,resolveClineBuildEnv as jn}from"@cline/shared";var Fn="CLINE_HUB_HOST",zn="CLINE_HUB_PORT",Gn="CLINE_HUB_PATHNAME",Jn="127.0.0.1",Vn=Wn,Kn="/hub";function St(e){return jn(e)==="development"?$n:Vn}function Qn(e={}){return(e.env??process.env)[Fn]?.trim()||Jn}function Yn(e={}){let n=(e.env??process.env)[zn]?.trim();if(!n)return St(e);let s=Number.parseInt(n,10);if(!Number.isInteger(s)||s<1||s>65535)return St(e);return s}function Xn(e={}){return(e.env??process.env)[Gn]?.trim()||Kn}function kt(e={},t={}){return{host:e.host??Qn(t),port:e.port??Yn(t),pathname:e.pathname??Xn(t)}}import{join as Zn}from"node:path";var es="shared:cline",ts="CLINE_HUB_DISCOVERY_PATH",ns="hub-production";function W(e=es){return mt(`${e}@${U()}`)}function te(){return{ownerId:ns,discoveryPath:process.env[ts]?.trim()||Zn(N(),"locks","hub","production.json")}}var Rt=15000,ys=200,_t=3000,bs=100,ws=[100,250,500,1000,2000],vs="--cline-hub-daemon",Cs=3,Ss=60000,Pt=new Map;function ks(e,t=Date.now()){let n=Pt.get(e);if(!n||t-n.windowStartedAt>Ss)return Pt.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Cs}function Rs(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function _s(){try{let e=ls(N(),"logs","hub-daemon.log");return os(us(e),{recursive:!0}),{fd:rs(e,"a"),logPath:e}}catch{return}}function Ps(){return Et()==="production"?te():W()}function j(e){return Z(e)}function As(e){try{let t=JSON.parse(as(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function Re(e){try{ds(`${e}.superseded`)}catch{}}function At(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function F(e,t){try{return await ee(e,{authToken:t})}catch{return}}async function Tt(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await F(e))?.url)return!0;await new Promise((i)=>setTimeout(i,bs))}return!1}async function Pe(e,t){if(!ks(e.url))return!1;await z(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Ht(e.url,e.authToken).catch(()=>!1);let n=await Tt(e.url,_t);if(!n&&e.pid&&Ts(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Tt(e.url,_t)}if(n)await D(t).catch(()=>{return});return n}function Ts(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Es(e){try{return(await Ae(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function _e(e,t){if(j(e))return"reusable";let n=await z(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await Es(e)){if(n)await z(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let s=await Pe(e,t);if(!s&&n)await z(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return s?"retired":"failed"}async function xs(e){if(Et()!=="production")return;let t=W();if(t.discoveryPath===e.discoveryPath)return;let n=await I(t.discoveryPath);if(n?.url)await Pe(n,t.discoveryPath);else await D(t.discoveryPath).catch(()=>{return})}function Hs(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return ps(new URL(`./entry.${e}`,import.meta.url))}function Is(e,t){if(hs(e))return[vs];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function Ms(e,t){let n=Hs(),s=process.execPath?.trim();if(!s)throw Error("unable to resolve runtime executable for hub daemon");let i=cs(s).toLowerCase().includes("bun"),o=Is(n,i);return{launcher:s,args:[...o,"--cwd",e,...Rs(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...gs(process.env),CLINE_NO_INTERACTIVE:"1",[fs]:"1"}}}function Os(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function Us(e,t={}){if(ms())return;let n=Ms(e,t),s=_s();try{ss(n.launcher,n.args,{detached:!0,stdio:s?["ignore",s.fd,s.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(s)is(s.fd)}}async function Ds(e,t={}){for(let n=0;;n++)try{Us(e,t);return}catch(s){let i=ws[n];if(!Os(s)||i===void 0)throw s;await new Promise((o)=>setTimeout(o,i))}}async function Ls(e,t,n={}){let s=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),i=kt(n),o=vt(i.host,i.port,i.pathname),r=(p)=>{if(!s)ne(p.url,p.authToken);return p};await xs(e).catch(()=>{return});let a=await I(e.discoveryPath),d=a?.url?void 0:As(e.discoveryPath),u=!1;if(a?.url){let p=a.authToken;if(!p)u=!0,await Pe(a,e.discoveryPath);else{let m=await F(a.url,p);if(m?.url&&j(m)&&await x(m.url,{authToken:p}))return Re(e.discoveryPath),r({url:m.url,authToken:p});if(m?.url){if(await _e({...m,authToken:p},e.discoveryPath)==="deferred_busy"&&await x(m.url,{authToken:p}))return r({url:m.url,authToken:p})}else await D(e.discoveryPath).catch(()=>{return})}}let f=await F(o);if(f?.url){let p=At(f,a??d,o);if(j(f)){let y=[f.authToken,a?.authToken,d?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0);for(let v of y){if(!await x(f.url,{authToken:v}))continue;let P={hubId:f.hubId??`repaired-${f.port}`,protocolVersion:f.protocolVersion,minClientProtocolVersion:f.minClientProtocolVersion,maxClientProtocolVersion:f.maxClientProtocolVersion,capabilities:f.capabilities,coreVersion:f.coreVersion,buildId:f.buildId,authToken:v,host:f.host,port:f.port,url:f.url,pid:f.pid??a?.pid??d?.pid,startedAt:f.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await gt(e.discoveryPath,P)}catch{}return Re(e.discoveryPath),r({url:f.url,authToken:v})}throw Error(`A compatible Cline Hub is already running at ${o}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${u?" 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 m=await _e(p,e.discoveryPath);if(m==="deferred_busy"){for(let y of[p.authToken,a?.authToken].filter((w)=>typeof w==="string"&&w.trim().length>0))if(await x(f.url,{authToken:y}))return r({url:f.url,authToken:y});if(n.allowPortFallback!==!0&&i.port!==0)throw Error(`An older Cline Hub is running at ${o} 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(m==="failed"&&n.allowPortFallback!==!0&&i.port!==0)throw Error(`An incompatible Cline Hub is already running at ${o} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let h=n.allowPortFallback===!0&&i.port!==0?{...i,port:0}:i;await Ds(t,{...h,manageConnectors:n.manageConnectors});let l=Date.now()+Rt;while(Date.now()<l){let p=await I(e.discoveryPath);if(p?.url&&p.authToken){let y=await F(p.url,p.authToken);if(y?.url&&j(y)&&await x(y.url,{authToken:p.authToken}))return Re(e.discoveryPath),r({url:y.url,authToken:p.authToken})}let m=await F(o);if(m?.url&&!j(m)){let y=At(m,p??d,o),w=await _e(y,e.discoveryPath);if(w==="deferred_busy"&&p?.authToken&&await x(m.url,{authToken:p.authToken}))return r({url:m.url,authToken:p.authToken});if(w==="failed"&&n.allowPortFallback!==!0&&i.port!==0)throw Error(`An incompatible Cline Hub is still running at ${o} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((y)=>setTimeout(y,ys))}throw Error(`Timed out after ${Rt}ms waiting for detached hub startup.`)}async function xt(e,t={}){let n=Ps();return await wt(n.discoveryPath,async()=>Ls(n,e,t))}function js(){return Ns()==="production"?te():W()}function Fs(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Bt(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return Bt(e.data);return String(e)}function zs(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function It(e){let t=e,n=zs(t.reason);return new k("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Ee,{closeCode:t.code,closeReason:n||void 0})}function Mt(e,t){if(e instanceof k)return e;if(e instanceof Error)return new k("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new k("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new k("hub_connect_failed",n);let s=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new k("hub_connect_failed",s?`Failed to connect to hub at ${t.toString()} (${s} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var Te="*",se=8000,Gs="cline-hub-auth.",qt=new Map,Nt=new Set,Js=3000;var Ee="Hub connection closed",Vs=250,Ks=5000,Ot=0.5;class k extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Qs(e){return e instanceof k}class xe extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function Ie(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let s=Me(e.toString());return s?qt.get(s):void 0}function Ys(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function Me(e){if(!Ys(e))return;let t=new URL($t(e));return t.search="",t.hash="",t.toString()}function Ut(e){let t=Me(e);return!!t&&Nt.has(t)}function ne(e,t){let n=Me(e);if(n){if(Nt.add(n),t?.trim())qt.set(n,t)}return e}class G{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new k("hub_connection_closed",Ee);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||Ie(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,s=this.openSocket(e,t,n),i;this.connectPromise=s.then(async(r)=>{if(i=r,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(q.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{r.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let a of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(a));this.reconnectAttempt=0});let o=this.connectPromise;try{await o}catch(r){if(this.connectPromise===o)this.connectPromise=void 0;if(i&&this.socket===i){this.lastCloseError=Mt(r,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{i.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw r}}async openSocket(e,t,n){let s=this.options.resolveConnectionHeaders,i;if(s){let d;try{i=await Promise.race([Promise.resolve().then(()=>s()),new Promise((u,f)=>{d=setTimeout(()=>{f(new k("hub_connect_timeout",`Timed out resolving hub connection headers after ${se}ms`))},se)})])}catch(u){let f=u instanceof k?u:new k("hub_connect_failed",u instanceof Error?u.message:String(u));if(n===this.connectGeneration)this.lastCloseError=f;throw f}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(i&&Object.keys(i).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new k("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let o=i?new Ws(e.toString(),{headers:{...i}}):new(Fs())(e.toString(),t?[`${Gs}${t}`]:void 0);this.socket=o;let r=!1,a=new Promise((d,u)=>{let f=!1,c=setTimeout(()=>{if(f)return;f=!0,r=!0;let h=new k("hub_connect_timeout",`Timed out connecting to hub after ${se}ms`);if(this.socket===o)this.lastCloseError=h,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{o.close()}catch{}u(h)},se);o.addEventListener("open",()=>{if(f)return;f=!0,clearTimeout(c),d()}),o.addEventListener("error",(h)=>{if(f)return;f=!0,clearTimeout(c);let l=Mt(h,e);if(this.socket===o)this.lastCloseError=l,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;u(l)}),o.addEventListener("close",(h)=>{if(f)return;f=!0,clearTimeout(c);let l=r?this.lastCloseError:It(h);if(this.socket===o){if(!r)this.lastCloseError=l,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}u(l)})});return o.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(Bt(d)))}),o.addEventListener("close",(d)=>{if(this.socket!==o)return;if(!r)this.lastCloseError=It(d),this.sawSocketClose=!0;this.registered=!1;for(let u of this.pendingReplies.values())u.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await a,o}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,s={listener:e,sessionId:n};return this.listeners.add(s),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(s))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,s){let i=0,o=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,s)}catch(r){if(!o||i>=1||!await this.recoverLocalHubTransport(r))throw r;i+=1}}async commandOnce(e,t,n,s,i=!0){if(i)await this.connect();s?.beforeDispatch?.();let o=Bs("hubreq_");s?.onDispatch?.(o);let r=$s(e,s?.timeoutMs),a=new Promise((u,f)=>{let c=r===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(o))return;f(new xe(e,"hub_command_timeout",`Hub command ${e} timed out after ${r}ms (hub=${this.currentUrl}, requestId=${o}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},r);this.pendingReplies.set(o,{resolve:(h)=>{if(c)clearTimeout(c);u(h)},reject:(h)=>{if(c)clearTimeout(c);f(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:o,clientId:this.clientId,sessionId:n,timeoutMs:r,payload:t}})}catch(u){throw this.pendingReplies.delete(o),u}let d=await a;if(!d.ok){if(d.error?.code===ot){let u=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Y(u,d.error.message)}throw new xe(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Ut(this.currentUrl)||!Qs(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Dt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let e=Math.min(Vs*2**this.reconnectAttempt,Ks),t=Math.round(e*(1-Ot)+Math.random()*e*Ot);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Ut(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Dt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new k("hub_connection_closed",Ee);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new k("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),s=(this.subscriptionCounts.get(n)??0)+t;if(s<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,s),t>0&&s===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??Te}subscriptionSessionIdFromKey(e){return e===Te?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let s of[Te,n]){if(!s||!this.subscriptionCounts.has(s))continue;let i=this.lastEventSequenceByKey.get(s)??0;if(t>i)this.lastEventSequenceByKey.set(s,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function $t(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function x(e,t){let n=new G({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function He(e,t){let n=$t(e),s=await ee(n,{authToken:t?.authToken});if(!s)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let i=U(),o=X(s,i);if(!o.compatible&&!Z(s))return{status:o.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!qs(s).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await x(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function Xs(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,s=new Set;for(let i of t){if(!i||typeof i!=="object")continue;let o=i.participants;if(!Array.isArray(o)||o.length===0)continue;n+=1;for(let r of o){let a=r&&typeof r==="object"?r.clientId:void 0;if(typeof a==="string"&&a.trim())s.add(a)}}return{activeSessionCount:n,participantClientCount:s.size}}async function Ae(e,t,n){let s=new G({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let i=await s.command("session.list",{limit:500},void 0,{timeoutMs:Js});return Xs(i.payload)}finally{await s.dispose().catch(()=>{return})}}async function Zs(e,t,n){try{return(await Ae(e,t,n)).activeSessionCount===0}catch{return!1}}async function ei(e,t){let n=`${e.discoveryPath}.superseded`,s=await I(n);if(!s?.url||!s.authToken)return;let i=await He(s.url,{authToken:s.authToken});if(i.status!=="compatible")return;if(await Zs(i.url,s.authToken,t))return;return ne(i.url,s.authToken)}async function ti(e={}){if(e.endpoint?.trim()){let i=await He(e.endpoint);return i.status==="compatible"?i.url:void 0}let t=js(),n=await I(t.discoveryPath);if(!n?.url)return await ei(t,e);let s=await He(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(s.status==="compatible")return ne(s.url,n.authToken);if(s.status==="protocol_mismatch")await D(t.discoveryPath).catch(()=>{return});return}async function Dt(e={}){let t=await ti(e);if(t&&await x(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await xt(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function z(e,t,n,s){Lt();let i=new URL(e),o=t?.trim()||Ie(i);if(i.protocol==="ws:")i.protocol="http:";else if(i.protocol==="wss:")i.protocol="https:";if(i.pathname="/drain",i.hash="",n)i.searchParams.set("reason",n);if(s?.off)i.searchParams.set("off","1");return(await fetch(i,{method:"POST",headers:o?{authorization:`Bearer ${o}`}:void 0})).ok}async function Ht(e,t){Lt();let n=new URL(e),s=t?.trim()||Ie(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:s?{authorization:`Bearer ${s}`}:void 0})).ok}function ni(e,t){if(!e||typeof e!=="object")return;let n=e,s=typeof n.id==="string"?n.id.trim():"";if(!s)return;let i=typeof n.display_name==="string"?n.display_name.trim():typeof n.displayName==="string"?n.displayName.trim():"",o=typeof n.name==="string"?n.name.trim():"";return{id:s,name:i||o||s,catalogId:t}}function Oe(e,t){return Array.isArray(e)?e.flatMap((n)=>{let s=ni(n,t);return s?[s]:[]}):[]}async function Wt(e,t={}){let n=e.trim(),s=n.length;while(s>0&&n[s-1]==="/")s--;let i=n.slice(0,s),o=async(m)=>{let y=await(t.fetchImpl??fetch)(`${i}${m}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!y.ok)throw Error(`HTTP ${y.status}`);return await y.json()},r,a;try{[r,a]=await Promise.all([o("/api/v1/ai/cline/models"),o("/api/v1/ai/cline/recommended-models")])}catch(m){throw Error("Could not load the cloud model catalog.",{cause:m})}let d=r&&typeof r==="object"?r:void 0,u=Oe(Array.isArray(r)?r:d?.data,"cline"),f=a&&typeof a==="object"?a:void 0,c=f?.data&&typeof f.data==="object"?f.data:f,h=Oe(c?.clinePass,"cline-pass"),l=Oe(c?.clineCloud,"cline-cloud"),p=new Set;return[...t.isOrganizationSession?[]:h,...l,...u].filter((m)=>{if(p.has(m.id))return!1;return p.add(m.id),!0})}import{formatDisplayUserInput as jt}from"@cline/shared";var si=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function ii(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function oi(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function ri(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function ai(e){if(typeof e.content==="string")return{hasAttachment:!1,text:e.content};if(!Array.isArray(e.content))return{hasAttachment:!1,text:"unknown"};let t=!1,n=!1,s=[];for(let i of e.content){if(!i||typeof i!=="object"||Array.isArray(i))continue;let o=i;if(o.type==="text"&&typeof o.text==="string")s.push(o.text);else if(o.type==="tool_result"||o.type==="tool-result")n=!0;else if(o.type==="file"||o.type==="image")t=!0}return{hasAttachment:t&&!n,text:s.join(`
|
|
11
|
+
`)}}function di(e){let t=jt(e);return t.startsWith("[TASK RESUMPTION]")||t==="The user approved switching to act mode. Continue with the approved plan now."}function ci(e){if(ii(e.role)!=="user")return 0;let t=oi(e),n=typeof t?.kind==="string"?t.kind:void 0,s=ri(t);if(n==="compaction"||n==="compaction_summary")return s??1;if(s!==void 0)return s;if(n&&si.has(n))return 0;let i=ai(e);if(!i.hasAttachment&&!jt(i.text))return 0;if(!i.hasAttachment&&di(i.text))return 0;return 1}function Ft(e){return ci(e)>0}function re(e){return Array.isArray(e?.sessions)?e.sessions.filter((t)=>Boolean(t)&&typeof t==="object"&&!Array.isArray(t)):[]}function Ue(e){let t=e.updatedAt;return typeof t==="number"?t:Date.parse(String(t??""))||0}function De(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return String(t?.model??e?.model??"").trim()}function ae(e){let t=e.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return!String(t?.parentSessionId??e.parentSessionId??"").trim()}function Vt(e,t="text"){if(!e||typeof e!=="object"||Array.isArray(e))return"";let n=e.content;if(typeof n==="string")return t==="text"?n.trim():"";if(!Array.isArray(n))return"";return n.map((s)=>s&&typeof s==="object"&&!Array.isArray(s)?t==="thinking"&&s.type==="redacted_thinking"?"[redacted]":String(s[t]??""):"").join("").trim()}function ie(e){let t=e.trim(),n=t.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(n?n[1]:t).trim()}function J(e,t,n){let s=ie(n);return e.filter((i)=>Boolean(i)&&typeof i==="object"&&!Array.isArray(i)&&String(i.role??"").toLowerCase()==="user"&&(s!==""||Ft(i))&&ie(Vt(i))===s).length+t.filter((i)=>ie(i.prompt)===s).length}function Le(e){return e.flatMap((t)=>{if(t.event!=="session.pending_prompt_submitted")return[];let n=t.payload?.prompt&&typeof t.payload.prompt==="object"&&!Array.isArray(t.payload.prompt)?t.payload.prompt:void 0,s=String(n?.id??"").trim();if(!s)return[];return[{id:s,prompt:String(n?.prompt??""),steer:n?.delivery==="steer",attachmentCount:typeof n?.attachmentCount==="number"?n.attachmentCount:0,userImages:Array.isArray(n?.userImages)?n.userImages.filter((i)=>typeof i==="string"):void 0}]})}var ui=new Set(["run.completed","run.aborted","run.failed"]),li=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function zt(e,t){return e.filter((n)=>Boolean(n)&&typeof n==="object"&&!Array.isArray(n)&&String(n.role??"").toLowerCase()==="assistant").map((n)=>Vt(n,t)).filter(Boolean)}function Gt(e,t,n="text"){let s=new Map;for(let i of zt(t,n))s.set(i,(s.get(i)??0)+1);return zt(e,n).filter((i)=>{let o=s.get(i)??0;if(o===0)return!0;if(o===1)s.delete(i);else s.set(i,o-1);return!1})}function oe(e,t,n=new Set){if(!e||typeof e!=="object")return n;if(Array.isArray(e)){for(let o of e)oe(o,t,n);return n}let s=e,i=t==="tool_use"?s.id:s.tool_use_id;if(s.type===t&&typeof i==="string")n.add(i);for(let o of Object.values(s))oe(o,t,n);return n}function Jt(e,t="assistant"){let n="",s="";for(let i of e)if(i.event===`${t}.delta`)s+=t==="reasoning"&&i.payload?.redacted&&!i.payload?.text?"[redacted]":typeof i.payload?.text==="string"?i.payload.text:"";else if(i.event===`${t}.finished`){let o=i.payload?.[t==="assistant"?"text":"reasoning"],r=typeof o==="string"&&o?o:s;if(r)n=r;s=""}return(n||s).trim()}function Kt(e,t,n={}){let s=n.queueSnapshotApplied!==!1,i=Gt(t,n.baselineMessages??[]),o=Gt(t,n.baselineMessages??[],"thinking"),r=oe(t,"tool_use"),a=oe(t,"tool_result"),d=new Set(e.slice(0,n.messagesSnapshotEventCutoff??e.length)),u=new Set,f=new Map;for(let y of e.slice(0,n.messagesSnapshotEventCutoff??e.length)){let w=Le([y])[0];if(!w)continue;let v=ie(w.prompt),P=f.get(v)??Math.max(0,J(t,[],v)-J(n.baselineMessages??[],[],v));if(f.set(v,Math.max(0,P-1)),P>0)u.add(y)}let h=[...s?e.slice(n.queueSnapshotEventCutoff??e.length):e].reverse().find((y)=>y.event==="session.pending_prompts"),l=[],p=[],m=(y)=>{if(p.length===0)return;let w=p.filter((A)=>d.has(A)),v=(A)=>{if(!y)return-1;let S=[...w].reverse().findIndex((tn)=>tn.event===`${A}.finished`),L=S<0?-1:w.length-1-S;return L>=0||p.at(-1)?.event==="run.aborted"?L:w.length-1},P=v("assistant"),H=v("reasoning"),b=Jt(w.slice(0,P+1)),R=b?i.findIndex((A)=>A.endsWith(b)):-1,M=R>=0;if(M)i.splice(R,1);let V=Jt(w.slice(0,H+1),"reasoning"),le=V?o.findIndex((A)=>A.endsWith(V)):-1;if(le>=0)o.splice(le,1);for(let[A,S]of p.entries()){if(u.has(S)){l.push({...S,payload:{...S.payload,transcriptReflected:!0}});continue}if(d.has(S)&&li.has(S.event)&&(S.event.startsWith("reasoning.")?le>=0&&A<=H:M&&A<=P))continue;if(S.event==="session.pending_prompts"&&S!==h)continue;if(d.has(S)&&S.event.startsWith("tool.")){let L=String(S.payload?.toolCallId??"").trim();if(a.has(L)||S.event==="tool.started"&&r.has(L))continue}l.push(S)}p=[]};for(let y of e)if(p.push(y),ui.has(y.event))m(!0);return m(!1),l}import{formatDisplayUserInput as pi}from"@cline/shared";function de(e){let t=structuredClone(e),n=(s)=>{if(!s||typeof s!=="object"||Object.isFrozen(s))return;for(let i of Object.values(s))n(i);Object.freeze(s)};return n(t),t}function ce(e){let t=e?.trim();return t?pi(t).slice(0,120):void 0}function Be(e){if(typeof e==="string")return e;if(Array.isArray(e)){let t=[];for(let n of e){if(typeof n==="string"){if(n.trim())t.push(n);continue}if(!n||typeof n!=="object")continue;let s=n,i=typeof s.type==="string"?s.type:"",o=i==="text"?String(s.text??""):i==="thinking"?String(s.thinking??""):i==="tool_use"?`[tool] ${String(s.name??"tool_call")}`:i==="tool_result"?`[tool_result]
|
|
12
|
+
${Be(s.content)}`:i==="image"?"[image]":i==="redacted_thinking"?"[redacted_thinking]":typeof s.text==="string"?s.text:"";if(o.trim())t.push(o)}return t.join(`
|
|
13
|
+
`)}if(e&&typeof e==="object"){let t=e;if(typeof t.text==="string")return t.text}return""}function fi(e){let t=ce(e??void 0);if(!t)return;return t.split(`
|
|
14
|
+
`)[0]?.trim().slice(0,70)||void 0}function hi(e){for(let t of["user","assistant"])for(let n of e){if(!n||typeof n!=="object")continue;let s=n;if(s.role!==t)continue;let i=ce(Be(s.content));if(!i)continue;return i.split(`
|
|
15
|
+
`)[0]?.trim().slice(0,70)||void 0}return}function qe(e){let t=e.metadata&&typeof e.metadata==="object"?ce(e.metadata.title):void 0;if(t)return t.slice(0,70);let n=fi(e.prompt);if(n)return n;let s=e.messages?hi(e.messages):void 0;if(s)return s;return`Session ${e.sessionId.slice(-6)}`}function Qt(e,t,n,s){let i=t.payload??{},o=()=>{let a=n.get(s);if(a===void 0||!e.messages[a]||e.messages[a]?.role!=="assistant")a=e.messages.length,e.messages.push({role:"assistant",content:[]}),n.set(s,a);let d=e.messages[a];if(!Array.isArray(d.content))d.content=[];return d.content},r=(a,d,u)=>{let f=o(),c=f.at(-1);if(c?.type===a)c[d]=`${c[d]??""}${u}`;else f.push({type:a,[d]:u})};switch(t.event){case"assistant.delta":if(typeof i.text==="string")r("text","text",i.text);return;case"reasoning.delta":if(typeof i.text==="string"&&i.text)r("thinking","thinking",i.text);else if(i.redacted===!0)o().push({type:"redacted_thinking",data:""});return;case"assistant.finished":n.delete(s);return;case"assistant.media":if(i.media)o().push({type:"media",media:structuredClone(i.media)});return;case"tool.started":{let a=String(i.toolCallId??"");if(a&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((u)=>u.type==="tool_use"&&u.id===a)))o().push({type:"tool_use",id:a,name:String(i.toolName??"tool"),input:structuredClone(i.input??{})});return}case"tool.finished":{let a=String(i.toolCallId??"");if(a&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((u)=>u.type==="tool_result"&&u.tool_use_id===a)))e.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:a,content:typeof i.output==="string"?i.output:JSON.stringify(i.output??""),is_error:Boolean(i.error)}]}),n.delete(s);return}case"usage.updated":e.usage=structuredClone(i.totals??i.delta??{});return;case"session.pending_prompts":{let a=Array.isArray(i.prompts)?i.prompts:[];e.promptsInQueue=a.map((d)=>({id:String(d.id??""),prompt:String(d.prompt??""),steer:d.delivery==="steer",attachmentCount:typeof d.attachmentCount==="number"?d.attachmentCount:0,userImages:Array.isArray(d.userImages)?d.userImages.filter((u)=>typeof u==="string"):void 0})).filter((d)=>d.id&&(d.prompt||d.attachmentCount));return}case"session.pending_prompt_submitted":{let a=i.prompt,d=String(a?.id??"");if(!d||e.lastQueuedPromptStartId===d)return;if(e.lastQueuedPromptStartId=d,e.promptsInQueue=e.promptsInQueue.filter((u)=>u.id!==d),i.transcriptReflected!==!0)e.messages.push({role:"user",content:[{type:"text",text:String(a?.prompt??"")}]});e.busy=!0,e.status="running",e.endedAt=void 0,n.delete(s);return}case"run.started":case"session.attached":case"session.updated":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;let a=i.session,d=typeof a?.status==="string"?a.status:t.event==="run.started"?"running":e.status,u=d==="pending"?"running":d;if(t.event==="session.updated"&&u==="running"&&e.endedAt!==void 0&&!e.busy)return;let f=e.busy;if(e.status=u,e.busy=u==="running",t.event==="run.started"){if(!f)n.delete(s);e.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;e.status=typeof i.reason==="string"?i.reason:t.event==="run.failed"?"error":t.event==="run.aborted"?"aborted":"completed",e.busy=!1,e.endedAt=Date.now(),n.delete(s);return}}}function Ne(e){return e instanceof Error&&e.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String(e.code))}function $e(e,t){return e instanceof Error&&e.name==="HubCommandError"&&e.code==="hub_command_timeout"&&(!t||e.command===t)}var C="/workspace",gi=30000,yi=2000,bi=2000,Yt="IMPORTANT: GitHub authentication is handled automatically by the infrastructure. An egress proxy transparently injects credentials into all GitHub traffic. You do NOT need to set up, configure, or manage any tokens, API keys, or credentials, and you must never run `gh auth login` or attempt to authenticate manually. "+"The GitHub CLI (`gh`) is installed and already authenticated — prefer it for GitHub work "+"(`gh pr create`, `gh pr diff`, `gh issue list`, `gh api`, ...). `git` push and pull are authenticated the same way. "+"Simply run the commands normally — credentials are injected transparently.";function We(e){if(!e)return C;if(ue.isAbsolute(e)||e.includes("\\")||e.split("/").some((n)=>!n||n==="."||n===".."))throw new g("request_failed","The handoff workspace path must stay inside the repository.");let t=ue.join(C,e);if(!t.startsWith(`${C}/`))throw new g("request_failed","The handoff workspace path must stay inside the repository.");return t}function Je(e){let t=e.metadata.cwd;return typeof t==="string"&&ue.normalize(t)===t&&(t===C||t.startsWith(`${C}/`))?t:C}function Xt(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0,n=t?.handoff&&typeof t.handoff==="object"?t.handoff:void 0;return String(n?.sourceSessionId??"").trim()}class ze extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud conversation creation was not dispatched.",{cause:e});this.name="CloudHandoffSeedRejectedError"}}class Ge extends g{constructor(){super("request_failed","The connection was interrupted and Cline could not confirm whether this message was queued. Check the cloud session before resending it.");this.name="CloudQueueUnconfirmedError"}}class en extends Error{constructor(){super("The cloud session was created, but its transcript was not persisted. This cloud runtime cannot durably seed handoff transcripts and must use @cline/core 0.0.72 or newer. Updating the cloud runtime or pod is required; retrying /cloud against this same pod will not help.");this.name="CloudHandoffSeedUnsupportedError"}}function T(e){let t=e.expiredAt?Date.parse(e.expiredAt):Number.NaN;return Number.isFinite(t)&&t<=Date.now()}function wi(e){return e.trim().startsWith("ses-")}function vi(e,t){let n=new URL(`/api/v1/session/${encodeURIComponent(t)}`,e);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.toString()}function je(e){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:e.metadata.modelId??"",modelId:e.metadata.modelId??"",repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",cwd:Je(e),workspaceRoot:C},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse(e.createdAt)||Date.now(),endedAt:T(e)&&e.expiredAt?Date.parse(e.expiredAt):void 0,status:e.status,attachedViaHub:!0}}function Fe(e,t,n){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:t,provider:"cline",model:e.metadata.modelId??"",repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",cwd:Je(e),workspaceRoot:C,...n?.trim()?{prompt:n.trim()}:{},metadata:{origin:"cloud",repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function Zt(e){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:e.status,provider:"cline",model:e.metadata.modelId??"",cwd:Je(e),workspaceRoot:C,repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",startedAt:e.createdAt,...e.lastActivityAt?{lastActivityAt:e.lastActivityAt}:{},endedAt:T(e)?e.expiredAt??void 0:e.status==="failed"?e.lastActivityAt??e.createdAt:void 0,updatedAt:e.updatedAt,...e.title?.trim()?{title:e.title.trim()}:{},metadata:{...e.title?.trim()?{title:e.title.trim()}:{},origin:"cloud",...e.metadata.provisioningPhase?{provisioningPhase:e.metadata.provisioningPhase}:{},repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function Ci(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function Si(e,t){let n=[...e??[]],s=new Set(n.map((i)=>i.id));for(let i of t)if(!s.has(i.id))n.push(i);return n}class ki{options;sessionGenerations=new Map;sessions=new Map;approvals=new Map;listeners=new Set;detachedSessions=new Set;restoredOptions=new Map;authoritativeMessages=new Map;streamingMessages=new Map;disposed=!1;connections=new Map;connectionPromises=new Map;knownSessions=new Map;unlistedSessions=new Map;pendingInitialTasks;lastListedSessions=[];discoveryRefresh;unconfirmedInnerCreates=new Set;createRequests=new Map;provisioningControllers=new Map;sendAbortTokens=new Map;titleWrites=new Map;deletingSessions=new Set;createHubClient;constructor(e){this.options=e;this.pendingInitialTasks=e.pendingInitialTasks??new Map,this.createHubClient=e.createHubClient??((t)=>new G(t))}restoreCreationOptions(e,t){if(this.restoredOptions.set(e,structuredClone(t)),this.pendingInitialTasks.has(e))this.pendingInitialTasks.set(e,{...this.pendingInitialTasks.get(e),...structuredClone(t)});let n=this.sessions.get(e);if(n)Object.assign(n.config,structuredClone(t))}seedSessionState(e,t){if(!this.sessions.has(e))this.sessions.set(e,structuredClone(t))}stateFromRecord(e){let t=je(e);return Object.assign(t.config,this.pendingInitialTasks.get(e.id),this.restoredOptions.get(e.id)),t}getSnapshot(e){let t=this.knownSessions.get(e),n=this.sessions.get(e)??(t?this.stateFromRecord(t):void 0);if(!n)return;let s=this.connections.get(e);return de({...n,sessionId:e,record:t,approvals:Array.from(this.approvals.values()).filter((i)=>i.item.sessionId===e).map((i)=>i.item),connectionState:this.detachedSessions.has(e)||this.disposed?"detached":s?.reconnectResolution||s?.rehydrationPromise?"reconnecting":s?s.connected?"connected":s.reconnecting?"reconnecting":"connecting":this.connectionPromises.has(e)?"connecting":"detached",transcriptKnown:s?.transcriptKnown??Boolean(t&&T(t))})}subscribe(e,t){let n=(s)=>{if(!t||s.sessionId===t)e(s)};return this.listeners.add(n),()=>{this.listeners.delete(n)}}publish(e){let t=e.type==="snapshot"?Object.freeze(e):de(e);for(let n of this.listeners)try{n(t)}catch(s){this.options.logger?.error?.("Cloud session subscriber failed",{error:s})}}publishSnapshot(e,t=!1,n){this.cancelScheduledSnapshot(e);let s=this.getSnapshot(e);if(s)this.publish({type:"snapshot",sessionId:e,snapshot:s,replace:t,cause:n});else this.publish({type:"removed",sessionId:e})}snapshotTimers=new Map;cancelScheduledSnapshot(e){clearTimeout(this.snapshotTimers.get(e)),this.snapshotTimers.delete(e)}scheduleSnapshot(e){if(this.disposed||this.detachedSessions.has(e)||this.snapshotTimers.has(e))return;let t=setTimeout(()=>this.publishSnapshot(e),100);t.unref?.(),this.snapshotTimers.set(e,t)}notify(e,t){let n=String(t.sessionId??"");if(e==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:n,message:String(t.message??"Cloud synchronization failed")});else this.publishSnapshot(n,e==="cloud_session_rehydrated",e==="chat_session_status"?"status":e==="chat_session_ended"?"ended":e==="tool_approval_state"?"approvals":void 0)}applyLiveEvent(e,t){let n=this.sessions.get(e);if(n)Qt(n,t,this.streamingMessages,e)}async respondApproval(e,t,n){this.assertSessionActive(e);let s=this.approvals.get(`${e}:${t}`);if(!s){if(!this.connections.has(e))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new g("request_failed","This approval was already resolved or is no longer available.")}await s.resolve(n)}async detach(e){this.detachedSessions.add(e),this.sessionGenerations.set(e,(this.sessionGenerations.get(e)??0)+1),this.connectionPromises.delete(e),this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud viewer detached")),await this.disposeConnection(e),this.publishSnapshot(e)}isCloudSession(e){return wi(e)||this.knownSessions.has(e)||this.connections.has(e)||this.sessions.get(e)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord(e){let t=this.knownSessions.get(e);return t?Zt(t):void 0}async getCrossScopeDiscoveryRecord(e){let t=this.getCachedDiscoveryRecord(e);if(!t)return;try{let s=(await this.options.api.status(e)).status?.trim();return s?{...t,status:s}:t}catch(n){if(n instanceof g&&(n.code==="session_not_found"||n.code==="session_expired")){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e);return}return t}}async list(){if(this.disposed)throw Error("Cloud session controller was disposed");let e=(r)=>this.sessions.get(r)?.title??this.knownSessions.get(r)?.title,t=new Map([...this.knownSessions.keys(),...this.sessions.keys()].map((r)=>[r,e(r)])),n=(r)=>{let a=e(r.id);if(this.titleWrites.has(r.id)||a!==t.get(r.id))r.title=a??r.title},s=await this.resolveActiveOrganizationId(),i=(await this.options.api.list(s)).map((r)=>this.preserveConnectedRuntimeModel(r));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=i;for(let r of i)n(r),this.knownSessions.set(r.id,r),this.unlistedSessions.delete(r.id);await Promise.all(Array.from(this.unlistedSessions.keys(),(r)=>this.getCrossScopeDiscoveryRecord(r)));let o=await Promise.all(i.map(async(r)=>{if(r.status!=="provisioning")return r;let a=await this.options.api.status(r.id).catch(()=>{return}),d=a?.status?.trim();if(!d)return r;return{...r,status:d,metadata:{...r.metadata,...be(a?.phase)?{provisioningPhase:a?.phase}:{},...a?.statusReason?.trim()?{statusReason:a.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let r of o){n(r),this.knownSessions.set(r.id,r);let a=this.sessions.get(r.id);if(a)a.title=r.title;if(a?.status==="provisioning"&&r.status!=="provisioning")a.status=r.status;let d=this.connections.get(r.id);if(d)d.remote=r;let u=T(r);if(u||r.status==="failed"||r.status==="suspended"){if(a)a.busy=!1,a.status=u?"expired":r.status,a.endedAt=u?Date.parse(r.expiredAt??"")||Date.now():Math.max(a.endedAt??0,Date.parse(r.lastActivityAt??r.createdAt)||0)||void 0;if(d)this.disposeConnection(r.id).catch(()=>{return})}}this.lastListedSessions=o;for(let r of o)if(this.sessions.has(r.id))this.publishSnapshot(r.id);return de(o)}async handoffTargetExists(e){try{return await this.options.api.status(e),!0}catch(t){if(t instanceof g&&(t.code==="session_not_found"||t.code==="session_expired"))return!1;throw t}}preserveConnectedRuntimeModel(e){let t=this.connections.get(e.id)?.remote.metadata,n=t?.cwd??this.knownSessions.get(e.id)?.metadata.cwd;return{...e,metadata:{...e.metadata,...t?.modelId?{modelId:t.modelId}:{},...n?{cwd:n}:{}}}}async resolveActiveOrganizationId(e){return await this.options.getActiveOrganizationId?.(e)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listModels(){if(this.disposed)throw Error("Cloud session manager was disposed");let e=await this.resolveActiveOrganizationId({fresh:!0}),t=await Wt(this.options.apiBaseUrl,{isOrganizationSession:Boolean(e)});if(this.disposed)throw Error("Cloud session manager was disposed");return t}async prepareHandoffRepository(e){let t=await this.resolveActiveOrganizationId(),n=await this.options.api.listRepositories(t);if(!n.connected)throw new g("github_not_connected","Connect GitHub before handing this session off to cloud.",n.connectUrl);let s=(i)=>i.trim().replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();if(!n.repositories.some((i)=>s(i.url)===s(e)))throw new g("github_not_connected",`The GitHub integration cannot access ${e}. Grant repository access before handing off.`,n.connectUrl);return t?{organizationId:t}:{}}async listBranches(e,t={}){return await this.options.api.listBranches(e,await this.resolveActiveOrganizationId(),t)}async listForDiscovery(e={}){let t=this.discoveryRefresh??this.list().finally(()=>{if(this.discoveryRefresh===t)this.discoveryRefresh=void 0});this.discoveryRefresh=t;let n=this.lastListedSessions;if(e.timeoutMs===void 0)n=await t;else{let o,r=await Promise.race([t.then((a)=>({value:a}),(a)=>{if(!(a instanceof g&&a.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:a});return{value:this.lastListedSessions}}),new Promise((a)=>{o=setTimeout(()=>a({value:this.lastListedSessions}),Math.max(0,e.timeoutMs??0))})]);if(o)clearTimeout(o);n=r.value}return[...new Map([...this.unlistedSessions.values(),...n].map((o)=>[o.id,o])).values()].map((o)=>{let r=Zt(o),a=this.sessions.get(o.id);if(!a)return r;let d=a.title?.trim()||o.title?.trim();return{...r,status:a.status,prompt:a.prompt,endedAt:a.endedAt!==void 0?new Date(a.endedAt).toISOString():r.endedAt,metadata:{...r.metadata??{},title:qe({sessionId:o.id,metadata:d?{title:d}:void 0,prompt:a.prompt,messages:a.messages})}}})}async create(e){let t=e.requestId?.trim();if(!t)return await this.createOnce(e);let n=this.createRequests.get(t);if(n)return await n;let s=this.createOnce(e).finally(()=>{if(this.createRequests.get(t)===s)this.createRequests.delete(t)});return this.createRequests.set(t,s),await s}trackProvisioningController(e,t){let n=this.provisioningControllers.get(e);if(!n)n=new Set,this.provisioningControllers.set(e,n);return n.add(t),()=>{if(n.delete(t),n.size===0)this.provisioningControllers.delete(e)}}abortProvisioningControllers(e,t){let n=this.provisioningControllers.get(e);if(!n?.size)return!1;for(let s of n)s.abort(t);return!0}async waitUntilReady(e){this.detachedSessions.delete(e),this.assertSessionActive(e);let t=new AbortController,n=this.trackProvisioningController(e,t);try{await this.options.api.waitUntilReady(e,AbortSignal.any([t.signal,AbortSignal.timeout(610000)])),t.signal.throwIfAborted(),this.assertSessionActive(e),await this.refreshKnownSession(e)}finally{n()}}async seedHandoff(e,t){We(t.workspaceRelativePath),this.detachedSessions.delete(e);let n=await this.ensureConnection(e,{createInner:!0,handoffSeed:t});if(!n.innerSessionId)throw Error("Cloud Hub did not return an inner session id");return{innerSessionId:n.innerSessionId}}async verifyHandoffTranscript(e,t,n={}){let s=await this.ensureConnection(e),i=s.innerSessionId;if(!i)throw Error("Cloud Hub did not return an inner session id");let o=await s.client.command("session.messages",{sessionId:i},i);this.assertSessionActive(e,s);let r=o.payload?.messages;if(!Array.isArray(r))throw Error("Cloud runtime returned no transcript after seeding.");if(t.length>0&&r.length===0)throw new en;if(!(n.allowAppendedMessages?r.length>=t.length&&fe(t,r.slice(0,t.length)):fe(t,r)))throw new he(t.length,r.length);s.transcriptKnown=!0;let d=this.sessions.get(e);if(d)d.messages=structuredClone(r),this.authoritativeMessages.set(e,structuredClone(r)),this.streamingMessages.delete(e),this.publishSnapshot(e,!0)}async createOnce(e){if(this.disposed)throw Error("Cloud session manager was disposed");let t=We(e.workspaceRelativePath),n=e.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):e.organizationId??void 0,s=e.handoff,i=!s,o=await this.options.api.create({...e,organizationId:n,...s&&{handoff:{...s,onOuterSessionCreated:async(h,l)=>{i=l?.created===!0,await s.onOuterSessionCreated(h,l)}}}});if(!o?.sessionId?.trim())throw new g("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(i&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(o.sessionId,o.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let r={id:o.sessionId,sandboxType:e.sandboxType,status:o.status,sandboxUrl:o.sandboxUrl,repoContext:{repoUrl:e.repoUrl,...e.branch?.trim()?{branch:e.branch.trim()}:{}},metadata:{modelId:e.modelId,cwd:t},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.knownSessions.set(r.id,r),this.unlistedSessions.set(r.id,r);let{autoApproveTools:a,thinking:d,reasoningEffort:u}=e;this.pendingInitialTasks.set(r.id,{autoApproveTools:a,thinking:d,reasoningEffort:u});let f=this.stateFromRecord(r);f.prompt=e.initialPrompt?.trim()||void 0,f.config.mode=e.mode??"act",this.sessions.set(r.id,f);let c;try{if(e.handoff){let h=await e.handoff.resolveMessages();this.assertSessionActive(r.id),c=(await this.seedHandoff(r.id,{sourceSessionId:e.handoff.sourceSessionId,messages:h,mode:e.mode,workspaceRelativePath:e.workspaceRelativePath,config:{autoApproveTools:e.autoApproveTools,thinking:e.thinking,reasoningEffort:e.reasoningEffort},onSeeding:e.handoff.onSeeding})).innerSessionId}}catch(h){if(this.disposed&&i&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(r.id,o.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw h}return this.assertSessionActive(r.id),this.notify("chat_session_status",{sessionId:r.id,status:f.status}),{sessionId:r.id,origin:"cloud",executionTarget:"cloud",status:r.status,provider:"cline",model:e.modelId,repoUrl:e.repoUrl,branch:e.branch??"",cwd:t,workspaceRoot:C,...c?{innerSessionId:c}:{},...f.prompt?{prompt:f.prompt}:{}}}async deleteProvisionedSessionAfterDispose(e,t,n){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),await this.options.api.delete(e,t).then(()=>n?.(e)).catch((s)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:e,error:s})})}async attach(e,t){let n=this.sessionGenerations.get(e)??0;if(this.detachedSessions.delete(e),t)this.restoreCreationOptions(e,t);let s=await this.ensureKnownSession(e);if(this.assertSessionActive(e),n!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has(e))this.sessions.set(e,this.stateFromRecord(s));if(s.status==="provisioning"||s.status==="failed")return Fe(s,s.status,this.sessions.get(e)?.prompt);if(T(s))return await this.disposeConnection(e),await this.attachExpired(s);let i;try{i=await this.ensureConnection(e)}catch(a){let d=await this.refreshKnownSession(e);if(d&&T(d))return await this.disposeConnection(e),await this.attachExpired(d);throw a}await this.ensureAttached(i);let o=i.remote,r=this.sessions.get(e);return Fe(o,r?.status??o.status,r?.prompt)}async send(e,t,n,s,i){let o=this.sendAbortTokens.get(e),r=this.knownSessions.get(e);if(r&&T(r))throw new g("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let a=await this.ensureConnection(e,{createInner:!0}),d=()=>this.disposed||a.disposed||this.deletingSessions.has(e)||this.sendAbortTokens.get(e)!==o,u=()=>{if(d())throw Error("Cloud session prompt cancelled")};if(u(),await a.reconnectResolution,u(),await this.ensureAttached(a),await a.reconnectResolution,u(),!a.transcriptKnown)await this.rehydrateAfterTransportDrop(e,a);u(),await this.updateModel(a,s),await a.reconnectResolution,u();let f=a.innerSessionId;if(!f)throw Error("Cloud Hub session was not initialized");let c=this.sessions.get(e),h=n??(c?.busy?"queue":void 0),l=J(c?.messages??[],c?.promptsInQueue??[],t),p=h!=="queue"&&h!=="steer",m=c&&h!=="queue"?{role:"user",content:[{type:"text",text:t}]}:void 0;if(c&&m)c.messages=[...c.messages,m];let y=()=>{if(c&&m)c.messages=c.messages.filter((b)=>b!==m),this.publishSnapshot(e)};if(c&&p){let b=c.status!=="running";if(c.busy=!0,c.status="running",c.prompt||=t,b)this.publishSnapshot(e,!1,"status")}let w=this.knownSessions.get(e);if(w&&!w.title?.trim()&&!this.titleWrites.has(e)){let b=st(t);if(b){if(w.title=b,c)c.title=b;let R=this.options.api.updateTitle?.(e,b).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get(e)===R)this.titleWrites.delete(e)});if(R)this.titleWrites.set(e,R)}}let v=new Set,P=!1,H=()=>{if(P||d())return;P=!0,this.publish({type:"prompt_accepted",sessionId:e,prompt:t,delivery:h})};try{let b=await a.client.command("session.send_input",{prompt:t,delivery:h,...i?.length?{attachments:{userImages:i}}:{}},f,{timeoutMs:h==="queue"?gi:null,onDispatch:(M)=>{v.add(M),a.pendingInputs??=new Map,a.pendingInputs.set(M,{clientId:a.client.getClientId(),ownsBusyState:p,accept:H})},beforeDispatch:()=>{if(u(),a.innerSessionId!==f)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.")}});H();let R=h==="queue"||h!=="steer"&&b.payload?.result===void 0;if(R)y();return{sessionId:e,ok:!0,...R?{queued:!0}:{},result:b.payload?.result}}catch(b){if(d())throw y(),b;if(Ne(b)||$e(b,"session.send_input")){let R;try{R=await this.rehydrateAfterTransportDrop(e,a)}catch(V){if(u(),y(),c&&p)c.busy=!1,c.status="error";if(h==="queue")throw new Ge;throw V}if(u(),h==="queue")throw new Ge;if(h==="steer")throw new g("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(J(R.messages,Si(R.prompts,R.submittedPrompts),t)<=l)throw new g("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:e,ok:!0,...h==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:R.status}}if(y(),c&&p)c.busy=!1,c.status="error";throw this.publishSnapshot(e),b}finally{for(let b of v)a.pendingInputs?.delete(b)}}async updateModel(e,t){let n=t?.trim();if(!n||e.remote.metadata.modelId===n)return;let s=e.innerSessionId;if(!s)throw Error("Cloud Hub session was not initialized");await e.client.command("session.update_connection",{sessionId:s,updates:{modelId:n}},s,{beforeDispatch:()=>{if(this.assertSessionActive(e.remote.id,e),e.innerSessionId!==s)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive(e.remote.id,e),this.applyModel(e,n)}applyModel(e,t){e.remote.metadata.modelId=t;let n=this.sessions.get(e.remote.id);if(n)n.config.model=t,n.config.modelId=t}async rehydrateAfterTransportDrop(e,t){if(this.assertSessionActive(e,t),t.rehydrationPromise)return t.rehydrationRerunRequested=!0,await t.rehydrationPromise;let n=(async()=>{let s;do t.rehydrationRerunRequested=!1,s=await this.performTransportRehydration(e,t),this.assertSessionActive(e,t);while(t.rehydrationRerunRequested&&!this.disposed);return s})().finally(()=>{if(t.rehydrationPromise===n)t.rehydrationPromise=void 0,this.publishSnapshot(e)});return t.rehydrationPromise=n,await n}async performTransportRehydration(e,t){this.assertSessionActive(e,t);let n=t.innerSessionId;if(!n)throw Error("Cloud Hub session was not initialized");t.bufferingEvents=!0,t.bufferedEvents=[],t.bufferedEventsDropped=0;try{await this.ensureAttached(t),this.assertSessionActive(e,t);let s=await t.client.command("session.get",{includeSnapshot:!0},n);this.assertSessionActive(e,t);let i=s.payload?.session&&typeof s.payload.session==="object"&&!Array.isArray(s.payload.session)?s.payload.session:void 0;this.applySessionModel(t,i);let o=this.sessions.get(e),r=this.authoritativeMessages.get(e)??[],a=String(i?.status??o?.status??"running").trim(),d=a==="pending"?"running":a;if(d==="running"&&!t.transcriptKnown&&!t.pendingInputs?.size)t.externalRun??={progressHydrated:!0};let u=()=>t.client.command("session.messages",{sessionId:n},n),f=await u().catch((b)=>{if(!$e(b,"session.messages"))throw b;return this.assertSessionActive(e,t),u()});if(this.assertSessionActive(e,t),!Array.isArray(f.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let c=f.payload.messages,h=t.bufferedEventsDropped+t.bufferedEvents.length,l=await t.client.command("session.pending_prompts",{sessionId:n},n).catch(()=>{return});this.assertSessionActive(e,t);let p=t.bufferedEventsDropped+t.bufferedEvents.length;if(o){let b=o.status!==d;if(this.authoritativeMessages.set(e,structuredClone(c)),o.messages=structuredClone(c),this.streamingMessages.delete(e),o.status=d,o.busy=d==="running",b)if(d==="completed"||d==="failed"||d==="aborted")o.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:e,reason:d==="failed"?"error":d});else this.notify("chat_session_status",{sessionId:e,status:d})}let m=l!==void 0&&l.ok!==!1&&Array.isArray(l.payload?.prompts),y=m?this.applyQueueSnapshot(e,l):void 0;t.transcriptKnown=!0;let w=c;this.assertSessionActive(e,t),this.notify("cloud_session_rehydrated",{sessionId:e,status:d,transcriptKnown:!0,messages:w}),this.assertSessionActive(e,t);let v=t.bufferedEvents,P=Le(v),H=Kt(v,c,{queueSnapshotApplied:m,queueSnapshotEventCutoff:Math.max(0,p-t.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,h-t.bufferedEventsDropped),baselineMessages:r});t.bufferedEvents=[],t.bufferingEvents=!1,t.syncFailureNotified=!1;for(let b of H)this.forwardEvent(e,t,b);return{status:d,messages:c,prompts:y,submittedPrompts:P}}catch(s){let i=t.bufferedEvents;t.bufferedEvents=[],t.bufferingEvents=!1,this.assertSessionActive(e,t);for(let o of i)this.forwardEvent(e,t,o);if(!t.syncFailureNotified)t.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:e,message:s instanceof Error?s.message:String(s)});throw s}}async abort(e){if(this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud session prompt cancelled")))return{sessionId:e,ok:!0};let t=await this.ensureConnection(e),n=()=>{if(this.disposed||t.disposed)throw Error("Cloud session connection was disposed")};if(n(),await t.client.connect(),await t.reconnectResolution,n(),await this.resolveInnerSession(e,t),t.innerSessionId){await this.ensureAttached(t),await t.reconnectResolution,n();let i=t.innerSessionId;if(!i)throw Error("Cloud Hub session was not initialized");await t.client.command("run.abort",{sessionId:i},i,{beforeDispatch:()=>{if(n(),t.innerSessionId!==i)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}n();let s=this.sessions.get(e);if(s)s.busy=!1,s.status="aborted";return this.publishSnapshot(e),{sessionId:e,ok:!0}}async pendingPrompts(e){if(this.knownSessions.get(e)?.status==="provisioning")return{sessionId:e,promptsInQueue:[]};if(!(await this.ensureConnection(e)).innerSessionId)return{sessionId:e,promptsInQueue:[]};let n=await this.queueCommand(e,"session.pending_prompts",{});return{sessionId:e,promptsInQueue:this.applyQueueSnapshot(e,n)}}async updatePendingPrompt(e,t,n){let s=await this.queueCommand(e,"session.update_pending_prompt",{promptId:t,...n});return{sessionId:e,updated:s.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot(e,s)}}async removePendingPrompt(e,t){let n=await this.queueCommand(e,"session.remove_pending_prompt",{promptId:t});return{sessionId:e,removed:n.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot(e,n)}}async queueCommand(e,t,n){let s=await this.ensureConnection(e),i=s.innerSessionId;if(!i)throw Error("Cloud Hub session was not initialized");await s.client.connect(),await s.reconnectResolution,await this.ensureAttached(s),await s.reconnectResolution;let o=await s.client.command(t,{sessionId:i,...n},i,{beforeDispatch:()=>{if(this.assertSessionActive(e,s),s.innerSessionId!==i)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive(e,s),o}applyQueueSnapshot(e,t){if(!Array.isArray(t.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let s=t.payload.prompts.map((o)=>({id:typeof o.id==="string"?o.id:"",prompt:typeof o.prompt==="string"?o.prompt:"",steer:o.delivery==="steer",attachmentCount:typeof o.attachmentCount==="number"?o.attachmentCount:0,userImages:Array.isArray(o.userImages)?o.userImages.filter((r)=>typeof r==="string"):void 0})).filter((o)=>o.id),i=this.sessions.get(e);if(i)i.promptsInQueue=s;return this.publishSnapshot(e,!1,"queue"),s}async readMessages(e){let t=this.knownSessions.get(e);if(t?.status==="provisioning"||t?.status==="failed")return[];if(t&&T(t))return await this.loadArchivedMessages(t)??[];try{let n=await this.ensureConnection(e);if(!n.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop(e,n)).messages}catch(n){let s=await this.refreshKnownSession(e)??t;if(s){let i=await this.loadArchivedMessages(s).catch(()=>null);if(i!==null)return i}throw n}}async updateTitle(e,t){let n=this.titleWrites.get(e),s=(async()=>{await n?.catch(()=>{}),this.assertSessionActive(e),await this.options.api.updateTitle(e,t);let i=this.knownSessions.get(e);if(i)i.title=t;let o=this.sessions.get(e);if(o)o.title=t;this.publishSnapshot(e)})();this.titleWrites.set(e,s);try{await s}finally{if(this.titleWrites.get(e)===s)this.titleWrites.delete(e)}}async delete(e){this.deletingSessions.add(e),this.abortProvisioningControllers(e);try{let t=this.connectionPromises.get(e);if(t)await t.catch(()=>{return});await this.disposeConnection(e);try{await this.options.api.delete(e)}catch(n){let s=n instanceof g?n.code:"";if(s!=="session_not_found"&&s!=="session_expired")throw n}this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),this.authoritativeMessages.delete(e),this.restoredOptions.delete(e),this.publish({type:"removed",sessionId:e}),this.sendAbortTokens.delete(e);for(let[n,s]of this.approvals)if(s.item.sessionId===e)this.approvals.delete(n)}finally{this.deletingSessions.delete(e)}}async dispose(){this.disposed=!0;for(let t of this.snapshotTimers.keys())this.cancelScheduledSnapshot(t);this.sendAbortTokens.clear();for(let t of this.provisioningControllers.values())for(let n of t)n.abort();this.provisioningControllers.clear();let e=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[t,n]of this.approvals)if(e.has(n.item.sessionId))this.approvals.delete(t);for(let t of e)this.sessions.delete(t),this.knownSessions.delete(t),this.publish({type:"removed",sessionId:t});if(this.knownSessions.clear(),this.unlistedSessions.clear(),!this.options.pendingInitialTasks)this.pendingInitialTasks.clear();this.listeners.clear(),await Promise.allSettled(Array.from(this.connections.keys()).map((t)=>this.disposeConnection(t)))}async attachExpired(e){let t=this.sessions.get(e.id)??je(e);return t.busy=!1,t.status="expired",this.sessions.set(e.id,t),await this.loadArchivedMessages(e).catch(()=>{return}),Fe(e,"expired")}async loadArchivedMessages(e){let t=this.sessionGenerations.get(e.id),n=await this.options.api.history(e.id);if(this.assertSessionActive(e.id),this.sessionGenerations.get(e.id)!==t)throw Error("Cloud session attachment changed while loading history");if(n===null)return null;let s=this.sessions.get(e.id)??je(e);return s.messages=structuredClone(n),this.sessions.set(e.id,s),this.authoritativeMessages.set(e.id,structuredClone(s.messages)),this.publishSnapshot(e.id,!0),n}async refreshKnownSession(e){let t=await this.resolveActiveOrganizationId(),n=await this.options.api.list(t).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!n)return this.knownSessions.get(e);for(let s of n)this.knownSessions.set(s.id,s);return n.find((s)=>s.id===e)}async ensureKnownSession(e){let t=this.knownSessions.get(e);if(t)return t;let n=(await this.list()).find((s)=>s.id===e);if(!n)throw new g("session_not_found",`Cloud session ${e} was not found.`);return this.knownSessions.get(e)??structuredClone(n)}assertSessionActive(e,t){if(this.disposed||t?.disposed||this.detachedSessions.has(e)||t?.generation!==void 0&&t.generation!==(this.sessionGenerations.get(e)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has(e))throw new g("session_not_found","This cloud session is being deleted.")}async ensureConnection(e,t={}){let n=this.sessionGenerations.get(e)??0,s=()=>{if(this.assertSessionActive(e),n!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during connection")};s();let i=this.connectionPromises.get(e),o=i?await i:this.connections.get(e);if(o?.remote.status==="suspended")return await this.disposeConnection(e),s(),await this.ensureConnection(e,t);if(o){if(this.assertSessionActive(e,o),await o.reconnectResolution,this.assertSessionActive(e,o),!o.innerSessionId)await o.client.connect(),await o.reconnectResolution,this.assertSessionActive(e,o),await this.resolveInnerSession(e,o,Boolean(t.handoffSeed)),this.assertSessionActive(e,o);if(t.handoffSeed&&o.innerSessionId)await this.assertHandoffConnectionReusable(o,t.handoffSeed);if(t.createInner&&!o.innerSessionId)await this.createInnerSession(o,t.handoffSeed);return this.assertSessionActive(e,o),o}let r=(async()=>{let a=await this.ensureKnownSession(e);if(s(),!this.pendingInitialTasks.has(e)&&(a.sandboxType==="resumable"||a.metadata.sandboxType==="resumable"||a.status==="suspended")){let c=await this.options.api.status(e).catch(async(l)=>{if(!(l instanceof g?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 s(),await this.refreshKnownSession(e).catch(()=>{return})});if(s(),c?.status)a.status=c.status;let h=this.sessions.get(e);if(h?.status==="suspended"&&["provisioning","ready","active"].includes(a.status))h.status=a.status,h.busy=!1,h.endedAt=void 0}if(a.status==="suspended"){let c=new AbortController,h=this.trackProvisioningController(e,c);try{try{a=await this.options.api.resume(e,c.signal)}catch(p){if(!(p instanceof g)||p.status!==409)throw p;s(),c.signal.throwIfAborted();let m=await this.options.api.status(e,{signal:c.signal});if(m.status!=="provisioning"&&m.status!=="ready"&&m.status!=="active")throw p;a={...a,status:m.status}}s(),c.signal.throwIfAborted(),this.knownSessions.set(e,a);let l=this.sessions.get(e);if(l)l.status=a.status,l.busy=!1,l.endedAt=void 0;this.publishSnapshot(e,!1,"status")}finally{h()}}if(a.status==="provisioning"){let c=new AbortController,h=this.trackProvisioningController(e,c);try{if(await this.options.api.waitUntilReady(e,c.signal,({phase:p})=>{a.metadata.provisioningPhase=p,this.notify("chat_session_status",{sessionId:e,status:"provisioning",phase:p})}),this.disposed)throw Error("Cloud session manager was disposed");if(a=await this.refreshKnownSession(e)??a,c.signal.throwIfAborted(),a.status==="provisioning")a.status="ready";let l=this.sessions.get(e);if(l?.status==="provisioning")l.status="idle",l.busy=!1,l.endedAt=void 0}catch(l){if(l instanceof g&&l.code==="session_failed"){if(a.status="failed",a.metadata.statusReason=l.detail,a.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set(e,a);let p=this.sessions.get(e);if(p)p.status="error";this.notify("chat_session_status",{sessionId:e,status:"error"})}throw l}finally{h()}}if(s(),a.status==="failed")throw new g("session_failed",a.metadata.statusReason||"The cloud sandbox could not be prepared.");if(T(a))throw new g("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set(e,this.sessions.get(e)??this.stateFromRecord(a));let d,u=0,f=this.createHubClient({url:vi(this.options.apiBaseUrl,e),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${e}-${mi()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:C,cwd:C,resolveConnectionHeaders:async()=>{s();let c=u>0;if(u+=1,d)d.connected=!1,d.reconnecting=c,this.publishSnapshot(e);if(c){let l=d;if(l&&!l.disposed){l.transcriptKnown=!1,l.innerSessionId=void 0;let p=(async()=>{if(await this.resolveInnerSession(e,l),l.innerSessionId)await this.rehydrateAfterTransportDrop(e,l)})().catch(()=>this.disposeConnectionIfSessionGone(e,l)).finally(()=>{if(l.reconnectResolution===p)l.reconnectResolution=void 0,l.connected=l.transcriptKnown,this.publishSnapshot(e)});l.reconnectResolution=p}}let h=await this.options.getAuthToken();if(!h?.trim())throw new g("authentication_required","Sign in to Cline to reconnect this cloud session.");return s(),{Authorization:`Bearer ${h.trim()}`}}});d={generation:n,remote:a,client:f,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},d.unsubscribe=f.subscribe(()=>{},{sessionId:a.metadata.taskId?.trim()||e}),this.connections.set(e,d);try{if(await f.connect(),d.connected=!0,this.publishSnapshot(e),this.assertSessionActive(e,d),await this.resolveInnerSession(e,d,Boolean(t.handoffSeed)),this.assertSessionActive(e,d),t.handoffSeed&&d.innerSessionId)await this.assertHandoffConnectionReusable(d,t.handoffSeed);if(t.createInner&&!d.innerSessionId)await this.createInnerSession(d,t.handoffSeed);return this.assertSessionActive(e,d),d}catch(c){if(Ne(c)&&!this.disposed&&!d.disposed&&!this.deletingSessions.has(e))throw c;if(this.connections.get(e)===d)this.connections.delete(e);if(d.disposed=!0,d.unsubscribe(),!this.disposed&&n===(this.sessionGenerations.get(e)??0))this.clearPendingApprovals(e);throw await f.dispose().catch(()=>{return}),c}})().finally(()=>{if(this.connectionPromises.get(e)===r)this.connectionPromises.delete(e)});return this.connectionPromises.set(e,r),await r}async resolveInnerSession(e,t,n=!1){if(this.assertSessionActive(e,t),t.innerSessionId)return;let s=t.remote.metadata.taskId?.trim(),i;if(s)try{let a=await t.client.command("session.get",{sessionId:s},s);this.assertSessionActive(e,t),i=a.payload?.session&&typeof a.payload.session==="object"&&!Array.isArray(a.payload.session)?a.payload.session:void 0}catch(a){if(!we(a))throw a}else{let a=await t.client.command("session.list",{limit:100});this.assertSessionActive(e,t),i=re(a.payload).filter(ae).sort((d,u)=>Ue(u)-Ue(d))[0]}let o=String(i?.sessionId??"").trim();if(!o||!i){if(!n&&!this.pendingInitialTasks.has(e))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}if(t.remote.sandboxType==="resumable"||t.remote.metadata.sandboxType==="resumable")await this.restoreSavedInnerSession(t,o,i),this.assertSessionActive(e,t);this.pendingInitialTasks.delete(e),t.innerSessionId=o,this.subscribeToInnerSession(e,t);let r=De(i);if(r)this.applyModel(t,r);await this.ensureAttached(t)}async restoreSavedInnerSession(e,t,n){let s=()=>e.client.command("session.update_connection",{sessionId:t,updates:{}},t);try{await s();return}catch(p){if(!(we(p)||p instanceof Error&&p.code==="command_failed"&&p.message===`session not found: ${t}`))throw p}this.assertSessionActive(e.remote.id,e);let i=await e.client.command("session.messages",{},t);this.assertSessionActive(e.remote.id,e);let o=i.payload?.messages;if(!Array.isArray(o)||o.length===0)throw Error("The saved conversation is empty or unavailable.");let r=n.metadata??{},a=n.runtimeOptions??{},d=this.sessions.get(e.remote.id)?.config,u=Object.hasOwn(r,"thinking")?r.thinking:d?.thinking,f=Object.hasOwn(r,"reasoningEffort")?r.reasoningEffort:d?.reasoningEffort,c=typeof r.autoApproveTools==="boolean"?r.autoApproveTools:d?.autoApproveTools,h=n.cwd??n.workspaceRoot??C,l=n.workspaceRoot??C;try{let p=await e.client.command("session.create",{workspaceRoot:l,cwd:h,initialMessages:o,metadata:{...r,interactive:!0},sessionConfig:{sessionId:t,providerId:r.provider??"cline",modelId:r.model??r.modelId??e.remote.metadata.modelId,workspaceRoot:l,cwd:h,systemPrompt:a.systemPrompt??r.systemPrompt??"",mode:a.mode??r.mode??"act",...typeof u==="boolean"?{thinking:u}:{},...typeof f==="string"?{reasoningEffort:f}:{},...r.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:a,...typeof c==="boolean"?{toolPolicies:{"*":{autoApprove:c}}}:{}});if(this.assertSessionActive(e.remote.id,e),(p.payload?.session?.sessionId??p.payload?.sessionId)!==t)throw Error("Cloud Hub did not restore the requested session.")}catch(p){if(p?.code!=="session_already_exists")throw p;this.assertSessionActive(e.remote.id,e),await s()}}async assertHandoffConnectionReusable(e,t){let n=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let s=re(n.payload).filter(ae),[i]=s;if(s.length!==1||String(i?.sessionId??"").trim()!==e.innerSessionId||Xt(i)!==t.sourceSessionId)throw new g("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.")}async createInnerSession(e,t){if(this.assertSessionActive(e.remote.id,e),e.innerSessionCreation){if(await e.innerSessionCreation,t)await this.assertHandoffConnectionReusable(e,t);return}let n=(async()=>{if(t&&await this.adoptExistingHandoffSession(e,t)){this.unconfirmedInnerCreates.delete(e.remote.id);return}if(t?.recoverOnly||this.unconfirmedInnerCreates.has(e.remote.id))throw new g("request_failed","Cloud conversation creation is still unconfirmed. Wait for it to appear before trying again.");await this.createInnerSessionOnce(e,t)})().finally(()=>{e.innerSessionCreation=void 0});return e.innerSessionCreation=n,await n}async adoptExistingHandoffSession(e,t){let n=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let s=re(n.payload).filter(ae);if(s.length===0)return!1;let[i]=s,o=String(i?.sessionId??"").trim();if(s.length!==1||!o||Xt(i)!==t.sourceSessionId)throw new g("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return e.innerSessionId=o,this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,i),await this.ensureAttached(e),!0}async createInnerSessionOnce(e,t){let n=e.remote.metadata.modelId?.trim();if(!n)throw Error("Cloud session is missing its model id");let s=this.sessions.get(e.remote.id),i=We(t?.workspaceRelativePath),o=t?.mode??"act";try{await t?.onSeeding?.(),this.assertSessionActive(e.remote.id,e)}catch(y){if(t)throw new ze(y);throw y}let r=`cline/${(e.remote.metadata.taskId?.trim()||e.remote.id).slice(-8).toLowerCase()}`,a=e.remote.sandboxType==="resumable"||e.remote.metadata.sandboxType==="resumable",d=`${Yt}
|
|
16
16
|
|
|
17
|
-
Do all work for this task on the branch \`${
|
|
17
|
+
Do all work for this task on the branch \`${r}\`: 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. `+(a?"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 \`${r}\` 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 ${r}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks.",u=t?.config?.thinking??s?.config.thinking,f=t?.config?.reasoningEffort??s?.config.reasoningEffort,c=!1,h=e.client.command("session.create",{workspaceRoot:C,cwd:i,...t?{initialMessages:t.messages}:{},sessionConfig:{...e.remote.metadata.taskId?.trim()?{sessionId:e.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:n,workspaceRoot:C,cwd:i,systemPrompt:t?`${Yt}
|
|
18
18
|
|
|
19
|
-
This session was handed off from a local workspace to a fresh Linux clone of ${e.remote.repoContext.repoUrl??"the repository"}@${e.remote.repoContext.branch??"the selected branch"} at ${C}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(
|
|
19
|
+
This session was handed off from a local workspace to a fresh Linux clone of ${e.remote.repoContext.repoUrl??"the repository"}@${e.remote.repoContext.branch??"the selected branch"} at ${C}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(i===C?"":`
|
|
20
20
|
|
|
21
|
-
Continue from the original repository subdirectory at ${
|
|
21
|
+
Continue from the original repository subdirectory at ${i}.`):d,mode:o,enableTools:!0,...typeof u==="boolean"?{thinking:u}:{},...typeof f==="string"?{reasoningEffort:f}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:n,interactive:!0,thinking:u??null,reasoningEffort:u===!1?null:f??null,...t?{handoff:{from:"local",sourceSessionId:t.sourceSessionId,outerSessionId:e.remote.id}}:{}},runtimeOptions:{mode:o},modelSelection:{provider:"cline",model:n},toolPolicies:{"*":{autoApprove:(t?.config?.autoApproveTools??s?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive(e.remote.id,e),onDispatch:()=>{c=!0}}),l;try{l=await h}catch(y){if(t&&!c)throw new ze(y);if(t&&($e(y,"session.create")||Ne(y)))this.unconfirmedInnerCreates.add(e.remote.id);throw y}this.assertSessionActive(e.remote.id,e);let p=l.payload?.session&&typeof l.payload.session==="object"?l.payload.session:void 0,m=String(p?.sessionId??l.payload?.sessionId??"").trim();if(!m){if(t)this.unconfirmedInnerCreates.add(e.remote.id);throw Error("Cloud Hub did not return an inner session id")}if(this.unconfirmedInnerCreates.delete(e.remote.id),this.pendingInitialTasks.delete(e.remote.id),e.innerSessionId=m,e.remote.metadata.cwd=i,s)s.config.cwd=i,s.config.mode=o;this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,p),e.transcriptKnown=!t}handleEvent(e,t,n){if(this.disposed||t.disposed)return;if(t.innerSessionId&&n.sessionId&&n.sessionId!==t.innerSessionId)return;let s=n.eventId?.trim();if(s&&!(n.event==="approval.requested"&&n.sequence===void 0)){if(t.seenEventIds.has(s))return;t.seenEventIds.add(s);while(t.seenEventIds.size>bi){let i=t.seenEventIds.values().next().value;if(i)t.seenEventIds.delete(i)}}if(t.bufferingEvents){if(t.bufferedEvents.push(n),t.bufferedEvents.length>yi)t.bufferedEvents.shift(),t.bufferedEventsDropped+=1,this.options.logger?.log("Cloud sync event buffer reached its limit",{sessionId:e,severity:"warn"});return}this.forwardEvent(e,t,n)}forwardEvent(e,t,n){if(this.disposed||t.disposed)return;if(n.event==="session.attached"||n.event==="session.updated"||n.event==="session.created")this.applySessionModel(t,n.payload?.session);if(n.event==="approval.requested"){this.handleApprovalRequested(e,t,n);return}if(n.event==="approval.resolved"){let r=String(n.payload?.approvalId??"").trim();if(r)this.removeApproval(e,r);return}if(n.event==="run.started"){let r=this.sessions.get(e)?.busy,a=n.payload?.requestId,d=typeof a==="string"?t.pendingInputs?.get(a):void 0;if(d&&n.payload?.clientId===d.clientId){if(d.accept(),d.ownsBusyState)t.externalRun=void 0}else if(typeof n.payload?.clientId==="string")t.externalRun??={progressHydrated:Boolean(r)}}let s=t.externalRun,i=n.event==="run.completed"||n.event==="run.failed"||n.event==="run.aborted",o=s&&!s.progressHydrated&&(n.event==="assistant.delta"||n.event==="reasoning.delta"||n.event==="tool.started");if(s&&(o||i)){if(s.progressHydrated=!0,i)t.externalRun=void 0;let r=Boolean(t.rehydrationPromise);if(this.rehydrateAfterTransportDrop(e,t).catch((a)=>{if(this.disposed||t.disposed)return;this.notify("cloud_session_sync_failed",{sessionId:e,message:a instanceof Error?a.message:"Cloud transcript refresh failed"})}),!r){t.bufferedEvents.push(n);return}}if(this.applyLiveEvent(e,n),this.publish({type:"hub_event",sessionId:e,event:{...n,sessionId:e}}),n.event==="assistant.delta"||n.event==="reasoning.delta"||n.event==="tool.updated")this.scheduleSnapshot(e);else this.publishSnapshot(e)}handleApprovalRequested(e,t,n){this.storePendingApproval(e,t,n.payload),this.sendApprovalSnapshot(e)}storePendingApproval(e,t,n){let s=String(n?.approvalId??"").trim();if(!s)return;let i=`${e}:${s}`,o={approvalId:s,requestId:i,sessionId:e,createdAt:new Date(typeof n?.createdAt==="number"?n.createdAt:Date.now()).toISOString(),toolCallId:String(n?.toolCallId??""),toolName:String(n?.toolName??"tool"),input:Ci(n?.inputJson),iteration:typeof n?.iteration==="number"?n.iteration:void 0,agentId:typeof n?.agentId==="string"?n.agentId:void 0,conversationId:typeof n?.conversationId==="string"?n.conversationId:void 0};this.approvals.set(i,{item:o,resolve:async(r)=>{if(this.disposed||t.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");if(await this.ensureAttached(t),this.disposed||t.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");await t.client.command("approval.respond",{approvalId:s,approved:r.approved,reason:r.reason},t.innerSessionId)}})}removeApproval(e,t){this.approvals.delete(`${e}:${t}`),this.sendApprovalSnapshot(e)}clearPendingApprovals(e){for(let[t,n]of this.approvals)if(n.item.sessionId===e)this.approvals.delete(t);this.sendApprovalSnapshot(e)}sendApprovalSnapshot(e){this.notify("tool_approval_state",{sessionId:e,items:Array.from(this.approvals.values()).filter((t)=>t.item.sessionId===e).map((t)=>t.item)})}async ensureAttached(e){if(this.assertSessionActive(e.remote.id,e),!e.innerSessionId)return;let t=await e.client.command("session.attach",{sessionId:e.innerSessionId},e.innerSessionId);this.assertSessionActive(e.remote.id,e),this.applySessionModel(e,t.payload?.session)}subscribeToInnerSession(e,t){let n=t.innerSessionId;if(!n)return;t.unsubscribe(),this.clearPendingApprovals(e),t.unsubscribe=t.client.subscribe((s)=>this.handleEvent(e,t,s),{sessionId:n})}applySessionModel(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return;let n=De(t);if(n)this.applyModel(e,n);let s=t,i=typeof s.cwd==="string"&&ue.normalize(s.cwd)===s.cwd&&(s.cwd===C||s.cwd.startsWith(`${C}/`))?s.cwd:void 0;if(i){e.remote.metadata.cwd=i;let a=this.sessions.get(e.remote.id);if(a)a.config.cwd=i}let o=this.sessions.get(e.remote.id),r=s.runtimeOptions?.mode;if(o&&(r==="act"||r==="plan"||r==="yolo"||r==="zen"))o.config.mode=r}async disposeConnection(e){this.cancelScheduledSnapshot(e);let t=this.connections.get(e);if(this.connections.delete(e),!t)return;t.disposed=!0,t.pendingInputs?.clear(),t.unsubscribe(),this.clearPendingApprovals(e),await t.client.dispose()}async disposeConnectionIfSessionGone(e,t){if(t.disposed||this.disposed)return;let n;try{n=await this.resolveActiveOrganizationId()}catch{return}let s=await this.options.api.list(n).catch(()=>{return});if(!s||t.disposed)return;let i=s.find((r)=>r.id===e),o=i?this.preserveConnectedRuntimeModel(i):void 0;if(!o){await this.disposeConnection(e).catch(()=>{return});return}if(this.knownSessions.set(e,o),t.remote=o,o.status==="failed"||o.status==="suspended"){let r=this.sessions.get(e);if(r)r.busy=!1,r.status=o.status,r.endedAt=Date.parse(o.updatedAt)||Date.now();await this.disposeConnection(e).catch(()=>{return});return}if(T(o))await this.attachExpired(o).catch(()=>{return}),await this.disposeConnection(e).catch(()=>{return})}}export{it as CloudHandoffCreationRejectedError,_ as CloudHandoffGitPreflightError,ze as CloudHandoffSeedRejectedError,en as CloudHandoffSeedUnsupportedError,he as CloudHandoffTranscriptMismatchError,Ge as CloudQueueUnconfirmedError,vn as CloudSessionApi,ki as CloudSessionController,g as CloudSessionError,qi as buildCloudHandoffDashboardUrl,Bi as clearCloudHandoffMetadata,Ui as cloudHandoffFingerprintsEqual,fe as cloudHandoffTranscriptsEqual,Zt as cloudSessionToDiscoveryRecord,J as countPromptOccurrences,ln as createCloudHandoffFingerprint,st as deriveCloudSessionTitle,wi as isCloudOuterSessionId,ae as isRootSessionRow,Wt as loadCloudModels,Li as mergeCloudHandoffMetadata,Xe as normalizeGitHubRemoteUrl,ce as normalizeSessionTitle,be as parseCloudProvisioningPhase,Mi as preflightCloudHandoffGit,Di as readCloudHandoffMetadata,re as readSessionRows,Kt as reconcileBufferedCloudEvents,qe as resolveSessionListTitle,De as sessionRowModelId,Be as stringifyMessageContent,Le as submittedPromptsFromEvents,Ue as updatedAt};
|