@cline/core 0.0.95 → 0.2.0-nightly.1793312794

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/dist/ClineCore.d.ts +6 -1
  2. package/dist/account/rpc.d.ts +3 -1
  3. package/dist/account/types.d.ts +2 -0
  4. package/dist/artifacts/cloud/fetch.d.ts +8 -0
  5. package/dist/artifacts/cloud/publish.d.ts +6 -0
  6. package/dist/artifacts/publish.d.ts +30 -0
  7. package/dist/cline-core/runtime-services.d.ts +4 -2
  8. package/dist/cloud/computer-use-prompt.d.ts +9 -0
  9. package/dist/cloud/controller.d.ts +26 -4
  10. package/dist/cloud/hub-client.d.ts +53 -0
  11. package/dist/cloud/hub-protocol.d.ts +32 -0
  12. package/dist/cloud/index.d.ts +5 -0
  13. package/dist/cloud/index.js +34 -17
  14. package/dist/cloud/types.d.ts +4 -1
  15. package/dist/extensions/context/compaction-shared.d.ts +1 -0
  16. package/dist/extensions/context/compaction.d.ts +7 -0
  17. package/dist/extensions/context/summarize-conversation.d.ts +7 -0
  18. package/dist/extensions/context/summary-generation.d.ts +14 -0
  19. package/dist/extensions/mcp/apps.d.ts +16 -0
  20. package/dist/extensions/mcp/client.d.ts +1 -0
  21. package/dist/extensions/mcp/index.d.ts +5 -1
  22. package/dist/extensions/mcp/manager.d.ts +2 -1
  23. package/dist/extensions/mcp/session-apps.d.ts +28 -0
  24. package/dist/extensions/mcp/types.d.ts +22 -0
  25. package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
  26. package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
  27. package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
  28. package/dist/hub/client/index.d.ts +6 -0
  29. package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
  30. package/dist/hub/client/plugin-commands.d.ts +4 -0
  31. package/dist/hub/client/session-client.d.ts +2 -0
  32. package/dist/hub/daemon/entry.js +248 -229
  33. package/dist/hub/daemon/index.d.ts +2 -0
  34. package/dist/hub/index.d.ts +1 -0
  35. package/dist/hub/index.js +238 -219
  36. package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
  37. package/dist/hub/server/cloud-session-service.d.ts +52 -0
  38. package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
  39. package/dist/hub/server/handlers/context.d.ts +13 -2
  40. package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
  41. package/dist/hub/server/handlers/session-handlers.d.ts +4 -0
  42. package/dist/hub/server/hub-server-options.d.ts +3 -0
  43. package/dist/hub/server/hub-server-transport.d.ts +2 -0
  44. package/dist/index.d.ts +10 -5
  45. package/dist/index.js +284 -258
  46. package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
  47. package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
  48. package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-bdvd54cj.js +1 -0
  49. package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-d88t4w67.js +1 -0
  50. package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-4rh6dw0e.js +1 -0
  51. package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-dex049wz.js +1 -0
  52. package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +38 -0
  53. package/dist/plugin-runtime/node_modules/@cline/core/dist/community-adrseffv.js +1 -0
  54. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-vf44v1q1.js +1 -0
  55. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-np6pavev.js +1 -0
  56. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-1xg0n8py.js +1 -0
  57. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-2h2811k3.js +1 -0
  58. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-918h9zb6.js +2 -0
  59. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-9g9qz8kw.js +2 -0
  60. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-8p52y0t4.js +1 -0
  61. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-cr4wnstr.js +1 -0
  62. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-aa72jh2v.js +1 -0
  63. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-k2y10eep.js +1 -0
  64. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-1hvm2h6v.js +1 -0
  65. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-7nqbajdc.js +1 -0
  66. package/dist/plugin-runtime/node_modules/@cline/core/dist/google-nqn5r579.js +1 -0
  67. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1166 -0
  68. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1153 -0
  69. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0ahmqye5.js +2 -0
  70. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1jwj53tz.js +2 -0
  71. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-3qy7846d.js +14 -0
  72. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-418gvd4a.js +2 -0
  73. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4etvmc8g.js +2 -0
  74. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4pm9q9we.js +1 -0
  75. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4tgv599k.js +2 -0
  76. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5hwscy9s.js +15 -0
  77. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6dpcn5cw.js +9 -0
  78. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-7ycwqbm0.js +1 -0
  79. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8qjtgvqw.js +9 -0
  80. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8zb5grad.js +1210 -0
  81. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-94jdgxt6.js +2 -0
  82. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9g67p34k.js +2 -0
  83. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-a9d2sjh0.js +85 -0
  84. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-agemt17a.js +3 -0
  85. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bhf7enwn.js +1 -0
  86. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bnwxdgvg.js +1 -0
  87. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-brjxtvsh.js +4 -0
  88. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bvb7f701.js +1 -0
  89. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bwet95hr.js +2 -0
  90. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cadyf2yp.js +14 -0
  91. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cxfnnrmh.js +9 -0
  92. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cyyvppz9.js +6 -0
  93. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d4pbedxj.js +137 -0
  94. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ddwn220p.js +12 -0
  95. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-edf1hmcw.js +62 -0
  96. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ejyd73x5.js +1 -0
  97. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f25bf131.js +4 -0
  98. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f4rfmj6q.js +3 -0
  99. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-fet3kwk6.js +1 -0
  100. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ffna8yzn.js +121 -0
  101. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-g2y6ptdc.js +213 -0
  102. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ge184xvn.js +6 -0
  103. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-gevnedsc.js +13 -0
  104. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkmarmve.js +190 -0
  105. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-kqacxn3s.js +39 -0
  106. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m3gtj35r.js +14 -0
  107. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-neczvge6.js +21 -0
  108. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-p5k5hnam.js +75 -0
  109. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sdvqs19c.js +20 -0
  110. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t75m2pgm.js +146 -0
  111. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-qqb2kabr.js +1 -0
  112. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v6mehmme.js +12 -0
  113. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v80fh3x3.js +16 -0
  114. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vd605jwp.js +2 -0
  115. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vryppqt1.js +1 -0
  116. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w55v4n1n.js +2 -0
  117. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w9n2kgjk.js +140 -0
  118. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yjbp9r76.js +142 -0
  119. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ztb3cjfh.js +3 -0
  120. package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
  121. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-kj4rdeey.js +473 -0
  122. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-y9tt7gmq.js +1 -0
  123. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-bg81k3qh.js +1 -0
  124. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-tkbfbx5w.js +1 -0
  125. package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-mkw95amh.js +1 -0
  126. package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-9z19cm6q.js +2 -0
  127. package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-sjp09b7p.js +1 -0
  128. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-1eyn4hw0.js +1 -0
  129. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-f99c7syq.js +1 -0
  130. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-19936r1a.js +1 -0
  131. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-eavx3zc3.js +1 -0
  132. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
  133. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
  134. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-04d0mwe8.js +1 -0
  135. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-mt7pvm61.js +1 -0
  136. package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-6armtc3s.js +1 -0
  137. package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
  138. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
  139. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
  140. package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
  141. package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
  142. package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
  143. package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
  144. package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
  145. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
  146. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
  147. package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
  148. package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
  149. package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
  150. package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
  151. package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
  152. package/dist/plugin-runtime/package.json +1 -0
  153. package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
  154. package/dist/remote/remote-environments.d.ts +1 -0
  155. package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
  156. package/dist/runtime/host/local-runtime-host.d.ts +10 -0
  157. package/dist/runtime/host/runtime-host.d.ts +6 -0
  158. package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
  159. package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
  160. package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
  161. package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
  162. package/dist/services/cloud-handoff/git-preparation.d.ts +22 -0
  163. package/dist/services/global-settings.d.ts +6 -0
  164. package/dist/services/llms/cline-recommended-models.d.ts +2 -0
  165. package/dist/services/local-runtime-bootstrap.d.ts +1 -0
  166. package/dist/services/plugin-command-api.d.ts +47 -0
  167. package/dist/services/plugin-commands.d.ts +25 -27
  168. package/dist/services/skills-cli.d.ts +2 -0
  169. package/dist/services/telemetry/core-events.d.ts +26 -0
  170. package/dist/services/telemetry/index.js +1 -1
  171. package/dist/services/telemetry/run-health.d.ts +40 -0
  172. package/dist/services/telemetry/stall-signals.d.ts +12 -0
  173. package/dist/types/config.d.ts +1 -0
  174. package/dist/types/session.d.ts +7 -0
  175. package/package.json +6 -5
@@ -1,21 +1,38 @@
1
- import{execFile as rn}from"node:child_process";import{basename as Do,resolve as an}from"node:path";import{promisify as dn}from"node:util";import{processWorkspaceInfo as No}from"@cline/shared";import Qe from"simple-git";var cn=dn(rn);function un(e,t){return cn("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 Ye(e){let t=Xe(e.cwd),n=e.git??un,s=async(i)=>(await n(i,{cwd:t,signal:e.signal})).stdout,o=async(i)=>(await s(i)).trim();return{async isInsideWorkTree(){try{return await o(["rev-parse","--is-inside-work-tree"])==="true"}catch(i){if(Q(i)===128&&/not a git repository|Kein Git-Repository/i.test(K(i)))return!1;throw i}},remotes:()=>Qe({baseDir:t}).getRemotes(!0),displayBranch:async()=>(await Qe({baseDir:t}).branch()).current.trim(),symbolicBranch:()=>o(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>o(["rev-parse","HEAD"]),workspacePrefix:async()=>(await s(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>o(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(i)=>o(["config","--get",`branch.${i}.remote`]),branchMergeRef:(i)=>o(["config","--get",`branch.${i}.merge`]),remoteUrl:(i)=>o(["remote","get-url",i]),remoteRefs:(i,r)=>o(["ls-remote","--exit-code",i,r])}}function Xe(e){return an(e)}class _ extends Error{code;constructor(e,t,n){super(t,n);this.code=e;this.name="CloudHandoffGitPreflightError"}}function Ze(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 et(e){let t=e.trim();if(!t)return null;let n=t.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(n?.[1]){let s=Ze(n[1]);return s.split("/").length===2?`https://github.com/${s}`:null}try{let s=new URL(t);if(s.hostname.toLowerCase()!=="github.com")return null;if(!new Set(["https:","http:","ssh:","git:"]).has(s.protocol))return null;let o=Ze(s.pathname);return o.split("/").length===2?`https://github.com/${o}`:null}catch{return null}}async function O(e,t,n){try{return await e()}catch(s){let o=K(s);throw new _(t,o?`${n} (${o})`:n,{cause:s})}}function ln(e,t){let n=`refs/heads/${t}`;for(let s of e.split(`
2
- `)){let[o,i]=s.trim().split(/\s+/,2);if(i===n&&/^[0-9a-f]{40,64}$/i.test(o??""))return o??null}return null}function pn(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 Fo(e){let t=Ye(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=pn(await O(t.workspacePrefix,"git_command_failed","Could not resolve the workspace path relative to the Git repository.")),o=await O(t.worktreeStatus,"git_command_failed","Could not inspect the Git worktree.");if(o){let u=o.split(`
3
- `).filter(Boolean),g=u.slice(0,5).join(`
4
- `),y=u.length>5?`
5
- ...and ${u.length-5} more`:"";throw new _("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
1
+ import{z as N}from"zod";var st=30000,wn=128,vn=N.object({success:N.literal(!0),data:N.object({url:N.string().url().pipe(N.string().refine((e)=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password})),expiresAt:N.string().datetime({offset:!0}).transform(Date.parse)})});function Cn({request:e,cloudSessionId:t}){let n=new Map;return async function({artifactId:o,signal:i}){let r=`/api/v1/session/${encodeURIComponent(t)}/artifacts/download-url?name=${encodeURIComponent(o)}`;for(let a=0;;a++){i?.throwIfAborted();let d=n.get(o);if(!d||d.expiresAt<=Date.now()+st){n.delete(o);let p=await e(r,{method:"GET",redirect:"error",cache:"no-store",signal:AbortSignal.any([...i?[i]:[],AbortSignal.timeout(15000)])});if(!p.ok)throw await p.body?.cancel().catch(()=>{}),Error(`Artifact service returned HTTP ${p.status}`);let u=vn.safeParse(await p.json());if(!u.success)throw Error("Artifact service returned an invalid download URL");d=u.data.data}i?.throwIfAborted();let c=await fetch(d.url,{method:"GET",credentials:"omit",redirect:"error",cache:"no-store",signal:i});if(c.ok){if(d.expiresAt>Date.now()+st){if(n.delete(o),n.size>=wn){let p=n.keys().next();if(!p.done)n.delete(p.value)}n.set(o,d)}return c}if(n.delete(o),await c.body?.cancel().catch(()=>{}),c.status===403&&a===0)continue;throw Error(`Artifact download returned HTTP ${c.status}`)}}}import{openAsBlob as Sn}from"node:fs";import{stat as kn}from"node:fs/promises";import{basename as Rn}from"node:path";import{setTimeout as ot}from"node:timers/promises";import{z as O}from"zod";import{createTool as bi}from"@cline/shared";class H extends Error{code;constructor(e,t){super(t);this.code=e}}function we(e,t,n,s){return{path:e,artifactId:n,error:s?.aborted?{code:"CANCELLED",message:"Publication cancelled"}:t instanceof H?{code:t.code,message:t.message}:{code:"FILE_READ_FAILED",message:"Could not read the local file"}}}var Pn=O.object({url:O.string(),fields:O.record(O.string().refine((e)=>!/^(key|file)$/i.test(e)),O.string()),keyPrefix:O.string().endsWith("/"),maxBytes:O.number().int().positive(),expiresAt:O.string().refine((e)=>Number.isFinite(Date.parse(e))).transform(Date.parse)}),An=O.object({success:O.literal(!0),data:Pn});async function it(e){let t=await kn(e.path);if(t.size!==e.size||t.mtimeMs!==e.modifiedAt)throw new H("FILE_CHANGED","Local file changed after it was selected")}function _n({request:e,cloudSessionId:t}){return async(n,{signal:s})=>{let o=[];async function i(){for(let a=0;a<3;a++){if(s?.throwIfAborted(),a)await ot(250*a,void 0,{signal:s});let d;try{d=await e(`/api/v1/session/${encodeURIComponent(t)}/artifacts/upload-policy`,{method:"POST",redirect:"error",signal:AbortSignal.any([...s?[s]:[],AbortSignal.timeout(15000)])})}catch{s?.throwIfAborted();continue}if(d.status===429||d.status>=500){await d.body?.cancel().catch(()=>{});continue}if(!d.ok)throw await d.body?.cancel().catch(()=>{}),new H("CORE_REJECTED",`Artifact service returned HTTP ${d.status}`);let c;try{c=await d.json()}catch{throw s?.throwIfAborted(),new H("INVALID_RESPONSE","Artifact service returned invalid JSON")}let p=An.safeParse(c);if(!p.success)throw new H("INVALID_RESPONSE","Invalid upload policy");return p.data.data}throw new H("CORE_UNAVAILABLE","Could not obtain an upload policy after 3 attempts")}let r;try{r=await i()}catch(a){for(let d of n)o.push(we(d.path,a,d.artifactId,s));return o}for(let a of n)try{if(a.size===0)throw new H("EMPTY_FILE","The upload policy does not allow empty files");for(let d=0;d<3;d++){if(s?.throwIfAborted(),d)await ot(250*d,void 0,{signal:s});if(Date.now()>=r.expiresAt)r=await i();if(a.size>r.maxBytes)throw new H("FILE_TOO_LARGE",`File exceeds the upload policy limit of ${r.maxBytes} bytes`);await it(a);let c=new FormData;for(let[f,m]of Object.entries(r.fields))c.append(f,m);c.append("key",r.keyPrefix+a.artifactId),c.append("file",await Sn(a.path,{type:r.fields["Content-Type"]}),Rn(a.path));let p;try{p=await fetch(r.url,{method:"POST",body:c,redirect:"error",signal:AbortSignal.any([...s?[s]:[],AbortSignal.timeout(120000)])})}catch{s?.throwIfAborted(),await it(a)}if(p?.ok){await p.body?.cancel().catch(()=>{});break}let u=!1,h=(p?.status===400||p?.status===403)&&/expired/i.test(await p.text().catch(()=>(u=!0,"")));s?.throwIfAborted();let l=u||!p||p.status===408||p.status===429||p.status>=500;if(await p?.body?.cancel().catch(()=>{}),!h&&!l)throw new H("UPLOAD_REJECTED",`Storage rejected upload with HTTP ${p?.status}`);if(d===2)throw new H("UPLOAD_FAILED","Upload was not confirmed after 3 attempts; retry with the same artifactId");if(h)r=await i()}o.push({path:a.path,artifactId:a.artifactId})}catch(d){o.push(we(a.path,d,a.artifactId,s))}return o}}import{execFile as xn}from"node:child_process";import{basename as xi,resolve as En}from"node:path";import{promisify as Tn}from"node:util";import{processWorkspaceInfo as Ii}from"@cline/shared";import rt from"simple-git";var In=Tn(xn);function Hn(e,t){return In("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 se(e){if(!e||typeof e!=="object"||!("stderr"in e))return"";return typeof e.stderr==="string"?e.stderr.trim():""}function oe(e){if(!e||typeof e!=="object"||!("code"in e))return;return typeof e.code==="number"?e.code:void 0}function at(e){let t=dt(e.cwd),n=e.git??Hn,s=async(i)=>(await n(i,{cwd:t,signal:e.signal})).stdout,o=async(i)=>(await s(i)).trim();return{async isInsideWorkTree(){try{return await o(["rev-parse","--is-inside-work-tree"])==="true"}catch(i){if(oe(i)===128&&/not a git repository|Kein Git-Repository/i.test(se(i)))return!1;throw i}},remotes:()=>rt({baseDir:t}).getRemotes(!0),displayBranch:async()=>(await rt({baseDir:t}).branch()).current.trim(),symbolicBranch:()=>o(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>o(["rev-parse","HEAD"]),workspacePrefix:async()=>(await s(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>o(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(i)=>o(["config","--get",`branch.${i}.remote`]),branchMergeRef:(i)=>o(["config","--get",`branch.${i}.merge`]),remoteUrl:(i)=>o(["remote","get-url",i]),remoteRefs:(i,r)=>o(["ls-remote","--exit-code",i,r])}}function dt(e){return En(e)}class T extends Error{code;constructor(e,t,n){super(t,n);this.code=e;this.name="CloudHandoffGitPreflightError"}}function ct(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 W(e){let t=e.trim();if(!t)return null;let n=t.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(n?.[1]){let s=ct(n[1]);return s.split("/").length===2?`https://github.com/${s}`:null}try{let s=new URL(t);if(s.hostname.toLowerCase()!=="github.com")return null;if(!new Set(["https:","http:","ssh:","git:"]).has(s.protocol))return null;let o=ct(s.pathname);return o.split("/").length===2?`https://github.com/${o}`:null}catch{return null}}async function q(e,t,n){try{return await e()}catch(s){let o=se(s);throw new T(t,o?`${n} (${o})`:n,{cause:s})}}function Mn(e,t){let n=`refs/heads/${t}`;for(let s of e.split(`
2
+ `)){let[o,i]=s.trim().split(/\s+/,2);if(i===n&&/^[0-9a-f]{40,64}$/i.test(o??""))return o??null}return null}function On(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 T("git_command_failed","Could not resolve the workspace path relative to the Git repository.");return t}async function Ui(e){let t=at(e);if(!await q(t.isInsideWorkTree,"not_git_repository","Cloud handoff requires a Git repository."))throw new T("not_git_repository","Cloud handoff requires a Git working tree.");let s=On(await q(t.workspacePrefix,"git_command_failed","Could not resolve the workspace path relative to the Git repository.")),o=await q(t.worktreeStatus,"git_command_failed","Could not inspect the Git worktree.");if(o){let f=o.split(`
3
+ `).filter(Boolean),m=f.slice(0,5).join(`
4
+ `),b=f.length>5?`
5
+ ...and ${f.length-5} more`:"";throw new T("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
6
6
 
7
- ${g}${y}`)}let i;try{i=await t.symbolicBranch()}catch(u){let g=Q(u)===1,y=K(u),w=g?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new _(g?"detached_head":"git_command_failed",y?`${w} (${y})`:w,{cause:u})}if(!i)throw new _("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[r,a,d]=await Promise.all([O(()=>t.branchRemote(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),O(()=>t.branchMergeRef(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),O(t.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!r||r==="."||!a.startsWith("refs/heads/"))throw new _("missing_upstream",`Branch ${i} has no remote branch upstream. Push it with -u before handing off.`);let l=a.slice(11),f=r;if(!et(r))try{f=await t.remoteUrl(r)}catch{throw new _("missing_upstream","Could not resolve the upstream remote.")}let c=et(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(u){let g=Q(u)===2,y=g?`The upstream branch ${l} was not found. Push it before handing off.`:"Could not verify the remote branch. Check your network and GitHub authentication, then try again.";throw new _(g?"remote_branch_missing":"git_command_failed",y)}let p=ln(h,l);if(!p)throw new _("remote_branch_missing",`The upstream branch ${l} was not found. Push it before handing off.`);if(p.toLowerCase()!==d.toLowerCase())throw new _("unpushed_commits",`Local HEAD does not match the upstream branch ${l}. Push the current commit before handing off.`);return{repoUrl:c,branch:l,headSha:d,...s?{workspaceRelativePath:s}:{}}}function pe(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function x(e){if(typeof e!=="string")return;return e.trim()||void 0}function fn(e){return typeof e==="string"&&e.length>0?e:void 0}function hn(e){let t=x(e.repoUrl),n=x(e.branch),s=x(e.headSha),o=x(e.modelId);if(!t||!n||!s||!o)throw Error("Cloud handoff fingerprint fields cannot be empty.");let i=x(e.organizationId),r=fn(e.workspaceRelativePath),a=e.mode;return{repoUrl:t,branch:n,headSha:s,modelId:o,...i?{organizationId:i}:{},...r?{workspaceRelativePath:r}:{},...a?{mode:a}:{}}}function Jo(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 mn(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 hn({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 Go(e){let t=pe(pe(e)?.handoff);if(!t)return;let n=x(t.toCloudSessionId),s=x(t.handedOffAt),o=t.status;if(!n||!s||o!=="pending"&&o!=="complete")return;let i=x(t.innerSessionId),r=x(t.dashboardUrl),a=mn(t.fingerprint);return{toCloudSessionId:n,handedOffAt:s,status:o,...i?{innerSessionId:i}:{},...r?{dashboardUrl:r}:{},...a?{fingerprint:a}:{}}}function Vo(e,t){return{...e??{},handoff:t}}function Ko(e){let{handoff:t,cloudHandoffIntent:n,cloudHandoffSeedDispatched:s,...o}=e??{};return o}function Qo(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 tt(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(tt(e))===JSON.stringify(tt(t))}class he extends Error{constructor(e,t){super(`Cloud transcript verification failed (local ${e} messages, cloud ${t}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as gn}from"node:crypto";import{decodeJwtPayload as yn}from"@cline/shared";var bn=610000,wn=3000,B=15000,vn="CLOUD_SESSION_ERROR:",ot="__cline_create_request__:";function it(e){return(e.trim().split(`
8
- `)[0]??"").trim().slice(0,72)}class m extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${vn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class rt extends m{constructor(e){super("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list or dashboard before starting another task.");this.name="CloudCreationUnconfirmedError",this.cause=e}}class at 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 Cn(e){return`${ot}${e}`.slice(0,255)}function nt(e){return e?.startsWith(ot)===!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=yn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function st(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()},wn);e.addEventListener("abort",s,{once:!0})})}function Sn(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=Sn(t,`Cloud session request failed (${e})`);if(e===401)return new m("authentication_required",o);if(e===404)return new m("session_not_found",o);if(e===410)return new m("session_expired",o);if(e===412)return new m("github_not_connected",o,s??`${ye(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new m("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new m("request_failed",o,void 0,e)}class kn{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??bn}async request(e,t={},n,s,o){let i=!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 m("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new m("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 m("authentication_required","The signed-in account changed during cloud session creation.");s.token=a.trim()}o?.();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}}),l=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,r=a.trim();continue}throw ge(d.status,l,this.appBaseUrl,n)}return l?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&nt(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&&nt(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 r=Number(i.id),a=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(i.name??"").trim();return[{id:r,name:d,fullName:String(i.full_name??(d||a)).trim(),url:a,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof m&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new m("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,r=n.query?.trim(),a=n.cursor?.trim();if(r)i.set("query",r);if(a)i.set("cursor",a);let d=i.size>0?`${o}?${i}`:o;try{let l=await this.request(d),f=Array.isArray(l)?l:Array.isArray(l?.items)?l.items:[],c=r?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let p=String(h.name??"").trim();return p&&(!Array.isArray(l)||!c||p.toLowerCase().includes(c))?[p]:[]}),nextToken:Array.isArray(l)?"":String(l?.nextToken??"").trim()}}catch(l){if(l instanceof m&&l.code==="session_not_found")return{available:!1,branches:[]};throw l}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new m("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new m("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:me(t)},s=Cn(e.requestId?.trim()||gn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new m("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),r=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let p=new m(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(u){if(!(u instanceof m&&(u.code==="session_not_found"||u.code==="session_expired")))throw AggregateError([p,u],"The unusable recovered cloud handoff workspace could not be removed.")}if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.delete(o);throw await e.handoff?.onOuterSessionRemoved?.(c.id),p}await e.handoff?.onOuterSessionCreated(c.id,{created:!1});let h={sessionId:c.id,status:c.status,sandboxUrl:c.sandboxUrl,cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,h);return h};if(o){let c=await i();if(c.length>1)throw new m("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await r(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(p){if(p instanceof m&&(p.code==="session_not_found"||p.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(o),this.unconfirmedHandoffCreates.delete(o);throw p}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:n.token}}if(this.unconfirmedHandoffCreates.has(o))throw new m("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),l,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new m("request_failed","The cloud session service returned no session id.");l=h,await this.persistHandoffOuterSession(e,h,n,o);let p={sessionId:h,status:c.status?.trim()||"provisioning",sandboxUrl:c.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,p);return p}catch(c){if(l)throw c;let h=!f||c instanceof m&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new at(c);if(a.signal.aborted||!(c instanceof m)||c instanceof m&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let u=[];try{u=await i()}catch(y){if(e.handoff)throw AggregateError([c,y],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(!e.handoff&&!h&&u.length!==1)throw new rt(c);if(u.length>1)throw new m("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let g=u[0];if(g){if(e.handoff)return await r(g);return{sessionId:g.id,status:g.status,sandboxUrl:g.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof m&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject: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(a){if(t.aborted)throw a;if(a instanceof m&&a.code!=="request_failed")throw a;await st(t);continue}let r=i?.status?.trim().toLowerCase();if(n?.({phase:be(i?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new m("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new m("request_failed","The cloud session service returned an unexpected provisioning status.");await st(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof m)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new m("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw 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 m("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as _o}from"node:crypto";import{posix as ue}from"node:path";import{createSessionId as js,ensureLoopbackProxyBypass as Nt,isHubProtocolCompatible as Fs,resolveClineBuildEnv as zs,resolveHubCommandTimeoutMs as Js}from"@cline/shared";import{HttpProxyAgent as Gs}from"http-proxy-agent";import{HttpsProxyAgent as Vs}from"https-proxy-agent";import{getProxyForUrl as Ks}from"proxy-from-env";import Qs from"ws";var q={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.95",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"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.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","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","proxy-from-env":"^2.1.0","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/proxy-from-env":"^1.0.4","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var dt="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 rs}from"node:child_process";import{closeSync as as,mkdirSync as ds,openSync as cs,readFileSync as us,unlinkSync as ls}from"node:fs";import{basename as ps,dirname as fs,join as hs}from"node:path";import{fileURLToPath as ms}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as gs,getClineClientIdentity as ys,isBunEmbeddedModulePath as bs,isHubDaemonProcess as ws,resolveClineBuildEnv as It,withHubLauncherIdentity as vs,withResolvedClineBuildEnv as Cs}from"@cline/shared";import{createHash as _n,randomBytes as Pn}from"node:crypto";import{mkdir as Ce,open as ct,readFile as ht,rename as An,rm as Se,writeFile as Tn}from"node:fs/promises";import{dirname as mt,join as ke}from"node:path";import{ensureLoopbackProxyBypass as xn,isHubProtocolCompatible as En}from"@cline/shared";import{resolveClineDataDir as N,resolveClineDir as hi}from"@cline/shared/storage";var Hn="CLINE_HUB_DISCOVERY_PATH",In="CLINE_HUB_BUILD_ID",Mn="CLINE_HUB_BUILD_EPOCH_MS",On=30000,Un=15000,ut=100;function Ln(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Dn(e){return _n("sha256").update(e).digest("hex").slice(0,12)}function Bn(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 lt(e){return new Promise((t)=>setTimeout(t,e))}function qn(e){return`${e}.lock`}async function Nn(e){try{let t=JSON.parse(await ht(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[In]?.trim();if(e)return e;return"sdk-v1-d7fc6ac75da1ec6a985419452ab0576ef1178c82233d7370cd14e6261884bd99".trim()||`source-${String(q.version)}`}function $n(){let e=Number(process.env[Mn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792205906587)?1792205906587:void 0}function X(e,t=U()){let n=En(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 pt(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ft(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 Wn(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 gt(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=pt(e.buildEpochMs),i=pt(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let r=ft(e.coreVersion),a=ft(t.coreVersion);if(r&&a){let d=Wn(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function yt(){return{buildId:U(),buildEpochMs:$n(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??yt(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return gt(n,e)<=0}function bt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Dn(e)}`,n=process.env[Hn]?.trim()||ke(N(),"locks","hub","owners",`${Ln(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e,t={}){try{let n;try{n=await ht(e,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let s;try{s=JSON.parse(n)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!s||typeof s.hubId!=="string"||typeof s.protocolVersion!=="string"||typeof s.authToken!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string"||typeof s.startedAt!=="string"||typeof s.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:s.hubId,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,authToken:s.authToken,host:s.host,port:s.port,url:s.url,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:s.startedAt,updatedAt:s.updatedAt}}catch(n){if(t.onError==="throw")throw n;return}}async function wt(e,t){await Ct(e,async()=>{let n=mt(e);await Ce(n,{recursive:!0});let s=`${e}.${process.pid}.${Pn(6).toString("hex")}.tmp`,o;try{o=await ct(s,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
9
- `,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await An(s,e);let i;try{i=await ct(n,"r"),await i.sync()}catch{}finally{await i?.close().catch(()=>{return})}}catch(i){throw await o?.close().catch(()=>{return}),await Se(s,{force:!0}).catch(()=>{return}),i}})}async function L(e){await Ct(e,async()=>{await Se(e,{force:!0}).catch(()=>{return})})}async function vt(e,t,n){let s=qn(e);await Ce(mt(s),{recursive:!0});let o=Date.now()+Un;while(!0){try{await Ce(s,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await Nn(s);if(!a){if(Date.now()>=o){await ve(s);continue}await lt(ut);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!Bn(a.pid)||d>On){await ve(s);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${s}`);await lt(ut);continue}try{return await Tn(ke(s,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
10
- `,"utf8"),await n()}finally{await ve(s)}}}function Ct(e,t){return vt(`${e}.mutation`,"discovery mutation",t)}function St(e,t){return vt(e,"startup",t)}async function ee(e,t){xn();try{let n=await fetch(t?.authToken?jn(e):Rt(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 kt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Rt(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function jn(e){let t=new URL(Rt(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as Fn,CLINE_HUB_PORT as zn,resolveClineBuildEnv as Jn}from"@cline/shared";var Gn="CLINE_HUB_HOST",Vn="CLINE_HUB_PORT",Kn="CLINE_HUB_PATHNAME",Qn="127.0.0.1",Yn=zn,Xn="/hub";function _t(e){return Jn(e)==="development"?Fn:Yn}function Zn(e={}){return(e.env??process.env)[Gn]?.trim()||Qn}function es(e={}){let n=(e.env??process.env)[Vn]?.trim();if(!n)return _t(e);let s=Number.parseInt(n,10);if(!Number.isInteger(s)||s<1||s>65535)return _t(e);return s}function ts(e={}){return(e.env??process.env)[Kn]?.trim()||Xn}function Pt(e={},t={}){return{host:e.host??Zn(t),port:e.port??es(t),pathname:e.pathname??ts(t)}}import{join as ns}from"node:path";var ss="shared:cline",os="CLINE_HUB_DISCOVERY_PATH",is="hub-production";function W(e=ss){return bt(`${e}@${U()}`)}function te(){return{ownerId:is,discoveryPath:process.env[os]?.trim()||ns(N(),"locks","hub","production.json")}}var At=15000,Ss=200,Tt=3000,ks=100,Rs=[100,250,500,1000,2000],Mt="--cline-hub-daemon",_s=3,Ps=60000,xt=new Map;function As(e,t=Date.now()){let n=xt.get(e);if(!n||t-n.windowStartedAt>Ps)return xt.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=_s}function Ts(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function xs(){try{let e=hs(N(),"logs","hub-daemon.log");return ds(fs(e),{recursive:!0}),{fd:cs(e,"a"),logPath:e}}catch{return}}function Es(){return It()==="production"?te():W()}function j(e){return Z(e)}function Hs(e){try{let t=JSON.parse(us(`${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{ls(`${e}.superseded`)}catch{}}function Et(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 Ht(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await F(e))?.url)return!0;await new Promise((o)=>setTimeout(o,ks))}return!1}async function Ae(e,t){if(!As(e.url))return!1;await z(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Ut(e.url,e.authToken).catch(()=>!1);let n=await Ht(e.url,Tt);if(!n&&e.pid&&Is(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Ht(e.url,Tt)}if(n)await L(t).catch(()=>{return});return n}function Is(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Ms(e){try{return(await Te(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 Ms(e)){if(n)await z(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let s=await Ae(e,t);if(!s&&n)await z(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return s?"retired":"failed"}async function Os(e){if(It()!=="production")return;let t=W();if(t.discoveryPath===e.discoveryPath)return;let n=await I(t.discoveryPath);if(n?.url)await Ae(n,t.discoveryPath);else await L(t.discoveryPath).catch(()=>{return})}function Us(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return ms(new URL(`./entry.${e}`,import.meta.url))}function Ls(e,t){if(bs(e))return[Mt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}var Pe;function Ds(e,t){let n,s;if(Pe)n=Pe.command,s=Pe.args??[Mt];else{let o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let i=ps(o).toLowerCase().includes("bun");n=o,s=Ls(Us(),i)}return{launcher:n,args:[...s,"--cwd",e,...Ts(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...vs(Cs(process.env),Bs()),CLINE_NO_INTERACTIVE:"1",[gs]:"1"}}}function Bs(){let e=ys(),t=e?.name?.trim();return t?{client:t,version:e?.version,transport:"local"}:void 0}function qs(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 Ns(e,t={}){if(ws())return;let n=Ds(e,t),s=xs();try{rs(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)as(s.fd)}}async function $s(e,t={}){for(let n=0;;n++)try{Ns(e,t);return}catch(s){let o=Rs[n];if(!qs(s)||o===void 0)throw s;await new Promise((i)=>setTimeout(i,o))}}async function Ws(e,t,n={}){let s=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Pt(n),i=kt(o.host,o.port,o.pathname),r=(u)=>{if(!s)ne(u.url,u.authToken);return u};await Os(e).catch(()=>{return});let a=await I(e.discoveryPath),d=a?.url?void 0:Hs(e.discoveryPath),l=!1;if(a?.url){let u=a.authToken;if(!u)l=!0,await Ae(a,e.discoveryPath);else{let g=await F(a.url,u);if(g?.url&&j(g)&&await E(g.url,{authToken:u}))return Re(e.discoveryPath),r({url:g.url,authToken:u});if(g?.url){if(await _e({...g,authToken:u},e.discoveryPath)==="deferred_busy"&&await E(g.url,{authToken:u}))return r({url:g.url,authToken:u})}else await L(e.discoveryPath).catch(()=>{return})}}let f=await F(i);if(f?.url){let u=Et(f,a??d,i);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 E(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 wt(e.discoveryPath,P)}catch{}return Re(e.discoveryPath),r({url:f.url,authToken:v})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${l?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let g=await _e(u,e.discoveryPath);if(g==="deferred_busy"){for(let y of[u.authToken,a?.authToken].filter((w)=>typeof w==="string"&&w.trim().length>0))if(await E(f.url,{authToken:y}))return r({url:f.url,authToken:y});if(n.allowPortFallback!==!0&&o.port!==0)throw Error(`An older Cline Hub is running at ${i} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(g==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let h=n.allowPortFallback===!0&&o.port!==0?{...o,port:0}:o;await n.beforeSpawn?.(),await $s(t,{...h,manageConnectors:n.manageConnectors});let p=Date.now()+At;while(Date.now()<p){let u=await I(e.discoveryPath);if(u?.url&&u.authToken){let y=await F(u.url,u.authToken);if(y?.url&&j(y)&&await E(y.url,{authToken:u.authToken}))return Re(e.discoveryPath),r({url:y.url,authToken:u.authToken})}let g=await F(i);if(g?.url&&!j(g)){let y=Et(g,u??d,i),w=await _e(y,e.discoveryPath);if(w==="deferred_busy"&&u?.authToken&&await E(g.url,{authToken:u.authToken}))return r({url:g.url,authToken:u.authToken});if(w==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((y)=>setTimeout(y,Ss))}throw Error(`Timed out after ${At}ms waiting for detached hub startup.`)}async function Ot(e,t={}){let n=Es();return await St(n.discoveryPath,async()=>Ws(n,e,t))}function Ys(){return zs()==="production"?te():W()}function Xs(){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 Zs(e){let t=new URL(e);t.protocol=e.protocol==="wss:"?"https:":"http:";let n=Ks(t.toString());if(!n)return;return e.protocol==="wss:"?new Vs(n):new Gs(n)}function $t(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 $t(e.data);return String(e)}function eo(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 Lt(e){let t=e,n=eo(t.reason);return new k("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:He,{closeCode:t.code,closeReason:n||void 0})}function xe(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 Ee="*",se=8000,to="cline-hub-auth.",Wt=new Map,jt=new Set,no=3000;var He="Hub connection closed",so=250,oo=5000,Dt=0.5;class k extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function io(e){return e instanceof k}class Ie extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function Oe(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let s=Ue(e.toString());return s?Wt.get(s):void 0}function ro(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 Ue(e){if(!ro(e))return;let t=new URL(Ft(e));return t.search="",t.hash="",t.toString()}function Bt(e){let t=Ue(e);return!!t&&jt.has(t)}function ne(e,t){let n=Ue(e);if(n){if(jt.add(n),t?.trim())Wt.set(n,t)}return e}class J{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",He);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()||Oe(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(r)=>{if(o=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 i=this.connectPromise;try{await i}catch(r){if(this.connectPromise===i)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=xe(r,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw r}}async openSocket(e,t,n){let s=this.options.resolveConnectionHeaders,o;if(s){let l;try{o=await Promise.race([Promise.resolve().then(()=>s()),new Promise((f,c)=>{l=setTimeout(()=>{c(new k("hub_connect_timeout",`Timed out resolving hub connection headers after ${se}ms`))},se)})])}catch(f){let c=f instanceof k?f:new k("hub_connect_failed",f instanceof Error?f.message:String(f));if(n===this.connectGeneration)this.lastCloseError=c;throw c}finally{clearTimeout(l)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((l)=>l.toLowerCase()==="sec-websocket-protocol")){let l=new k("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=l;throw l}let i;try{i=o?Zs(e):void 0}catch(l){let f=xe(l,e);if(n===this.connectGeneration)this.lastCloseError=f;throw f}let r=o?new Qs(e.toString(),{headers:{...o},agent:i}):new(Xs())(e.toString(),t?[`${to}${t}`]:void 0);this.socket=r;let a=!1,d=new Promise((l,f)=>{let c=!1,h=setTimeout(()=>{if(c)return;c=!0,a=!0;let p=new k("hub_connect_timeout",`Timed out connecting to hub after ${se}ms`);if(this.socket===r)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{r.close()}catch{}f(p)},se);r.addEventListener("open",()=>{if(c)return;c=!0,clearTimeout(h),l()}),r.addEventListener("error",(p)=>{if(c)return;c=!0,clearTimeout(h);let u=xe(p,e);if(this.socket===r)this.lastCloseError=u,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;f(u)}),r.addEventListener("close",(p)=>{if(c)return;c=!0,clearTimeout(h);let u=a?this.lastCloseError:Lt(p);if(this.socket===r){if(!a)this.lastCloseError=u,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}f(u)})});return r.addEventListener("message",(l)=>{this.handleFrame(JSON.parse($t(l)))}),r.addEventListener("close",(l)=>{if(this.socket!==r)return;if(!a)this.lastCloseError=Lt(l),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await d,r}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(r){if(!i||o>=1||!await this.recoverLocalHubTransport(r))throw r;o+=1}}async commandOnce(e,t,n,s,o=!0){if(o)await this.connect();s?.beforeDispatch?.();let i=js("hubreq_");s?.onDispatch?.(i);let r=Js(e,s?.timeoutMs),a=new Promise((l,f)=>{let c=r===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;f(new Ie(e,"hub_command_timeout",`Hub command ${e} timed out after ${r}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.`))},r);this.pendingReplies.set(i,{resolve:(h)=>{if(c)clearTimeout(c);l(h)},reject:(h)=>{if(c)clearTimeout(c);f(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:r,payload:t}})}catch(l){throw this.pendingReplies.delete(i),l}let d=await a;if(!d.ok){if(d.error?.code===dt){let l=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Y(l,d.error.message)}throw new Ie(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Bt(this.currentUrl)||!io(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await qt({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(so*2**this.reconnectAttempt,oo),t=Math.round(e*(1-Dt)+Math.random()*e*Dt);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(!Bt(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await qt({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",He);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??Ee}subscriptionSessionIdFromKey(e){return e===Ee?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[Ee,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 Ft(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 E(e,t){let n=new J({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 Me(e,t){let n=Ft(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(!Fs(s).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await E(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function ao(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 r of i){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 Te(e,t,n){let s=new J({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:no});return ao(o.payload)}finally{await s.dispose().catch(()=>{return})}}async function co(e,t,n){try{return(await Te(e,t,n)).activeSessionCount===0}catch{return!1}}async function uo(e,t){let n=`${e.discoveryPath}.superseded`,s=await I(n);if(!s?.url||!s.authToken)return;let o=await Me(s.url,{authToken:s.authToken});if(o.status!=="compatible")return;if(await co(o.url,s.authToken,t))return;return ne(o.url,s.authToken)}async function lo(e={}){if(e.endpoint?.trim()){let o=await Me(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=Ys(),n=await I(t.discoveryPath);if(!n?.url)return await uo(t,e);let s=await Me(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(s.status==="compatible")return ne(s.url,n.authToken);if(s.status==="protocol_mismatch")await L(t.discoveryPath).catch(()=>{return});return}async function qt(e={}){let t=await lo(e);if(t&&await E(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Ot(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function z(e,t,n,s){Nt();let o=new URL(e),i=t?.trim()||Oe(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 Ut(e,t){Nt();let n=new URL(e),s=t?.trim()||Oe(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 po(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 Le(e,t){return Array.isArray(e)?e.flatMap((n)=>{let s=po(n,t);return s?[s]:[]}):[]}async function zt(e,t={}){let n=e.trim(),s=n.length;while(s>0&&n[s-1]==="/")s--;let o=n.slice(0,s),i=async(g)=>{let y=await(t.fetchImpl??fetch)(`${o}${g}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!y.ok)throw Error(`HTTP ${y.status}`);return await y.json()},r,a;try{[r,a]=await Promise.all([i("/api/v1/ai/cline/models"),i("/api/v1/ai/cline/recommended-models")])}catch(g){throw Error("Could not load the cloud model catalog.",{cause:g})}let d=r&&typeof r==="object"?r:void 0,l=Le(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=Le(c?.clinePass,"cline-pass"),p=Le(c?.clineCloud,"cline-cloud"),u=new Set;return[...t.isOrganizationSession?[]:h,...p,...l].filter((g)=>{if(u.has(g.id))return!1;return u.add(g.id),!0})}import{formatDisplayUserInput as Jt}from"@cline/shared";var fo=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function ho(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function mo(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function go(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function yo(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 bo(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 wo(e){if(ho(e.role)!=="user")return 0;let t=mo(e),n=typeof t?.kind==="string"?t.kind:void 0,s=go(t);if(n==="compaction"||n==="compaction_summary")return s??1;if(s!==void 0)return s;if(n&&fo.has(n))return 0;let o=yo(e);if(!o.hasAttachment&&!Jt(o.text))return 0;if(!o.hasAttachment&&bo(o.text))return 0;return 1}function Gt(e){return wo(e)>0}function re(e){return Array.isArray(e?.sessions)?e.sessions.filter((t)=>Boolean(t)&&typeof t==="object"&&!Array.isArray(t)):[]}function De(e){let t=e.updatedAt;return typeof t==="number"?t:Date.parse(String(t??""))||0}function Be(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 Yt(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 oe(e){let t=e.trim(),n=t.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(n?n[1]:t).trim()}function G(e,t,n){let s=oe(n);return e.filter((o)=>Boolean(o)&&typeof o==="object"&&!Array.isArray(o)&&String(o.role??"").toLowerCase()==="user"&&(s!==""||Gt(o))&&oe(Yt(o))===s).length+t.filter((o)=>oe(o.prompt)===s).length}function qe(e){return e.flatMap((t)=>{if(t.event!=="session.pending_prompt_submitted")return[];let n=t.payload?.prompt&&typeof t.payload.prompt==="object"&&!Array.isArray(t.payload.prompt)?t.payload.prompt:void 0,s=String(n?.id??"").trim();if(!s)return[];return[{id:s,prompt:String(n?.prompt??""),steer:n?.delivery==="steer",attachmentCount:typeof n?.attachmentCount==="number"?n.attachmentCount:0,userImages:Array.isArray(n?.userImages)?n.userImages.filter((o)=>typeof o==="string"):void 0}]})}var vo=new Set(["run.completed","run.aborted","run.failed"]),Co=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function Vt(e,t){return e.filter((n)=>Boolean(n)&&typeof n==="object"&&!Array.isArray(n)&&String(n.role??"").toLowerCase()==="assistant").map((n)=>Yt(n,t)).filter(Boolean)}function Kt(e,t,n="text"){let s=new Map;for(let o of Vt(t,n))s.set(o,(s.get(o)??0)+1);return Vt(e,n).filter((o)=>{let i=s.get(o)??0;if(i===0)return!0;if(i===1)s.delete(o);else s.set(o,i-1);return!1})}function ie(e,t,n=new Set){if(!e||typeof e!=="object")return n;if(Array.isArray(e)){for(let i of e)ie(i,t,n);return n}let s=e,o=t==="tool_use"?s.id:s.tool_use_id;if(s.type===t&&typeof o==="string")n.add(o);for(let i of Object.values(s))ie(i,t,n);return n}function Qt(e,t="assistant"){let n="",s="";for(let o of e)if(o.event===`${t}.delta`)s+=t==="reasoning"&&o.payload?.redacted&&!o.payload?.text?"[redacted]":typeof o.payload?.text==="string"?o.payload.text:"";else if(o.event===`${t}.finished`){let i=o.payload?.[t==="assistant"?"text":"reasoning"],r=typeof i==="string"&&i?i:s;if(r)n=r;s=""}return(n||s).trim()}function Xt(e,t,n={}){let s=n.queueSnapshotApplied!==!1,o=Kt(t,n.baselineMessages??[]),i=Kt(t,n.baselineMessages??[],"thinking"),r=ie(t,"tool_use"),a=ie(t,"tool_result"),d=new Set(e.slice(0,n.messagesSnapshotEventCutoff??e.length)),l=new Set,f=new Map;for(let y of e.slice(0,n.messagesSnapshotEventCutoff??e.length)){let w=qe([y])[0];if(!w)continue;let v=oe(w.prompt),P=f.get(v)??Math.max(0,G(t,[],v)-G(n.baselineMessages??[],[],v));if(f.set(v,Math.max(0,P-1)),P>0)l.add(y)}let h=[...s?e.slice(n.queueSnapshotEventCutoff??e.length):e].reverse().find((y)=>y.event==="session.pending_prompts"),p=[],u=[],g=(y)=>{if(u.length===0)return;let w=u.filter((A)=>d.has(A)),v=(A)=>{if(!y)return-1;let S=[...w].reverse().findIndex((on)=>on.event===`${A}.finished`),D=S<0?-1:w.length-1-S;return D>=0||u.at(-1)?.event==="run.aborted"?D:w.length-1},P=v("assistant"),H=v("reasoning"),b=Qt(w.slice(0,P+1)),R=b?o.findIndex((A)=>A.endsWith(b)):-1,M=R>=0;if(M)o.splice(R,1);let V=Qt(w.slice(0,H+1),"reasoning"),le=V?i.findIndex((A)=>A.endsWith(V)):-1;if(le>=0)i.splice(le,1);for(let[A,S]of u.entries()){if(l.has(S)){p.push({...S,payload:{...S.payload,transcriptReflected:!0}});continue}if(d.has(S)&&Co.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 D=String(S.payload?.toolCallId??"").trim();if(a.has(D)||S.event==="tool.started"&&r.has(D))continue}p.push(S)}u=[]};for(let y of e)if(u.push(y),vo.has(y.event))g(!0);return g(!1),p}import{formatDisplayUserInput as So}from"@cline/shared";function de(e){let t=structuredClone(e),n=(s)=>{if(!s||typeof s!=="object"||Object.isFrozen(s))return;for(let o of Object.values(s))n(o);Object.freeze(s)};return n(t),t}function ce(e){let t=e?.trim();return t?So(t).slice(0,120):void 0}function Ne(e){if(typeof e==="string")return e;if(Array.isArray(e)){let t=[];for(let n of e){if(typeof n==="string"){if(n.trim())t.push(n);continue}if(!n||typeof n!=="object")continue;let s=n,o=typeof s.type==="string"?s.type:"",i=o==="text"?String(s.text??""):o==="thinking"?String(s.thinking??""):o==="tool_use"?`[tool] ${String(s.name??"tool_call")}`:o==="tool_result"?`[tool_result]
12
- ${Ne(s.content)}`:o==="image"?"[image]":o==="redacted_thinking"?"[redacted_thinking]":typeof s.text==="string"?s.text:"";if(i.trim())t.push(i)}return t.join(`
13
- `)}if(e&&typeof e==="object"){let t=e;if(typeof t.text==="string")return t.text}return""}function ko(e){let t=ce(e??void 0);if(!t)return;return t.split(`
14
- `)[0]?.trim().slice(0,70)||void 0}function Ro(e){for(let t of["user","assistant"])for(let n of e){if(!n||typeof n!=="object")continue;let s=n;if(s.role!==t)continue;let o=ce(Ne(s.content));if(!o)continue;return o.split(`
15
- `)[0]?.trim().slice(0,70)||void 0}return}function $e(e){let t=e.metadata&&typeof e.metadata==="object"?ce(e.metadata.title):void 0;if(t)return t.slice(0,70);let n=ko(e.prompt);if(n)return n;let s=e.messages?Ro(e.messages):void 0;if(s)return s;return`Session ${e.sessionId.slice(-6)}`}function Zt(e,t,n,s){let o=t.payload??{},i=()=>{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,l)=>{let f=i(),c=f.at(-1);if(c?.type===a)c[d]=`${c[d]??""}${l}`;else f.push({type:a,[d]:l})};switch(t.event){case"assistant.delta":if(typeof o.text==="string")r("text","text",o.text);return;case"reasoning.delta":if(typeof o.text==="string"&&o.text)r("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 a=String(o.toolCallId??"");if(a&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((l)=>l.type==="tool_use"&&l.id===a)))i().push({type:"tool_use",id:a,name:String(o.toolName??"tool"),input:structuredClone(o.input??{})});return}case"tool.finished":{let a=String(o.toolCallId??"");if(a&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((l)=>l.type==="tool_result"&&l.tool_use_id===a)))e.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:a,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 a=Array.isArray(o.prompts)?o.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((l)=>typeof l==="string"):void 0})).filter((d)=>d.id&&(d.prompt||d.attachmentCount));return}case"session.pending_prompt_submitted":{let a=o.prompt,d=String(a?.id??"");if(!d||e.lastQueuedPromptStartId===d)return;if(e.lastQueuedPromptStartId=d,e.promptsInQueue=e.promptsInQueue.filter((l)=>l.id!==d),o.transcriptReflected!==!0)e.messages.push({role:"user",content:[{type:"text",text:String(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=o.session,d=typeof a?.status==="string"?a.status:t.event==="run.started"?"running":e.status,l=d==="pending"?"running":d;if(t.event==="session.updated"&&l==="running"&&e.endedAt!==void 0&&!e.busy)return;let f=e.busy;if(e.status=l,e.busy=l==="running",t.event==="run.started"){if(!f)n.delete(s);e.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;e.status=typeof o.reason==="string"?o.reason:t.event==="run.failed"?"error":t.event==="run.aborted"?"aborted":"completed",e.busy=!1,e.endedAt=Date.now(),n.delete(s);return}}}function We(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 je(e,t){return e instanceof Error&&e.name==="HubCommandError"&&e.code==="hub_command_timeout"&&(!t||e.command===t)}var C="/workspace",Po=30000,Ao=2000,To=2000,nn="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 xo(e){let t=`cline/${(e.metadata.taskId?.trim()||e.id).slice(-8).toLowerCase()}`,n=e.sandboxType==="resumable"||e.metadata.sandboxType==="resumable";return`${nn}
7
+ ${m}${b}`)}let i;try{i=await t.symbolicBranch()}catch(f){let m=oe(f)===1,b=se(f),w=m?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new T(m?"detached_head":"git_command_failed",b?`${w} (${b})`:w,{cause:f})}if(!i)throw new T("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[r,a,d]=await Promise.all([q(()=>t.branchRemote(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),q(()=>t.branchMergeRef(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),q(t.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!r||r==="."||!a.startsWith("refs/heads/"))throw new T("missing_upstream",`Branch ${i} has no remote branch upstream. Push it with -u before handing off.`);let c=a.slice(11),p=r;if(!W(r))try{p=await t.remoteUrl(r)}catch{throw new T("missing_upstream","Could not resolve the upstream remote.")}let u=W(p);if(!u)throw new T("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let h;try{h=await t.remoteRefs(r,a)}catch(f){let m=oe(f)===2,b=m?`The upstream branch ${c} 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 T(m?"remote_branch_missing":"git_command_failed",b)}let l=Mn(h,c);if(!l)throw new T("remote_branch_missing",`The upstream branch ${c} was not found. Push it before handing off.`);if(l.toLowerCase()!==d.toLowerCase())throw new T("unpushed_commits",`Local HEAD does not match the upstream branch ${c}. Push the current commit before handing off.`);return{repoUrl:u,branch:c,headSha:d,...s?{workspaceRelativePath:s}:{}}}function ve(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function D(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 Dn(e){let t=D(e.repoUrl),n=D(e.branch),s=D(e.headSha),o=D(e.modelId);if(!t||!n||!s||!o)throw Error("Cloud handoff fingerprint fields cannot be empty.");let i=D(e.organizationId),r=Un(e.workspaceRelativePath),a=e.mode;return{repoUrl:t,branch:n,headSha:s,modelId:o,...i?{organizationId:i}:{},...r?{workspaceRelativePath:r}:{},...a?{mode:a}:{}}}function Li(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 Ln(e){let t=ve(e);if(!t||typeof t.repoUrl!=="string"||typeof t.branch!=="string"||typeof t.headSha!=="string"||typeof t.modelId!=="string")return;try{return Dn({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 Bi(e){let t=ve(ve(e)?.handoff);if(!t)return;let n=D(t.toCloudSessionId),s=D(t.handedOffAt),o=t.status;if(!n||!s||o!=="pending"&&o!=="complete")return;let i=D(t.innerSessionId),r=D(t.dashboardUrl),a=Ln(t.fingerprint);return{toCloudSessionId:n,handedOffAt:s,status:o,...i?{innerSessionId:i}:{},...r?{dashboardUrl:r}:{},...a?{fingerprint:a}:{}}}function Ni(e,t){return{...e??{},handoff:t}}function qi(e){let{handoff:t,cloudHandoffIntent:n,cloudHandoffSeedDispatched:s,...o}=e??{};return o}function $i(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 ut(e){return e.map((t)=>{let n=t&&typeof t==="object"?t:{};return{role:n.role,content:n.content}})}function Ce(e,t){return e.length===t.length&&JSON.stringify(ut(e))===JSON.stringify(ut(t))}class Se extends Error{constructor(e,t){super(`Cloud transcript verification failed (local ${e} messages, cloud ${t}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{execFile as Bn}from"node:child_process";import{randomUUID as lt}from"node:crypto";import{mkdtemp as Nn,rm as qn}from"node:fs/promises";import{tmpdir as $n}from"node:os";import{join as pt}from"node:path";function zn(e){let{id:t,repoUrl:n,remote:s,branch:o,sourceBranch:i,files:r,commits:a}=e;return{id:t,repoUrl:n,remote:s,branch:o,sourceBranch:i,files:r,commits:a}}async function C(e,t,n={}){try{return await new Promise((s,o)=>{let i=Bn("git",t,{cwd:e,env:{...process.env,...n.env,GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_GRAFT_FILE:"/dev/null"},encoding:"utf8",maxBuffer:8388608,timeout:n.timeout??60000},(r,a)=>r?o(r):s(a.trimEnd()));if(n.input!==void 0)i.stdin?.on("error",o),i.stdin?.end(n.input)})}catch(s){let o=s instanceof Error&&"code"in s?s.code:void 0,r=o===null&&s instanceof Error&&"killed"in s&&s.killed===!0?`timed out after ${(n.timeout??60000)/1000} seconds`:`failed${typeof o==="number"?` (exit code ${o})`:""}. Check Git authentication, permissions, and repository state`;throw Error(`Git ${t[0]} ${r}.`)}}async function Fn(e,t){try{return await C(e,["config","--get",t])}catch{return""}}function ft(e){return/(^|\/)(\.env(?:\.[^/]*)?|\.npmrc|\.yarnrc\.yml|\.netrc|\.pgpass|\.pypirc|\.aws\/credentials|id_rsa|id_ed25519|credentials\.json)$|\.(pem|key|p12|pfx|jks|keystore)$/i.test(e)&&!/\.(example|sample|template)$/i.test(e)}async function jn(e,t){let n=(await C(e,["remote","get-url","--all",t])).split(`
8
+ `),s=(await C(e,["remote","get-url","--push","--all",t])).split(`
9
+ `),o=W(n[0]??""),i=s[0];if(o&&i&&n.length===1&&s.length===1&&W(i)===o)return{repoUrl:o,pushUrl:i};return}async function Gn(e,t){let n=await C(e,["rev-parse","--show-toplevel"]).catch(()=>{throw Error("Could not read the Git repository. Open a Git repository and check access before using /cloud.")}),s=(await C(e,["rev-parse","--show-prefix"])).replace(/\/$/,"");if((await C(n,["ls-files","-v","-z"])).split("\x00").some((y)=>/^[a-zS] /.test(y)))throw Error("Cloud preparation cannot include files marked skip-worktree or assume-unchanged. Review these flags and local changes before retrying /cloud.");let o=await C(n,["symbolic-ref","--short","HEAD"]).catch(()=>{throw Error("Could not read the current branch. Check out a Git branch before using /cloud.")}),i=await C(n,["rev-parse","HEAD"]),r=await C(n,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--no-renames"]),a=r.split("\x00").filter(Boolean).map((y)=>({status:y.slice(0,2),path:y.slice(3)})),d=(await C(n,["ls-files","--stage","-z"])).split("\x00").filter((y)=>y.startsWith("160000 ")).map((y)=>y.slice(y.indexOf("\t")+1));if(a.some((y)=>y.status.includes("U")||["AA","DD"].includes(y.status)||d.includes(y.path)))throw Error("Resolve conflicts or changes inside submodules before continuing in cloud.");if(a.some(({path:y})=>ft(y)))throw Error("Potentially sensitive files need review before cloud preparation. Keep private files out of the changes and unpublished history before retrying /cloud.");let c=await C(n,["write-tree"]),p=await Nn(pt($n(),"cline-handoff-index-")),u;try{let y={GIT_INDEX_FILE:pt(p,"index")};await C(n,["read-tree",c],{env:y}),await C(n,["add","-A","--",":/"],{env:y}),u=await C(n,["write-tree"],{env:y})}finally{await qn(p,{recursive:!0,force:!0})}if((await C(n,["ls-tree","-r","-z",u])).split("\x00").filter((y)=>y.startsWith("160000 ")).map((y)=>y.slice(y.indexOf("\t")+1)).some((y)=>!d.includes(y)))throw Error("Nested Git repositories cannot be included in automatic cloud preparation. Review them before continuing.");if(await C(n,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--no-renames"])!==r||await C(n,["rev-parse","HEAD"])!==i||await C(n,["write-tree"])!==c)throw Error("The repository changed while preparing the preview. Run /cloud again.");t?.();let l=await Fn(n,`branch.${o}.remote`)||"origin";if(l==="."||l.startsWith("-"))throw Error("Choose a GitHub remote before continuing in cloud.");let f=await jn(n,l);if(!f)throw Error("Cloud preparation requires one GitHub repository shared by the fetch and push destination. Review the remote configuration first.");let{repoUrl:m}=f,w=(await C(n,["ls-remote","--heads",l])).split(`
10
+ `).map((y)=>y.split(/\s/)[0]??"").filter((y)=>/^[0-9a-f]{40,64}$/.test(y)),v=[],R=w.includes(i);if(!R&&w.length)try{let y={GIT_NO_LAZY_FETCH:"1"},_=(await C(n,["cat-file","--batch-check=%(objectname) %(objecttype)"],{input:`${w.join(`
11
+ `)}
12
+ `,env:y})).split(`
13
+ `),S=w.filter((x,I)=>_[I]===`${x} commit`);if(S.length)R=await C(n,["rev-list","--count","--stdin"],{input:`${[i,...S.map((x)=>`^${x}`)].join(`
14
+ `)}
15
+ `,env:y})==="0"}catch{}if(!R){if(w.length)await C(n,["fetch","--no-prune","--no-tags","--no-write-fetch-head","--no-recurse-submodules","--refmap=","--stdin",l],{input:`${w.join(`
16
+ `)}
17
+ `});let y=`${[i,...w.map((S)=>`^${S}`)].join(`
18
+ `)}
19
+ `;if(v=(await C(n,["log","--format=%h %s","--stdin"],{input:y})).split(`
20
+ `).filter(Boolean),(await C(n,["log","--format=","--name-only","-z","--root","-c","--no-renames","--stdin"],{input:y})).split("\x00").some(ft))throw Error("Potentially sensitive files exist in unpublished history, even if deleted later. Review that history before retrying /cloud; no branch was created or pushed.")}return{id:lt(),root:n,workspaceRelativePath:s,repoUrl:m,remote:l,branch:`cline/handoff-${lt().slice(0,12)}`,sourceBranch:o,headSha:i,treeSha:u,files:a,commits:v}}import{randomUUID as Wn}from"node:crypto";import{decodeJwtPayload as Jn}from"@cline/shared";var Vn=610000,Kn=3000,J=15000,Qn="CLOUD_SESSION_ERROR:",gt="__cline_create_request__:";function bt(e){return(e.trim().split(`
21
+ `)[0]??"").trim().slice(0,72)}class g extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${Qn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class yt extends g{constructor(e){super("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list or dashboard before starting another task.");this.name="CloudCreationUnconfirmedError",this.cause=e}}class wt extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function Pe(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function Yn(e){return`${gt}${e}`.slice(0,255)}function ht(e){return e?.startsWith(gt)===!0}function Ae(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function ke(e){let t=Jn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function mt(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()},Kn);e.addEventListener("abort",s,{once:!0})})}function Xn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function Re(e,t,n,s){let o=Xn(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??`${Pe(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 Zn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=Pe(e.apiBaseUrl),this.appBaseUrl=Pe(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??Vn}async request(e,t={},n,s,o){let i=!1,r;while(!0){let a;try{a=typeof s==="string"?s:await this.options.getAuthToken()}catch(p){if(r)throw Re(401,void 0,this.appBaseUrl,n);throw p}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?ke(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()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(J),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),c=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,r=a.trim();continue}throw Re(d.status,c,this.appBaseUrl,n)}return c?.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&&ht(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&&ht(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 r=Number(i.id),a=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(i.name??"").trim();return[{id:r,name:d,fullName:String(i.full_name??(d||a)).trim(),url:a,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,r=n.query?.trim(),a=n.cursor?.trim();if(r)i.set("query",r);if(a)i.set("cursor",a);let d=i.size>0?`${o}?${i}`:o;try{let c=await this.request(d),p=Array.isArray(c)?c:Array.isArray(c?.items)?c.items:[],u=r?.toLowerCase();return{available:!0,branches:p.flatMap((h)=>{let l=String(h.name??"").trim();return l&&(!Array.isArray(c)||!u||l.toLowerCase().includes(u))?[l]:[]}),nextToken:Array.isArray(c)?"":String(c?.nextToken??"").trim()}}catch(c){if(c instanceof g&&c.code==="session_not_found")return{available:!1,branches:[]};throw c}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(J)]):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:ke(t)},s=Yn(e.requestId?.trim()||Wn()),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((u)=>u.title===s&&u.repoContext.repoUrl===e.repoUrl&&u.metadata.modelId===e.modelId&&(!e.branch?.trim()||u.repoContext.branch===e.branch.trim())),r=async(u)=>{if(u.status==="failed"||u.expiredAt&&Date.parse(u.expiredAt)<=Date.now()){let l=new g(u.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(u.id,n)}catch(f){if(!(f instanceof g&&(f.code==="session_not_found"||f.code==="session_expired")))throw AggregateError([l,f],"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?.(u.id),l}await e.handoff?.onOuterSessionCreated(u.id,{created:!1});let h={sessionId:u.id,status:u.status,sandboxUrl:u.sandboxUrl,cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,h);return h};if(o){let u=await i();if(u.length>1)throw new g("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(u[0])return await r(u[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(u){if(o)this.unconfirmedHandoffCreates.delete(o);throw u}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),c,p=!1;try{let u=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,()=>{p=!0}),h=u?.sessionId?.trim();if(!h)throw new g("request_failed","The cloud session service returned no session id.");c=h,await this.persistHandoffOuterSession(e,h,n,o);let l={sessionId:h,status:u.status?.trim()||"provisioning",sandboxUrl:u.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,l);return l}catch(u){if(c)throw u;let h=!p||u instanceof g&&(u.status!==void 0&&u.status>=400&&u.status<500&&u.status!==408&&u.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(u.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new wt(u);if(a.signal.aborted||!(u instanceof g)||u instanceof g&&u.code==="request_failed"&&(u.status===void 0||u.status>=500||u.status===408||u.status===409)){let f=[];try{f=await i()}catch(b){if(e.handoff)throw AggregateError([u,b],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(!e.handoff&&!h&&f.length!==1)throw new yt(u);if(f.length>1)throw new g("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let m=f[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(o)this.unconfirmedHandoffCreates.delete(o);throw u}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:ke(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(J)])},void 0,o)}catch(a){if(t.aborted)throw a;if(a instanceof g&&a.code!=="request_failed")throw a;await mt(t);continue}let r=i?.status?.trim().toLowerCase();if(n?.({phase:Ae(i?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new g("session_failed",i?.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 mt(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(J)]):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(J)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw Re(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 si}from"node:crypto";import{posix as ye}from"node:path";import{createSessionId as vo,ensureLoopbackProxyBypass as Xt,isHubProtocolCompatible as Co,resolveClineBuildEnv as So,resolveHubCommandTimeoutMs as ko}from"@cline/shared";import{HttpProxyAgent as Ro}from"http-proxy-agent";import{HttpsProxyAgent as Po}from"https-proxy-agent";import{getProxyForUrl as Ao}from"proxy-from-env";import _o from"ws";var V={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.2.0-nightly.1793312794",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"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.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","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","proxy-from-env":"^2.1.0","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/proxy-from-env":"^1.0.4","@types/ws":"^8.18.1","posthog-node":"^5.8.0",skills:"1.7.2"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var vt="session_not_found";class ie 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 _e(e){return e instanceof ie||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as Ds}from"node:child_process";import{closeSync as Ls,mkdirSync as Bs,openSync as Ns,readFileSync as qs,unlinkSync as $s}from"node:fs";import{basename as zs,dirname as Fs,join as js}from"node:path";import{fileURLToPath as Gs}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as Ws,getClineClientIdentity as Js,isBunEmbeddedModulePath as Vs,isHubDaemonProcess as Ks,resolveClineBuildEnv as jt,withHubLauncherIdentity as Qs,withResolvedClineBuildEnv as Ys}from"@cline/shared";import{createHash as ts,randomBytes as ns}from"node:crypto";import{mkdir as Ee,open as Ct,readFile as At,rename as ss,rm as Te,writeFile as os}from"node:fs/promises";import{dirname as _t,join as Ie}from"node:path";import{ensureLoopbackProxyBypass as is,isHubProtocolCompatible as rs}from"@cline/shared";import{resolveClineDataDir as K,resolveClineDir as pr}from"@cline/shared/storage";var as="CLINE_HUB_DISCOVERY_PATH",ds="CLINE_HUB_BUILD_ID",cs="CLINE_HUB_BUILD_EPOCH_MS",us=30000,ls=15000,St=100;function ps(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function fs(e){return ts("sha256").update(e).digest("hex").slice(0,12)}function hs(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 kt(e){return new Promise((t)=>setTimeout(t,e))}function ms(e){return`${e}.lock`}async function gs(e){try{let t=JSON.parse(await At(Ie(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 xe(e){await Te(e,{recursive:!0,force:!0}).catch(()=>{return})}function z(){let e=process.env[ds]?.trim();if(e)return e;return"sdk-v1-5440fffc790ba5c6e5fa7cf89479eda8b49b27304efecf0ecb12ca78ad581c61".trim()||`source-${String(V.version)}`}function bs(){let e=Number(process.env[cs]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1793312823572)?1793312823572:void 0}function re(e,t=z()){let n=rs(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 Rt(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function Pt(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 ys(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 xt(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=Rt(e.buildEpochMs),i=Rt(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let r=Pt(e.coreVersion),a=Pt(t.coreVersion);if(r&&a){let d=ys(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function Et(){return{buildId:z(),buildEpochMs:bs(),coreVersion:String(V.version)}}function ae(e,t){let n=t?.self??Et(),s=re(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return xt(n,e)<=0}function Tt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${fs(e)}`,n=process.env[as]?.trim()||Ie(K(),"locks","hub","owners",`${ps(t)}.json`);return{ownerId:t,discoveryPath:n}}async function B(e,t={}){try{let n;try{n=await At(e,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let s;try{s=JSON.parse(n)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!s||typeof s.hubId!=="string"||typeof s.protocolVersion!=="string"||typeof s.authToken!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string"||typeof s.startedAt!=="string"||typeof s.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:s.hubId,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,authToken:s.authToken,host:s.host,port:s.port,url:s.url,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:s.startedAt,updatedAt:s.updatedAt}}catch(n){if(t.onError==="throw")throw n;return}}async function It(e,t){await Mt(e,async()=>{let n=_t(e);await Ee(n,{recursive:!0});let s=`${e}.${process.pid}.${ns(6).toString("hex")}.tmp`,o;try{o=await Ct(s,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
22
+ `,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await ss(s,e);let i;try{i=await Ct(n,"r"),await i.sync()}catch{}finally{await i?.close().catch(()=>{return})}}catch(i){throw await o?.close().catch(()=>{return}),await Te(s,{force:!0}).catch(()=>{return}),i}})}async function F(e){await Mt(e,async()=>{await Te(e,{force:!0}).catch(()=>{return})})}async function Ht(e,t,n){let s=ms(e);await Ee(_t(s),{recursive:!0});let o=Date.now()+ls;while(!0){try{await Ee(s,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await gs(s);if(!a){if(Date.now()>=o){await xe(s);continue}await kt(St);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!hs(a.pid)||d>us){await xe(s);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${s}`);await kt(St);continue}try{return await os(Ie(s,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
23
+ `,"utf8"),await n()}finally{await xe(s)}}}function Mt(e,t){return Ht(`${e}.mutation`,"discovery mutation",t)}function Ot(e,t){return Ht(e,"startup",t)}async function de(e,t){is();try{let n=await fetch(t?.authToken?ws(e):Dt(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 Ut(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Dt(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function ws(e){let t=new URL(Dt(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as vs,CLINE_HUB_PORT as Cs,resolveClineBuildEnv as Ss}from"@cline/shared";var ks="CLINE_HUB_HOST",Rs="CLINE_HUB_PORT",Ps="CLINE_HUB_PATHNAME",As="127.0.0.1",_s=Cs,xs="/hub";function Lt(e){return Ss(e)==="development"?vs:_s}function Es(e={}){return(e.env??process.env)[ks]?.trim()||As}function Ts(e={}){let n=(e.env??process.env)[Rs]?.trim();if(!n)return Lt(e);let s=Number.parseInt(n,10);if(!Number.isInteger(s)||s<1||s>65535)return Lt(e);return s}function Is(e={}){return(e.env??process.env)[Ps]?.trim()||xs}function Bt(e={},t={}){return{host:e.host??Es(t),port:e.port??Ts(t),pathname:e.pathname??Is(t)}}import{join as Hs}from"node:path";var Ms="shared:cline",Os="CLINE_HUB_DISCOVERY_PATH",Us="hub-production";function Q(e=Ms){return Tt(`${e}@${z()}`)}function ce(){return{ownerId:Us,discoveryPath:process.env[Os]?.trim()||Hs(K(),"locks","hub","production.json")}}var Nt=15000,Xs=200,qt=3000,Zs=100,eo=[100,250,500,1000,2000],Gt="--cline-hub-daemon",to=3,no=60000,$t=new Map;function so(e,t=Date.now()){let n=$t.get(e);if(!n||t-n.windowStartedAt>no)return $t.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=to}function oo(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function io(){try{let e=js(K(),"logs","hub-daemon.log");return Bs(Fs(e),{recursive:!0}),{fd:Ns(e,"a"),logPath:e}}catch{return}}function ro(){return jt()==="production"?ce():Q()}function Y(e){return ae(e)}function ao(e){try{let t=JSON.parse(qs(`${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 He(e){try{$s(`${e}.superseded`)}catch{}}function zt(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function X(e,t){try{return await de(e,{authToken:t})}catch{return}}async function Ft(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await X(e))?.url)return!0;await new Promise((o)=>setTimeout(o,Zs))}return!1}async function Oe(e,t){if(!so(e.url))return!1;await Z(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Jt(e.url,e.authToken).catch(()=>!1);let n=await Ft(e.url,qt);if(!n&&e.pid&&co(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Ft(e.url,qt)}if(n)await F(t).catch(()=>{return});return n}function co(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function uo(e){try{let t=await Ue(e.url,e.authToken);return t.activeSessionCount>0||(t.activePluginRequests??0)>0||(t.activeCloudCommands??0)>0}catch{return!1}}async function Me(e,t){if(Y(e))return"reusable";let n=await Z(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await uo(e)){if(n)await Z(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let s=await Oe(e,t);if(!s&&n)await Z(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return s?"retired":"failed"}async function lo(e){if(jt()!=="production")return;let t=Q();if(t.discoveryPath===e.discoveryPath)return;let n=await B(t.discoveryPath);if(n?.url)await Oe(n,t.discoveryPath);else await F(t.discoveryPath).catch(()=>{return})}function po(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return Gs(new URL(`./entry.${e}`,import.meta.url))}function fo(e,t){if(Vs(e))return[Gt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}var ue;function ho(e,t){let n,s;if(ue)n=ue.command,s=ue.args??[Gt];else{let o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let i=zs(o).toLowerCase().includes("bun");n=o,s=fo(po(),i)}return{launcher:n,args:[...s,"--cwd",e,...oo(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...Qs(Ys({...process.env,...ue?.env}),mo()),CLINE_NO_INTERACTIVE:"1",[Ws]:"1"}}}function mo(){let e=Js(),t=e?.name?.trim();return t?{client:t,version:e?.version,transport:"local"}:void 0}function go(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 bo(e,t={}){if(Ks())return;let n=ho(e,t),s=io();try{Ds(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)Ls(s.fd)}}async function yo(e,t={}){for(let n=0;;n++)try{bo(e,t);return}catch(s){let o=eo[n];if(!go(s)||o===void 0)throw s;await new Promise((i)=>setTimeout(i,o))}}async function wo(e,t,n={}){let s=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Bt(n),i=Ut(o.host,o.port,o.pathname),r=(f)=>{if(!s)le(f.url,f.authToken);return f};await lo(e).catch(()=>{return});let a=await B(e.discoveryPath),d=a?.url?void 0:ao(e.discoveryPath),c=!1;if(a?.url){let f=a.authToken;if(!f)c=!0,await Oe(a,e.discoveryPath);else{let m=await X(a.url,f);if(m?.url&&Y(m)&&await L(m.url,{authToken:f}))return He(e.discoveryPath),r({url:m.url,authToken:f});if(m?.url){if(await Me({...m,authToken:f},e.discoveryPath)==="deferred_busy"&&await L(m.url,{authToken:f}))return r({url:m.url,authToken:f})}else await F(e.discoveryPath).catch(()=>{return})}}let p=await X(i);if(p?.url){let f=zt(p,a??d,i);if(Y(p)){let b=[p.authToken,a?.authToken,d?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0);for(let v of b){if(!await L(p.url,{authToken:v}))continue;let R={hubId:p.hubId??`repaired-${p.port}`,protocolVersion:p.protocolVersion,minClientProtocolVersion:p.minClientProtocolVersion,maxClientProtocolVersion:p.maxClientProtocolVersion,capabilities:p.capabilities,coreVersion:p.coreVersion,buildId:p.buildId,authToken:v,host:p.host,port:p.port,url:p.url,pid:p.pid??a?.pid??d?.pid,startedAt:p.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await It(e.discoveryPath,R)}catch{}return He(e.discoveryPath),r({url:p.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.${c?" 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 Me(f,e.discoveryPath);if(m==="deferred_busy"){for(let b of[f.authToken,a?.authToken].filter((w)=>typeof w==="string"&&w.trim().length>0))if(await L(p.url,{authToken:b}))return r({url:p.url,authToken:b});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 n.beforeSpawn?.(),await yo(t,{...h,manageConnectors:n.manageConnectors});let l=Date.now()+Nt;while(Date.now()<l){let f=await B(e.discoveryPath);if(f?.url&&f.authToken){let b=await X(f.url,f.authToken);if(b?.url&&Y(b)&&await L(b.url,{authToken:f.authToken}))return He(e.discoveryPath),r({url:b.url,authToken:f.authToken})}let m=await X(i);if(m?.url&&!Y(m)){let b=zt(m,f??d,i),w=await Me(b,e.discoveryPath);if(w==="deferred_busy"&&f?.authToken&&await L(m.url,{authToken:f.authToken}))return r({url:m.url,authToken:f.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((b)=>setTimeout(b,Xs))}throw Error(`Timed out after ${Nt}ms waiting for detached hub startup.`)}async function Wt(e,t={}){let n=ro();return await Ot(n.discoveryPath,async()=>wo(n,e,t))}function xo(){return So()==="production"?ce():Q()}function Eo(){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 To(e){let t=new URL(e);t.protocol=e.protocol==="wss:"?"https:":"http:";let n=Ao(t.toString());if(!n)return;return e.protocol==="wss:"?new Po(n):new Ro(n)}function Zt(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 Zt(e.data);return String(e)}function Io(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 Vt(e){let t=e,n=Io(t.reason);return new A("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Be,{closeCode:t.code,closeReason:n||void 0})}function De(e,t){if(e instanceof A)return e;if(e instanceof Error)return new A("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new A("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 A("hub_connect_failed",n);let s=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new A("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 Le="*",pe=8000,Ho="cline-hub-auth.",en=new Map,tn=new Set,Mo=3000;var Be="Hub connection closed",Oo=250,Uo=5000,Kt=0.5;class A extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Do(e){return e instanceof A}class ee extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function qe(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let s=$e(e.toString());return s?en.get(s):void 0}function Lo(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 $e(e){if(!Lo(e))return;let t=new URL(nn(e));return t.search="",t.hash="",t.toString()}function Qt(e){let t=$e(e);return!!t&&tn.has(t)}function le(e,t){let n=$e(e);if(n){if(tn.add(n),t?.trim())en.set(n,t)}return e}class te{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 A("hub_connection_closed",Be);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()||qe(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(r)=>{if(o=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(V.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 i=this.connectPromise;try{await i}catch(r){if(this.connectPromise===i)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=De(r,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw r}}async openSocket(e,t,n){let s=this.options.resolveConnectionHeaders,o;if(s){let c;try{o=await Promise.race([Promise.resolve().then(()=>s()),new Promise((p,u)=>{c=setTimeout(()=>{u(new A("hub_connect_timeout",`Timed out resolving hub connection headers after ${pe}ms`))},pe)})])}catch(p){let u=p instanceof A?p:new A("hub_connect_failed",p instanceof Error?p.message:String(p));if(n===this.connectGeneration)this.lastCloseError=u;throw u}finally{clearTimeout(c)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((c)=>c.toLowerCase()==="sec-websocket-protocol")){let c=new A("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=c;throw c}let i;try{i=o?To(e):void 0}catch(c){let p=De(c,e);if(n===this.connectGeneration)this.lastCloseError=p;throw p}let r=o?new _o(e.toString(),{headers:{...o},agent:i}):new(Eo())(e.toString(),t?[`${Ho}${t}`]:void 0);this.socket=r;let a=!1,d=new Promise((c,p)=>{let u=!1,h=setTimeout(()=>{if(u)return;u=!0,a=!0;let l=new A("hub_connect_timeout",`Timed out connecting to hub after ${pe}ms`);if(this.socket===r)this.lastCloseError=l,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{r.close()}catch{}p(l)},pe);r.addEventListener("open",()=>{if(u)return;u=!0,clearTimeout(h),c()}),r.addEventListener("error",(l)=>{if(u)return;u=!0,clearTimeout(h);let f=De(l,e);if(this.socket===r)this.lastCloseError=f,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;p(f)}),r.addEventListener("close",(l)=>{if(u)return;u=!0,clearTimeout(h);let f=a?this.lastCloseError:Vt(l);if(this.socket===r){if(!a)this.lastCloseError=f,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}p(f)})});return r.addEventListener("message",(c)=>{this.handleFrame(JSON.parse(Zt(c)))}),r.addEventListener("close",(c)=>{if(this.socket!==r)return;if(!a)this.lastCloseError=Vt(c),this.sawSocketClose=!0;this.registered=!1;for(let p of this.pendingReplies.values())p.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await d,r}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=!1,r={...s,onDispatch:(d)=>{i=!0,s?.onDispatch?.(d)}},a=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,r)}catch(d){if(!a||i&&s?.retryAfterDispatch===!1||o>=1||!await this.recoverLocalHubTransport(d))throw d;o+=1}}async commandOnce(e,t,n,s,o=!0){if(o)await this.connect();s?.beforeDispatch?.();let i=vo("hubreq_");s?.onDispatch?.(i);let r=ko(e,s?.timeoutMs),a=new Promise((c,p)=>{let u=r===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;p(new ee(e,"hub_command_timeout",`Hub command ${e} timed out after ${r}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.`))},r);this.pendingReplies.set(i,{resolve:(h)=>{if(u)clearTimeout(u);c(h)},reject:(h)=>{if(u)clearTimeout(u);p(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:r,payload:t}})}catch(c){throw this.pendingReplies.delete(i),c}let d=await a;if(!d.ok){if(d.error?.code===vt){let c=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new ie(c,d.error.message)}throw new ee(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Qt(this.currentUrl)||!Do(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Yt({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(Oo*2**this.reconnectAttempt,Uo),t=Math.round(e*(1-Kt)+Math.random()*e*Kt);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(!Qt(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Yt({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 A("hub_connection_closed",Be);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 A("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??Le}subscriptionSessionIdFromKey(e){return e===Le?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[Le,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 nn(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 L(e,t){let n=new te({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 Ne(e,t){let n=nn(e),s=await de(n,{authToken:t?.authToken});if(!s)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=z(),i=re(s,o);if(!i.compatible&&!ae(s))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!Co(s).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await L(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function Bo(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 r=i.participants;if(!Array.isArray(r)||r.length===0)continue;n+=1;for(let a of r){let d=a&&typeof a==="object"?a.clientId:void 0;if(typeof d==="string"&&d.trim())s.add(d)}}let o=(i)=>{let r=e&&typeof e==="object"?e[i]:void 0;return typeof r==="number"&&Number.isInteger(r)&&r>0?r:0};return{activeSessionCount:n,participantClientCount:s.size,activePluginRequests:o("activePluginRequests"),activeCloudCommands:o("activeCloudCommands")}}async function Ue(e,t,n){let s=new te({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:Mo});return Bo(o.payload)}finally{await s.dispose().catch(()=>{return})}}async function No(e,t,n){try{let s=await Ue(e,t,n);return s.activeSessionCount===0&&s.activePluginRequests===0&&s.activeCloudCommands===0}catch{return!1}}async function qo(e,t){let n=`${e.discoveryPath}.superseded`,s=await B(n);if(!s?.url||!s.authToken)return;let o=await Ne(s.url,{authToken:s.authToken});if(o.status!=="compatible")return;if(await No(o.url,s.authToken,t))return;return le(o.url,s.authToken)}async function $o(e={}){if(e.endpoint?.trim()){let o=await Ne(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=xo(),n=await B(t.discoveryPath);if(!n?.url)return await qo(t,e);let s=await Ne(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(s.status==="compatible")return le(s.url,n.authToken);if(s.status==="protocol_mismatch")await F(t.discoveryPath).catch(()=>{return});return}async function Yt(e={}){let t=await $o(e);if(t&&await L(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Wt(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function Z(e,t,n,s){Xt();let o=new URL(e),i=t?.trim()||qe(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 Jt(e,t){Xt();let n=new URL(e),s=t?.trim()||qe(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}import{MODEL_COLLECTIONS_BY_PROVIDER_ID as zo}from"@cline/llms";import{modelSupportsImageInput as Fo}from"@cline/shared";function sn(e){let t=zo.cline?.models?.[e];return t?Fo(t):!1}var ze="## Verify your work visually\n\nThis sandbox may have a virtual display and standard Linux tools for computer use: Xvfb, xdotool, ImageMagick (`import`), wmctrl, and Chromium. Check with `command -v Xvfb xdotool import chromium` the first time you need them. If any are missing, skip visual verification and don't try to install them. To see a screenshot, call `read_files` on the image file.\n\n### When to verify\n\nUse your judgment. Verify when a change affects something a user sees or interacts with (a navbar style, a new dialog, a form flow, a terminal UI). Skip it when there's nothing to look at (a git operation, a config tweak, a refactor with no visible effect).\n\n### Display, input, and screenshots\n\n- Start the display if it isn't running: `Xvfb :99 -screen 0 1280x800x24 -nolisten tcp &`, and run every GUI command with `DISPLAY=:99` (for example `export DISPLAY=:99` at the start of the command). Keep the display as small as the check allows so screenshots stay legible. To check a phone layout, restart Xvfb at 390x844 and relaunch the app window at 0,0 with the same size.\n- Start the app (for example `bun run dev &`) and wait until it's serving.\n- Open web apps in a normal Chromium window so screenshots look like a real browser:\n `chromium --new-window http://localhost:5173 --remote-debugging-port=9222 --window-position=0,0 --window-size=1280,800 --force-device-scale-factor=1 --user-data-dir=\"$(mktemp -d)\" --no-first-run --no-default-browser-check --disable-features=Translate --disable-gpu --no-sandbox &`\n - `--remote-debugging-port=9222` exposes the Chrome DevTools Protocol, so you can inspect the DOM, console, and network when a screenshot alone doesn't explain a problem.\n - A fixed position and size, plus `--force-device-scale-factor=1`, keep screenshot pixels equal to click coordinates.\n - A fresh `--user-data-dir` and the first-run flags keep restore prompts and popups out of screenshots. `--disable-gpu` and `--no-sandbox` are needed in this container.\n- Drive the app with xdotool: `key`, `type --delay 40 --`, `mousemove X Y click 1` (buttons 4 and 5 scroll). Find the window with `xdotool search --sync --onlyvisible --class chromium | tail -1` and focus it with `xdotool windowfocus --sync <id>`.\n- Take screenshots of the whole display, for example `import -window root /tmp/cu-shots/03-filtered.png`, so every frame has the same size and framing. Wait about half a second after each action so the UI settles. To look closely at one area, crop a copy instead of capturing a region.\n- Take a fresh screenshot before every click and click in that screenshot's coordinates; layouts move. If a click misses, look again before retrying.\n- Move the pointer out of the way before screenshots you'll show the user, so hover states don't leak in.\n\nExample of a loop that works well:\n\n```bash\nexport DISPLAY=:99\nmkdir -p /tmp/cu-shots\nWID=$(xdotool search --sync --onlyvisible --class chromium | tail -1)\nxdotool windowfocus --sync \"$WID\"\nxdotool key ctrl+k && sleep 0.5 && import -window root /tmp/cu-shots/01-palette.png\nxdotool type --delay 40 -- \"over\" && sleep 0.5 && import -window root /tmp/cu-shots/02-search.png\nxdotool mousemove 640 228 click 1 && sleep 0.5 && import -window root /tmp/cu-shots/03-filtered.png\n```\n\n### What to check\n\n- Check the states that usually break: empty, loading, error, long content, dark mode, and a narrow viewport.\n- If something looks wrong, fix it, reload, and check again.\n- Read only the screenshots you need; each one costs context (about 1.4k tokens at 1280x800).\n- Never close the window you're testing, and never put secrets (tokens, passwords, `.env` contents) on screen.\n\n### Show the user what you verified\n\nThe user can't see this sandbox, and its files disappear when it stops. When you've verified something, publish the few screenshots that prove it with the `publish_artifacts` tool, which uploads them to this session so the user can open them. Pass absolute paths, for example `{\"files\": [{\"path\": \"/tmp/cu-shots/01-palette.png\"}, {\"path\": \"/tmp/cu-shots/03-filtered.png\"}]}`.\n\n- Publish frames for the reader, not a log of every input: usually 1 to 8 per thing you verified, in the order that tells the story (at most 20 per call).\n- The tool reports an `artifactId` or an `error` for each file. To retry a failed file, pass the same `artifactId` back. If publishing fails or the tool isn't available, say so in your answer and carry on.\n- In your answer, say what each published screenshot shows, in order, and call out anything you couldn't fix.";function jo(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 Fe(e,t){return Array.isArray(e)?e.flatMap((n)=>{let s=jo(n,t);return s?[s]:[]}):[]}async function on(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 b=await(t.fetchImpl??fetch)(`${o}${m}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!b.ok)throw Error(`HTTP ${b.status}`);return await b.json()},r,a;try{[r,a]=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=r&&typeof r==="object"?r:void 0,c=Fe(Array.isArray(r)?r:d?.data,"cline"),p=a&&typeof a==="object"?a:void 0,u=p?.data&&typeof p.data==="object"?p.data:p,h=Fe(u?.clinePass,"cline-pass"),l=Fe(u?.clineCloud,"cline-cloud"),f=new Set;return[...t.isOrganizationSession?[]:h,...l,...c].filter((m)=>{if(f.has(m.id))return!1;return f.add(m.id),!0})}import{formatDisplayUserInput as rn}from"@cline/shared";var Go=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function Wo(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function Jo(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function Vo(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function Ko(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(`
24
+ `)}}function Qo(e){let t=rn(e);return t.startsWith("[TASK RESUMPTION]")||t==="The user approved switching to act mode. Continue with the approved plan now."}function Yo(e){if(Wo(e.role)!=="user")return 0;let t=Jo(e),n=typeof t?.kind==="string"?t.kind:void 0,s=Vo(t);if(n==="compaction"||n==="compaction_summary")return s??1;if(s!==void 0)return s;if(n&&Go.has(n))return 0;let o=Ko(e);if(!o.hasAttachment&&!rn(o.text))return 0;if(!o.hasAttachment&&Qo(o.text))return 0;return 1}function an(e){return Yo(e)>0}function me(e){return Array.isArray(e?.sessions)?e.sessions.filter((t)=>Boolean(t)&&typeof t==="object"&&!Array.isArray(t)):[]}function je(e){let t=e.updatedAt;return typeof t==="number"?t:Date.parse(String(t??""))||0}function Ge(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return String(t?.model??e?.model??"").trim()}function ge(e){let t=e.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return!String(t?.parentSessionId??e.parentSessionId??"").trim()}function ln(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 fe(e){let t=e.trim(),n=t.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(n?n[1]:t).trim()}function ne(e,t,n){let s=fe(n);return e.filter((o)=>Boolean(o)&&typeof o==="object"&&!Array.isArray(o)&&String(o.role??"").toLowerCase()==="user"&&(s!==""||an(o))&&fe(ln(o))===s).length+t.filter((o)=>fe(o.prompt)===s).length}function We(e){return e.flatMap((t)=>{if(t.event!=="session.pending_prompt_submitted")return[];let n=t.payload?.prompt&&typeof t.payload.prompt==="object"&&!Array.isArray(t.payload.prompt)?t.payload.prompt:void 0,s=String(n?.id??"").trim();if(!s)return[];return[{id:s,prompt:String(n?.prompt??""),steer:n?.delivery==="steer",attachmentCount:typeof n?.attachmentCount==="number"?n.attachmentCount:0,userImages:Array.isArray(n?.userImages)?n.userImages.filter((o)=>typeof o==="string"):void 0}]})}var Xo=new Set(["run.completed","run.aborted","run.failed"]),Zo=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function dn(e,t){return e.filter((n)=>Boolean(n)&&typeof n==="object"&&!Array.isArray(n)&&String(n.role??"").toLowerCase()==="assistant").map((n)=>ln(n,t)).filter(Boolean)}function cn(e,t,n="text"){let s=new Map;for(let o of dn(t,n))s.set(o,(s.get(o)??0)+1);return dn(e,n).filter((o)=>{let i=s.get(o)??0;if(i===0)return!0;if(i===1)s.delete(o);else s.set(o,i-1);return!1})}function he(e,t,n=new Set){if(!e||typeof e!=="object")return n;if(Array.isArray(e)){for(let i of e)he(i,t,n);return n}let s=e,o=t==="tool_use"?s.id:s.tool_use_id;if(s.type===t&&typeof o==="string")n.add(o);for(let i of Object.values(s))he(i,t,n);return n}function un(e,t="assistant"){let n="",s="";for(let o of e)if(o.event===`${t}.delta`)s+=t==="reasoning"&&o.payload?.redacted&&!o.payload?.text?"[redacted]":typeof o.payload?.text==="string"?o.payload.text:"";else if(o.event===`${t}.finished`){let i=o.payload?.[t==="assistant"?"text":"reasoning"],r=typeof i==="string"&&i?i:s;if(r)n=r;s=""}return(n||s).trim()}function pn(e,t,n={}){let s=n.queueSnapshotApplied!==!1,o=cn(t,n.baselineMessages??[]),i=cn(t,n.baselineMessages??[],"thinking"),r=he(t,"tool_use"),a=he(t,"tool_result"),d=new Set(e.slice(0,n.messagesSnapshotEventCutoff??e.length)),c=new Set,p=new Map;for(let b of e.slice(0,n.messagesSnapshotEventCutoff??e.length)){let w=We([b])[0];if(!w)continue;let v=fe(w.prompt),R=p.get(v)??Math.max(0,ne(t,[],v)-ne(n.baselineMessages??[],[],v));if(p.set(v,Math.max(0,R-1)),R>0)c.add(b)}let h=[...s?e.slice(n.queueSnapshotEventCutoff??e.length):e].reverse().find((b)=>b.event==="session.pending_prompts"),l=[],f=[],m=(b)=>{if(f.length===0)return;let w=f.filter((E)=>d.has(E)),v=(E)=>{if(!b)return-1;let P=[...w].reverse().findIndex((yn)=>yn.event===`${E}.finished`),G=P<0?-1:w.length-1-P;return G>=0||f.at(-1)?.event==="run.aborted"?G:w.length-1},R=v("assistant"),y=v("reasoning"),_=un(w.slice(0,R+1)),S=_?o.findIndex((E)=>E.endsWith(_)):-1,x=S>=0;if(x)o.splice(S,1);let I=un(w.slice(0,y+1),"reasoning"),M=I?i.findIndex((E)=>E.endsWith(I)):-1;if(M>=0)i.splice(M,1);for(let[E,P]of f.entries()){if(c.has(P)){l.push({...P,payload:{...P.payload,transcriptReflected:!0}});continue}if(d.has(P)&&Zo.has(P.event)&&(P.event.startsWith("reasoning.")?M>=0&&E<=y:x&&E<=R))continue;if(P.event==="session.pending_prompts"&&P!==h)continue;if(d.has(P)&&P.event.startsWith("tool.")){let G=String(P.payload?.toolCallId??"").trim();if(a.has(G)||P.event==="tool.started"&&r.has(G))continue}l.push(P)}f=[]};for(let b of e)if(f.push(b),Xo.has(b.event))m(!0);return m(!1),l}import{formatDisplayUserInput as ei}from"@cline/shared";function j(e){let t=structuredClone(e),n=(s)=>{if(!s||typeof s!=="object"||Object.isFrozen(s))return;for(let o of Object.values(s))n(o);Object.freeze(s)};return n(t),t}function be(e){let t=e?.trim();return t?ei(t).slice(0,120):void 0}function Je(e){if(typeof e==="string")return e;if(Array.isArray(e)){let t=[];for(let n of e){if(typeof n==="string"){if(n.trim())t.push(n);continue}if(!n||typeof n!=="object")continue;let s=n,o=typeof s.type==="string"?s.type:"",i=o==="text"?String(s.text??""):o==="thinking"?String(s.thinking??""):o==="tool_use"?`[tool] ${String(s.name??"tool_call")}`:o==="tool_result"?`[tool_result]
25
+ ${Je(s.content)}`:o==="image"?"[image]":o==="redacted_thinking"?"[redacted_thinking]":typeof s.text==="string"?s.text:"";if(i.trim())t.push(i)}return t.join(`
26
+ `)}if(e&&typeof e==="object"){let t=e;if(typeof t.text==="string")return t.text}return""}function ti(e){let t=be(e??void 0);if(!t)return;return t.split(`
27
+ `)[0]?.trim().slice(0,70)||void 0}function ni(e){for(let t of["user","assistant"])for(let n of e){if(!n||typeof n!=="object")continue;let s=n;if(s.role!==t)continue;let o=be(Je(s.content));if(!o)continue;return o.split(`
28
+ `)[0]?.trim().slice(0,70)||void 0}return}function Ve(e){let t=e.metadata&&typeof e.metadata==="object"?be(e.metadata.title):void 0;if(t)return t.slice(0,70);let n=ti(e.prompt);if(n)return n;let s=e.messages?ni(e.messages):void 0;if(s)return s;return`Session ${e.sessionId.slice(-6)}`}function fn(e,t,n,s){let o=t.payload??{},i=()=>{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,c)=>{let p=i(),u=p.at(-1);if(u?.type===a)u[d]=`${u[d]??""}${c}`;else p.push({type:a,[d]:c})};switch(t.event){case"assistant.delta":if(typeof o.text==="string")r("text","text",o.text);return;case"reasoning.delta":if(typeof o.text==="string"&&o.text)r("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 a=String(o.toolCallId??"");if(a&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((c)=>c.type==="tool_use"&&c.id===a)))i().push({type:"tool_use",id:a,name:String(o.toolName??"tool"),input:structuredClone(o.input??{})});return}case"tool.finished":{let a=String(o.toolCallId??"");if(a&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((c)=>c.type==="tool_result"&&c.tool_use_id===a)))e.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:a,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 a=Array.isArray(o.prompts)?o.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((c)=>typeof c==="string"):void 0})).filter((d)=>d.id&&(d.prompt||d.attachmentCount));return}case"session.pending_prompt_submitted":{let a=o.prompt,d=String(a?.id??"");if(!d||e.lastQueuedPromptStartId===d)return;if(e.lastQueuedPromptStartId=d,e.promptsInQueue=e.promptsInQueue.filter((c)=>c.id!==d),o.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=o.session,d=typeof a?.status==="string"?a.status:t.event==="run.started"?"running":e.status,c=d==="pending"?"running":d;if(t.event==="session.updated"&&c==="running"&&e.endedAt!==void 0&&!e.busy)return;let p=e.busy;if(e.status=c,e.busy=c==="running",t.event==="run.started"){if(!p)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 Ke(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 Qe(e,t){return e instanceof Error&&e.name==="HubCommandError"&&e.code==="hub_command_timeout"&&(!t||e.command===t)}var k="/workspace",oi=30000,ii=2000,ri=2000,gn="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 ai(e,t={}){let n=`cline/${(e.metadata.taskId?.trim()||e.id).slice(-8).toLowerCase()}`,s=e.sandboxType==="resumable"||e.metadata.sandboxType==="resumable";return`${gn}
16
29
 
17
- Do all work for this task on the branch \`${t}\`: 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. `+(n?"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 \`${t}\` 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 ${t}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks."}function Fe(e){if(!e)return C;if(ue.isAbsolute(e)||e.includes("\\")||e.split("/").some((n)=>!n||n==="."||n===".."))throw new m("request_failed","The handoff workspace path must stay inside the repository.");let t=ue.join(C,e);if(!t.startsWith(`${C}/`))throw new m("request_failed","The handoff workspace path must stay inside the repository.");return t}function Ke(e){let t=e.metadata.cwd;return typeof t==="string"&&ue.normalize(t)===t&&(t===C||t.startsWith(`${C}/`))?t:C}function en(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 Ge extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud conversation creation was not dispatched.",{cause:e});this.name="CloudHandoffSeedRejectedError"}}class Ve extends m{constructor(){super("request_failed","The connection was interrupted and Cline could not confirm whether this message was queued. Check the cloud session before resending it.");this.name="CloudQueueUnconfirmedError"}}class sn 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 Eo(e){return e.trim().startsWith("ses-")}function Ho(e,t){let n=new URL(`/api/v1/session/${encodeURIComponent(t)}`,e);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.toString()}function ze(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:Ke(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 Je(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:Ke(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 tn(e){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:e.status,provider:"cline",model:e.metadata.modelId??"",cwd:Ke(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 Io(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function Mo(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 Oo{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 J(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=ze(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)Zt(n,t,this.streamingMessages,e)}async respondApproval(e,t,n){this.assertSessionActive(e);let s=this.approvals.get(`${e}:${t}`);if(!s){if(!this.connections.has(e))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new m("request_failed","This approval was already resolved or is no longer available.")}await s.resolve(n)}async detach(e){this.detachedSessions.add(e),this.sessionGenerations.set(e,(this.sessionGenerations.get(e)??0)+1),this.connectionPromises.delete(e),this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud viewer detached")),await this.disposeConnection(e),this.publishSnapshot(e)}isCloudSession(e){return Eo(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?tn(t):void 0}async getCrossScopeDiscoveryRecord(e){let t=this.getCachedDiscoveryRecord(e);if(!t)return;try{let s=(await this.options.api.status(e)).status?.trim();return s?{...t,status:s}:t}catch(n){if(n instanceof m&&(n.code==="session_not_found"||n.code==="session_expired")){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e);return}return t}}async list(){if(this.disposed)throw Error("Cloud session controller was disposed");let e=(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(),o=(await this.options.api.list(s)).map((r)=>this.preserveConnectedRuntimeModel(r));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedSessions=o;for(let r of o)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 i=await Promise.all(o.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 i){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 l=T(r);if(l||r.status==="failed"||r.status==="suspended"){if(a)a.busy=!1,a.status=l?"expired":r.status,a.endedAt=l?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=i;for(let r of i)if(this.sessions.has(r.id))this.publishSnapshot(r.id);return de(i)}async handoffTargetExists(e){try{return await this.options.api.status(e),!0}catch(t){if(t instanceof m&&(t.code==="session_not_found"||t.code==="session_expired"))return!1;throw t}}preserveConnectedRuntimeModel(e){let t=this.connections.get(e.id)?.remote.metadata,n=t?.cwd??this.knownSessions.get(e.id)?.metadata.cwd;return{...e,metadata:{...e.metadata,...t?.modelId?{modelId:t.modelId}:{},...n?{cwd:n}:{}}}}async resolveActiveOrganizationId(e){return await this.options.getActiveOrganizationId?.(e)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listModels(){if(this.disposed)throw Error("Cloud session manager was disposed");let e=await this.resolveActiveOrganizationId({fresh:!0}),t=await zt(this.options.apiBaseUrl,{isOrganizationSession:Boolean(e)});if(this.disposed)throw Error("Cloud session manager was disposed");return t}async prepareHandoffRepository(e){let t=await this.resolveActiveOrganizationId(),n=await this.options.api.listRepositories(t);if(!n.connected)throw new m("github_not_connected","Connect GitHub before handing this session off to cloud.",n.connectUrl);let s=(o)=>o.trim().replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();if(!n.repositories.some((o)=>s(o.url)===s(e)))throw new m("github_not_connected",`The GitHub integration cannot access ${e}. Grant repository access before handing off.`,n.connectUrl);return t?{organizationId:t}:{}}async listBranches(e,t={}){return await this.options.api.listBranches(e,await this.resolveActiveOrganizationId(),t)}async listForDiscovery(e={}){let t=this.discoveryRefresh??this.list().finally(()=>{if(this.discoveryRefresh===t)this.discoveryRefresh=void 0});this.discoveryRefresh=t;let n=this.lastListedSessions;if(e.timeoutMs===void 0)n=await t;else{let i,r=await Promise.race([t.then((a)=>({value:a}),(a)=>{if(!(a instanceof m&&a.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:a});return{value:this.lastListedSessions}}),new Promise((a)=>{i=setTimeout(()=>a({value:this.lastListedSessions}),Math.max(0,e.timeoutMs??0))})]);if(i)clearTimeout(i);n=r.value}return[...new Map([...this.unlistedSessions.values(),...n].map((i)=>[i.id,i])).values()].map((i)=>{let r=tn(i),a=this.sessions.get(i.id);if(!a)return r;let d=a.title?.trim()||i.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:$e({sessionId:i.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){Fe(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 r=i.payload?.messages;if(!Array.isArray(r))throw Error("Cloud runtime returned no transcript after seeding.");if(t.length>0&&r.length===0)throw new sn;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=Fe(e.workspaceRelativePath),n=e.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):e.organizationId??void 0,s=e.handoff,o=!s,i=await this.options.api.create({...e,organizationId:n,...s&&{handoff:{...s,onOuterSessionCreated:async(h,p)=>{o=p?.created===!0,await s.onOuterSessionCreated(h,p)}}}});if(!i?.sessionId?.trim())throw new m("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(o&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(i.sessionId,i.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let r={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(r.id,r),this.unlistedSessions.set(r.id,r);let{autoApproveTools:a,thinking:d,reasoningEffort:l}=e;this.pendingInitialTasks.set(r.id,{autoApproveTools:a,thinking:d,reasoningEffort:l});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&&o&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(r.id,i.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 Je(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(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(o);let i=o.remote,r=this.sessions.get(e);return Je(i,r?.status??i.status,r?.prompt)}async send(e,t,n,s,o){let i=this.sendAbortTokens.get(e),r=this.knownSessions.get(e);if(r&&T(r))throw new m("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)!==i,l=()=>{if(d())throw Error("Cloud session prompt cancelled")};if(l(),await a.reconnectResolution,l(),await this.ensureAttached(a),await a.reconnectResolution,l(),!a.transcriptKnown)await this.rehydrateAfterTransportDrop(e,a);l(),await this.updateModel(a,s),await a.reconnectResolution,l();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),p=G(c?.messages??[],c?.promptsInQueue??[],t),u=h!=="queue"&&h!=="steer",g=c&&h!=="queue"?{role:"user",content:[{type:"text",text:t}]}:void 0;if(c&&g)c.messages=[...c.messages,g];let y=()=>{if(c&&g)c.messages=c.messages.filter((b)=>b!==g),this.publishSnapshot(e)};if(c&&u){let b=c.status!=="running";if(c.busy=!0,c.status="running",c.prompt||=t,b)this.publishSnapshot(e,!1,"status")}let w=this.knownSessions.get(e);if(w&&!w.title?.trim()&&!this.titleWrites.has(e)){let b=it(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,...o?.length?{attachments:{userImages:o}}:{}},f,{timeoutMs:h==="queue"?Po:null,onDispatch:(M)=>{v.add(M),a.pendingInputs??=new Map,a.pendingInputs.set(M,{clientId:a.client.getClientId(),ownsBusyState:u,accept:H})},beforeDispatch:()=>{if(l(),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(We(b)||je(b,"session.send_input")){let R;try{R=await this.rehydrateAfterTransportDrop(e,a)}catch(V){if(l(),y(),c&&u)c.busy=!1,c.status="error";if(h==="queue")throw new Ve;throw V}if(l(),h==="queue")throw new Ve;if(h==="steer")throw new m("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(G(R.messages,Mo(R.prompts,R.submittedPrompts),t)<=p)throw new m("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:e,ok:!0,...h==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:R.status}}if(y(),c&&u)c.busy=!1,c.status="error";throw this.publishSnapshot(e),b}finally{for(let b of v)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 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),r=this.authoritativeMessages.get(e)??[],a=String(o?.status??i?.status??"running").trim(),d=a==="pending"?"running":a;if(d==="running"&&!t.transcriptKnown&&!t.pendingInputs?.size)t.externalRun??={progressHydrated:!0};let l=()=>t.client.command("session.messages",{sessionId:n},n),f=await l().catch((b)=>{if(!je(b,"session.messages"))throw b;return this.assertSessionActive(e,t),l()});if(this.assertSessionActive(e,t),!Array.isArray(f.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let c=f.payload.messages,h=t.bufferedEventsDropped+t.bufferedEvents.length,p=await t.client.command("session.pending_prompts",{sessionId:n},n).catch(()=>{return});this.assertSessionActive(e,t);let u=t.bufferedEventsDropped+t.bufferedEvents.length;if(i){let b=i.status!==d;if(this.authoritativeMessages.set(e,structuredClone(c)),i.messages=structuredClone(c),this.streamingMessages.delete(e),i.status=d,i.busy=d==="running",b)if(d==="completed"||d==="failed"||d==="aborted")i.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:e,reason:d==="failed"?"error":d});else this.notify("chat_session_status",{sessionId:e,status:d})}let g=p!==void 0&&p.ok!==!1&&Array.isArray(p.payload?.prompts),y=g?this.applyQueueSnapshot(e,p):void 0;t.transcriptKnown=!0;let w=c;this.assertSessionActive(e,t),this.notify("cloud_session_rehydrated",{sessionId:e,status:d,transcriptKnown:!0,messages:w}),this.assertSessionActive(e,t);let v=t.bufferedEvents,P=qe(v),H=Xt(v,c,{queueSnapshotApplied:g,queueSnapshotEventCutoff:Math.max(0,u-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 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((r)=>typeof r==="string"):void 0})).filter((i)=>i.id),o=this.sessions.get(e);if(o)o.promptsInQueue=s;return this.publishSnapshot(e,!1,"queue"),s}async readMessages(e){let t=this.knownSessions.get(e);if(t?.status==="provisioning"||t?.status==="failed")return[];if(t&&T(t))return await this.loadArchivedMessages(t)??[];try{let n=await this.ensureConnection(e);if(!n.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop(e,n)).messages}catch(n){let s=await this.refreshKnownSession(e)??t;if(s){let o=await this.loadArchivedMessages(s).catch(()=>null);if(o!==null)return o}throw n}}async updateTitle(e,t){let n=this.titleWrites.get(e),s=(async()=>{await n?.catch(()=>{}),this.assertSessionActive(e),await this.options.api.updateTitle(e,t);let o=this.knownSessions.get(e);if(o)o.title=t;let i=this.sessions.get(e);if(i)i.title=t;this.publishSnapshot(e)})();this.titleWrites.set(e,s);try{await s}finally{if(this.titleWrites.get(e)===s)this.titleWrites.delete(e)}}async delete(e){this.deletingSessions.add(e),this.abortProvisioningControllers(e);try{let t=this.connectionPromises.get(e);if(t)await t.catch(()=>{return});await this.disposeConnection(e);try{await this.options.api.delete(e)}catch(n){let s=n instanceof m?n.code:"";if(s!=="session_not_found"&&s!=="session_expired")throw n}this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),this.authoritativeMessages.delete(e),this.restoredOptions.delete(e),this.publish({type:"removed",sessionId:e}),this.sendAbortTokens.delete(e);for(let[n,s]of this.approvals)if(s.item.sessionId===e)this.approvals.delete(n)}finally{this.deletingSessions.delete(e)}}async dispose(){this.disposed=!0;for(let t of this.snapshotTimers.keys())this.cancelScheduledSnapshot(t);this.sendAbortTokens.clear();for(let t of this.provisioningControllers.values())for(let n of t)n.abort();this.provisioningControllers.clear();let e=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[t,n]of this.approvals)if(e.has(n.item.sessionId))this.approvals.delete(t);for(let t of e)this.sessions.delete(t),this.knownSessions.delete(t),this.publish({type:"removed",sessionId:t});if(this.knownSessions.clear(),this.unlistedSessions.clear(),!this.options.pendingInitialTasks)this.pendingInitialTasks.clear();this.listeners.clear(),await Promise.allSettled(Array.from(this.connections.keys()).map((t)=>this.disposeConnection(t)))}async attachExpired(e){let t=this.sessions.get(e.id)??ze(e);return t.busy=!1,t.status="expired",this.sessions.set(e.id,t),await this.loadArchivedMessages(e).catch(()=>{return}),Je(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)??ze(e);return s.messages=structuredClone(n),this.sessions.set(e.id,s),this.authoritativeMessages.set(e.id,structuredClone(s.messages)),this.publishSnapshot(e.id,!0),n}async refreshKnownSession(e){let t=await this.resolveActiveOrganizationId(),n=await this.options.api.list(t).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!n)return this.knownSessions.get(e);for(let s of n)this.knownSessions.set(s.id,s);return n.find((s)=>s.id===e)}async ensureKnownSession(e){let t=this.knownSessions.get(e);if(t)return t;let n=(await this.list()).find((s)=>s.id===e);if(!n)throw new m("session_not_found",`Cloud session ${e} was not found.`);return this.knownSessions.get(e)??structuredClone(n)}assertSessionActive(e,t){if(this.disposed||t?.disposed||this.detachedSessions.has(e)||t?.generation!==void 0&&t.generation!==(this.sessionGenerations.get(e)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has(e))throw new m("session_not_found","This cloud session is being deleted.")}async ensureConnection(e,t={}){let n=this.sessionGenerations.get(e)??0,s=()=>{if(this.assertSessionActive(e),n!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during connection")};s();let o=this.connectionPromises.get(e),i=o?await o:this.connections.get(e);if(i?.remote.status==="suspended")return await this.disposeConnection(e),s(),await this.ensureConnection(e,t);if(i){if(this.assertSessionActive(e,i),await i.reconnectResolution,this.assertSessionActive(e,i),!i.innerSessionId)await i.client.connect(),await i.reconnectResolution,this.assertSessionActive(e,i),await this.resolveInnerSession(e,i,Boolean(t.handoffSeed)),this.assertSessionActive(e,i);if(t.handoffSeed&&i.innerSessionId)await this.assertHandoffConnectionReusable(i,t.handoffSeed);if(t.createInner&&!i.innerSessionId)await this.createInnerSession(i,t.handoffSeed);return this.assertSessionActive(e,i),i}let 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(p)=>{if(!(p instanceof m?p.code==="request_failed"&&(p.status===void 0||p.status===408||p.status===429||p.status>=500):p instanceof TypeError||p instanceof Error&&p.name==="TimeoutError"))throw p;return s(),await this.refreshKnownSession(e).catch(()=>{return})});if(s(),c?.status)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(u){if(!(u instanceof m)||u.status!==409)throw u;s(),c.signal.throwIfAborted();let g=await this.options.api.status(e,{signal:c.signal});if(g.status!=="provisioning"&&g.status!=="ready"&&g.status!=="active")throw u;a={...a,status:g.status}}s(),c.signal.throwIfAborted(),this.knownSessions.set(e,a);let p=this.sessions.get(e);if(p)p.status=a.status,p.busy=!1,p.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:u})=>{a.metadata.provisioningPhase=u,this.notify("chat_session_status",{sessionId:e,status:"provisioning",phase:u})}),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 p=this.sessions.get(e);if(p?.status==="provisioning")p.status="idle",p.busy=!1,p.endedAt=void 0}catch(p){if(p instanceof m&&p.code==="session_failed"){if(a.status="failed",a.metadata.statusReason=p.detail,a.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set(e,a);let u=this.sessions.get(e);if(u)u.status="error";this.notify("chat_session_status",{sessionId:e,status:"error"})}throw p}finally{h()}}if(s(),a.status==="failed")throw new m("session_failed",a.metadata.statusReason||"The cloud sandbox could not be prepared.");if(T(a))throw new m("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set(e,this.sessions.get(e)??this.stateFromRecord(a));let d,l=0,f=this.createHubClient({url:Ho(this.options.apiBaseUrl,e),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${e}-${_o()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:C,cwd:C,resolveConnectionHeaders:async()=>{s();let c=l>0;if(l+=1,d)d.connected=!1,d.reconnecting=c,this.publishSnapshot(e);if(c){let p=d;if(p&&!p.disposed){p.transcriptKnown=!1,p.innerSessionId=void 0;let u=(async()=>{if(await this.resolveInnerSession(e,p),p.innerSessionId)await this.rehydrateAfterTransportDrop(e,p)})().catch(()=>this.disposeConnectionIfSessionGone(e,p)).finally(()=>{if(p.reconnectResolution===u)p.reconnectResolution=void 0,p.connected=p.transcriptKnown,this.publishSnapshot(e)});p.reconnectResolution=u}}let h=await this.options.getAuthToken();if(!h?.trim())throw new m("authentication_required","Sign in to Cline to reconnect this cloud session.");return s(),{Authorization:`Bearer ${h.trim()}`}}});d={generation:n,remote: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(We(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(),o;if(s)try{let a=await t.client.command("session.get",{sessionId:s},s);this.assertSessionActive(e,t),o=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),o=re(a.payload).filter(ae).sort((d,l)=>De(l)-De(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 r=Be(o);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(u){if(!(we(u)||u instanceof Error&&u.code==="command_failed"&&u.message===`session not found: ${t}`))throw u}this.assertSessionActive(e.remote.id,e);let o=await e.client.command("session.messages",{},t);this.assertSessionActive(e.remote.id,e);let i=o.payload?.messages;if(!Array.isArray(i)||i.length===0)throw Error("The saved conversation is empty or unavailable.");let r=n.metadata??{},a=n.runtimeOptions??{},d=this.sessions.get(e.remote.id)?.config,l=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,p=n.workspaceRoot??C;try{let u=await e.client.command("session.create",{workspaceRoot:p,cwd:h,initialMessages:i,metadata:{...r,interactive:!0},sessionConfig:{sessionId:t,providerId:r.provider??"cline",modelId:r.model??r.modelId??e.remote.metadata.modelId,workspaceRoot:p,cwd:h,systemPrompt:a.systemPrompt??r.systemPrompt??"",mode:a.mode??r.mode??"act",...typeof l==="boolean"?{thinking:l}:{},...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),(u.payload?.session?.sessionId??u.payload?.sessionId)!==t)throw Error("Cloud Hub did not restore the requested session.")}catch(u){if(u?.code!=="session_already_exists")throw u;this.assertSessionActive(e.remote.id,e),await s()}}async assertHandoffConnectionReusable(e,t){let n=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let s=re(n.payload).filter(ae),[o]=s;if(s.length!==1||String(o?.sessionId??"").trim()!==e.innerSessionId||en(o)!==t.sourceSessionId)throw new m("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.")}async createInnerSession(e,t){if(this.assertSessionActive(e.remote.id,e),e.innerSessionCreation){if(await e.innerSessionCreation,t)await this.assertHandoffConnectionReusable(e,t);return}let n=(async()=>{if(t&&await this.adoptExistingHandoffSession(e,t)){this.unconfirmedInnerCreates.delete(e.remote.id);return}if(t?.recoverOnly||this.unconfirmedInnerCreates.has(e.remote.id))throw new m("request_failed","Cloud conversation creation is still unconfirmed. Wait for it to appear before trying again.");await this.createInnerSessionOnce(e,t)})().finally(()=>{e.innerSessionCreation=void 0});return e.innerSessionCreation=n,await n}async adoptExistingHandoffSession(e,t){let n=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let s=re(n.payload).filter(ae);if(s.length===0)return!1;let[o]=s,i=String(o?.sessionId??"").trim();if(s.length!==1||!i||en(o)!==t.sourceSessionId)throw new m("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return e.innerSessionId=i,this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,o),await this.ensureAttached(e),!0}async createInnerSessionOnce(e,t){let n=e.remote.metadata.modelId?.trim();if(!n)throw Error("Cloud session is missing its model id");let s=this.sessions.get(e.remote.id),o=Fe(t?.workspaceRelativePath),i=t?.mode??"act";try{await t?.onSeeding?.(),this.assertSessionActive(e.remote.id,e)}catch(u){if(t)throw new Ge(u);throw u}let r=xo(e.remote),a=t?.config?.thinking??s?.config.thinking,d=t?.config?.reasoningEffort??s?.config.reasoningEffort,l=!1,f=e.client.command("session.create",{workspaceRoot:C,cwd:o,...t?{initialMessages:t.messages}:{},sessionConfig:{...e.remote.metadata.taskId?.trim()?{sessionId:e.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:n,workspaceRoot:C,cwd:o,systemPrompt:t?`${nn}
30
+ Do all work for this task on the branch \`${n}\`: 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. `+(s?"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 \`${n}\` 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 ${n}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks."+(t.computerUse?`
18
31
 
19
- This session was handed off from a local workspace to a fresh Linux clone of ${e.remote.repoContext.repoUrl??"the repository"}@${e.remote.repoContext.branch??"the selected branch"} at ${C}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(o===C?"":`
32
+ ${ze}`:"")}function Ye(e){if(!e)return k;if(ye.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=ye.join(k,e);if(!t.startsWith(`${k}/`))throw new g("request_failed","The handoff workspace path must stay inside the repository.");return t}function nt(e){let t=e.metadata.cwd;return typeof t==="string"&&ye.normalize(t)===t&&(t===k||t.startsWith(`${k}/`))?t:k}function hn(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 et extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud conversation creation was not dispatched.",{cause:e});this.name="CloudHandoffSeedRejectedError"}}class tt 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 bn 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 U(e){let t=e.expiredAt?Date.parse(e.expiredAt):Number.NaN;return Number.isFinite(t)&&t<=Date.now()}function di(e){return e.trim().startsWith("ses-")}function ci(e,t){let n=new URL(`/api/v1/session/${encodeURIComponent(t)}`,e);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.toString()}function Xe(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:nt(e),workspaceRoot:k},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse(e.createdAt)||Date.now(),endedAt:U(e)&&e.expiredAt?Date.parse(e.expiredAt):void 0,status:e.status,attachedViaHub:!0}}function Ze(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:nt(e),workspaceRoot:k,...n?.trim()?{prompt:n.trim()}:{},metadata:{origin:"cloud",repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function mn(e){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:e.status,provider:"cline",model:e.metadata.modelId??"",cwd:nt(e),workspaceRoot:k,repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",startedAt:e.createdAt,...e.lastActivityAt?{lastActivityAt:e.lastActivityAt}:{},endedAt:U(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 ui(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function li(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 pi{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=[];lastListedOrganizationId;discoveryRefresh;unconfirmedInnerCreates=new Set;createRequests=new Map;initialSends=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 te(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=Xe(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 j({...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&&U(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):j(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)fn(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 di(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?mn(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(){return await this.listInOrganization(await this.resolveActiveOrganizationId())}async listInOrganization(e){if(this.disposed)throw Error("Cloud session controller was disposed");let t=(r)=>this.sessions.get(r)?.title??this.knownSessions.get(r)?.title,n=new Map([...this.knownSessions.keys(),...this.sessions.keys()].map((r)=>[r,t(r)])),s=(r)=>{let a=t(r.id);if(this.titleWrites.has(r.id)||a!==n.get(r.id))r.title=a??r.title},o=(await this.options.api.list(e)).map((r)=>this.preserveConnectedRuntimeModel(r));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedOrganizationId=e,this.lastListedSessions=o;for(let r of o)s(r),this.knownSessions.set(r.id,r),this.unlistedSessions.delete(r.id);await Promise.all(Array.from(this.unlistedSessions.entries()).filter(([,r])=>r.organizationId===e).map(([r])=>this.getCrossScopeDiscoveryRecord(r)));let i=await Promise.all(o.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,...Ae(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 i){s(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 c=U(r);if(c||r.status==="failed"||r.status==="suspended"){if(a)a.busy=!1,a.status=c?"expired":r.status,a.endedAt=c?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.lastListedOrganizationId=e,this.lastListedSessions=i;for(let r of i)if(this.sessions.has(r.id))this.publishSnapshot(r.id);return j(i)}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 refreshOrganization(){await this.resolveActiveOrganizationId({fresh:!0})}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 on(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,n=(async()=>{let c=await this.resolveActiveOrganizationId();t={organizationId:c};let p=this.discoveryRefresh?.organizationId===c?this.discoveryRefresh?.promise:void 0;if(!p){let u=this.listInOrganization(c).finally(()=>{if(this.discoveryRefresh?.promise===u)this.discoveryRefresh=void 0});this.discoveryRefresh={organizationId:c,promise:u},p=u}return{organizationId:c,records:await p}})(),s=()=>t?{organizationId:t.organizationId,records:this.lastListedOrganizationId===t.organizationId?this.lastListedSessions:[]}:void 0,o;if(e.timeoutMs===void 0)o=await n;else{let c;try{o=await Promise.race([n.catch((p)=>{if(!(p instanceof g&&p.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:p});return s()}),new Promise((p)=>{c=setTimeout(()=>p(s()),Math.max(0,e.timeoutMs??0))})])}finally{if(c!==void 0)clearTimeout(c)}}if(!o)return[];let{organizationId:i,records:r}=o;return[...new Map([...Array.from(this.unlistedSessions.values()).filter((c)=>c.organizationId===i).map((c)=>c.record),...r].map((c)=>[c.id,c])).values()].map((c)=>{let p=mn(c),u=this.sessions.get(c.id);if(!u)return p;let h=u.title?.trim()||c.title?.trim();return{...p,status:u.status,prompt:u.prompt,endedAt:u.endedAt!==void 0?new Date(u.endedAt).toISOString():p.endedAt,metadata:{...p.metadata??{},title:Ve({sessionId:c.id,metadata:h?{title:h}:void 0,prompt:u.prompt,messages:u.messages})}}})}async create(e){let t=e.requestId?.trim();if(!t)return this.createSession(e);let n=this.createRequests.get(t);if(n)return n;let s=this.createSession(e).finally(()=>{if(this.createRequests.get(t)===s)this.createRequests.delete(t)});return this.createRequests.set(t,s),s}async createSession(e){let{initialMessage:t,...n}=e;if(!t)return this.createOnce(n);let s=!1,o,i={lifecycle:{beforeDispatch:()=>{s=!0}},settled:new Promise((d)=>{o=d})},r,a;try{r=await this.createOnce({...n,initialPrompt:t.text},(c)=>{if(a=c,!this.initialSends.has(c))this.initialSends.set(c,i)});let d=await this.send(r.sessionId,t.text,"queue",e.modelId,t.images,i.lifecycle);return o(),{...r,initialSend:d}}catch(d){let c={dispatched:s,message:d instanceof Error?d.message:String(d),...d instanceof Error&&"detail"in d&&typeof d.detail==="string"?{detail:d.detail}:{}};if(o(c),!r)throw d;return{...r,initialSend:c}}finally{if(a&&this.initialSends.get(a)===i)this.initialSends.delete(a)}}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){Ye(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 r=i.payload?.messages;if(!Array.isArray(r))throw Error("Cloud runtime returned no transcript after seeding.");if(t.length>0&&r.length===0)throw new bn;if(!(n.allowAppendedMessages?r.length>=t.length&&Ce(t,r.slice(0,t.length)):Ce(t,r)))throw new Se(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,t){if(this.disposed)throw Error("Cloud session manager was disposed");let n=Ye(e.workspaceRelativePath),s=e.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):e.organizationId??void 0,o=e.handoff,i=!o,r=await this.options.api.create({...e,organizationId:s,...o&&{handoff:{...o,onOuterSessionCreated:async(m,b)=>{i=b?.created===!0,await o.onOuterSessionCreated(m,b)}}}});if(!r?.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(r.sessionId,r.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let a={id:r.sessionId,sandboxType:e.sandboxType,status:r.status,sandboxUrl:r.sandboxUrl,repoContext:{repoUrl:e.repoUrl,...e.branch?.trim()?{branch:e.branch.trim()}:{}},metadata:{modelId:e.modelId,cwd:n},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};t?.(a.id),this.knownSessions.set(a.id,a),this.unlistedSessions.set(a.id,{record:a,organizationId:s});let{autoApproveTools:d,thinking:c,reasoningEffort:p,mode:u,workspaceRelativePath:h}=e;this.pendingInitialTasks.set(a.id,{autoApproveTools:d,thinking:c,reasoningEffort:p,mode:u??"act",workspaceRelativePath:h});let l=this.stateFromRecord(a);l.prompt=e.initialPrompt?.trim()||void 0,l.config.mode=e.mode??"act",this.sessions.set(a.id,l);let f;try{if(e.handoff){let m=await e.handoff.resolveMessages();this.assertSessionActive(a.id),f=(await this.seedHandoff(a.id,{sourceSessionId:e.handoff.sourceSessionId,messages:m,mode:e.mode,workspaceRelativePath:e.workspaceRelativePath,config:{autoApproveTools:e.autoApproveTools,thinking:e.thinking,reasoningEffort:e.reasoningEffort},onSeeding:e.handoff.onSeeding})).innerSessionId}}catch(m){if(this.disposed&&i&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(a.id,r.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw m}return this.assertSessionActive(a.id),this.notify("chat_session_status",{sessionId:a.id,status:l.status}),{sessionId:a.id,origin:"cloud",executionTarget:"cloud",status:a.status,provider:"cline",model:e.modelId,repoUrl:e.repoUrl,branch:e.branch??"",cwd:n,workspaceRoot:k,...f?{innerSessionId:f}:{},...l.prompt?{prompt:l.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 Ze(s,s.status,this.sessions.get(e)?.prompt);if(U(s))return await this.disposeConnection(e),await this.attachExpired(s);let o;try{o=await this.ensureConnection(e)}catch(a){let d=await this.refreshKnownSession(e);if(d&&U(d))return await this.disposeConnection(e),await this.attachExpired(d);throw a}await this.ensureAttached(o);let i=o.remote,r=this.sessions.get(e);return Ze(i,r?.status??i.status,r?.prompt)}async send(e,t,n,s,o,i){let r=this.sendAbortTokens.get(e),a=this.initialSends.get(e);if(a&&i!==a.lifecycle){if(await a.settled)throw new g("request_failed","The initial cloud prompt was not confirmed. Check the cloud task before sending another message.")}let d=this.knownSessions.get(e);if(d&&U(d))throw new g("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let c=await this.ensureConnection(e,{createInner:!0}),p=()=>this.disposed||c.disposed||this.deletingSessions.has(e)||this.sendAbortTokens.get(e)!==r,u=()=>{if(p())throw Error("Cloud session prompt cancelled")};if(u(),await c.reconnectResolution,u(),await this.ensureAttached(c),await c.reconnectResolution,u(),!c.transcriptKnown)await this.rehydrateAfterTransportDrop(e,c);u(),await this.updateModel(c,s),await c.reconnectResolution,u();let h=c.innerSessionId;if(!h)throw Error("Cloud Hub session was not initialized");let l=this.sessions.get(e),f=n??(l?.busy?"queue":void 0),m=ne(l?.messages??[],l?.promptsInQueue??[],t),b=f!=="queue"&&f!=="steer",w=l&&f!=="queue"?{role:"user",content:[{type:"text",text:t}]}:void 0;if(l&&w)l.messages=[...l.messages,w];let v=()=>{if(l&&w)l.messages=l.messages.filter((S)=>S!==w),this.publishSnapshot(e)};if(l&&b){let S=l.status!=="running";if(l.busy=!0,l.status="running",S)this.publishSnapshot(e,!1,"status")}let R=new Set,y=!1,_=()=>{if(y||p())return;y=!0,this.publish({type:"prompt_accepted",sessionId:e,prompt:t,delivery:f})};try{let S=await c.client.command("session.send_input",{prompt:t,delivery:f,...o?.length?{attachments:{userImages:o}}:{}},h,{timeoutMs:f==="queue"?oi:null,onDispatch:(I)=>{R.add(I),c.pendingInputs??=new Map,c.pendingInputs.set(I,{clientId:c.client.getClientId(),ownsBusyState:b,accept:_})},beforeDispatch:()=>{if(u(),c.innerSessionId!==h)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.");if(i?.beforeDispatch?.(),l&&b)l.prompt||=t;let I=this.knownSessions.get(e);if(I&&!I.title?.trim()&&!this.titleWrites.has(e)){let M=bt(t);if(M){if(I.title=M,l)l.title=M;let E=this.options.api.updateTitle?.(e,M).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get(e)===E)this.titleWrites.delete(e)});if(E)this.titleWrites.set(e,E)}}}});_();let x=f==="queue"||f!=="steer"&&S.payload?.result===void 0;if(x)v();return{sessionId:e,ok:!0,...x?{queued:!0}:{},result:S.payload?.result}}catch(S){if(p())throw v(),S;if(Ke(S)||Qe(S,"session.send_input")){let x;try{x=await this.rehydrateAfterTransportDrop(e,c)}catch(M){if(u(),v(),l&&b)l.busy=!1,l.status="error";if(f==="queue")throw new tt;throw M}if(u(),f==="queue")throw new tt;if(f==="steer")throw new g("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(ne(x.messages,li(x.prompts,x.submittedPrompts),t)<=m)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,...f==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:x.status}}if(v(),l&&b)l.busy=!1,l.status="error";throw this.publishSnapshot(e),S}finally{for(let S of R)c.pendingInputs?.delete(S)}}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),r=this.authoritativeMessages.get(e)??[],a=String(o?.status??i?.status??"running").trim(),d=a==="pending"?"running":a;if(d==="running"&&!t.transcriptKnown&&!t.pendingInputs?.size)t.externalRun??={progressHydrated:!0};let c=()=>t.client.command("session.messages",{sessionId:n},n),p=await c().catch((_)=>{if(!Qe(_,"session.messages"))throw _;return this.assertSessionActive(e,t),c()});if(this.assertSessionActive(e,t),!Array.isArray(p.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let u=p.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 f=t.bufferedEventsDropped+t.bufferedEvents.length;if(i){let _=i.status!==d;if(this.authoritativeMessages.set(e,structuredClone(u)),i.messages=structuredClone(u),this.streamingMessages.delete(e),i.status=d,i.busy=d==="running",_)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),b=m?this.applyQueueSnapshot(e,l):void 0;t.transcriptKnown=!0;let w=u;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,R=We(v),y=pn(v,u,{queueSnapshotApplied:m,queueSnapshotEventCutoff:Math.max(0,f-t.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,h-t.bufferedEventsDropped),baselineMessages:r});t.bufferedEvents=[],t.bufferingEvents=!1,t.syncFailureNotified=!1;for(let _ of y)this.forwardEvent(e,t,_);return{status:d,messages:u,prompts:b,submittedPrompts:R}}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((r)=>typeof r==="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&&U(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)??Xe(e);return t.busy=!1,t.status="expired",this.sessions.set(e.id,t),await this.loadArchivedMessages(e).catch(()=>{return}),Ze(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)??Xe(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 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 u=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(),u?.status)a.status=u.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 u=new AbortController,h=this.trackProvisioningController(e,u);try{try{a=await this.options.api.resume(e,u.signal)}catch(f){if(!(f instanceof g)||f.status!==409)throw f;s(),u.signal.throwIfAborted();let m=await this.options.api.status(e,{signal:u.signal});if(m.status!=="provisioning"&&m.status!=="ready"&&m.status!=="active")throw f;a={...a,status:m.status}}s(),u.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 u=new AbortController,h=this.trackProvisioningController(e,u);try{if(await this.options.api.waitUntilReady(e,u.signal,({phase:f})=>{a.metadata.provisioningPhase=f,this.notify("chat_session_status",{sessionId:e,status:"provisioning",phase:f})}),this.disposed)throw Error("Cloud session manager was disposed");if(a=await this.refreshKnownSession(e)??a,u.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 f=this.sessions.get(e);if(f)f.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(U(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,c=0,p=this.createHubClient({url:ci(this.options.apiBaseUrl,e),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${e}-${si()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:k,cwd:k,resolveConnectionHeaders:async()=>{s();let u=c>0;if(c+=1,d)d.connected=!1,d.reconnecting=u,this.publishSnapshot(e);if(u){let l=d;if(l&&!l.disposed){l.transcriptKnown=!1,l.innerSessionId=void 0;let f=(async()=>{if(await this.resolveInnerSession(e,l),l.innerSessionId)await this.rehydrateAfterTransportDrop(e,l)})().catch(()=>this.disposeConnectionIfSessionGone(e,l)).finally(()=>{if(l.reconnectResolution===f)l.reconnectResolution=void 0,l.connected=l.transcriptKnown,this.publishSnapshot(e)});l.reconnectResolution=f}}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:p,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},d.unsubscribe=p.subscribe(()=>{},{sessionId:a.metadata.taskId?.trim()||e}),this.connections.set(e,d);try{if(await p.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(u){if(Ke(u)&&!this.disposed&&!d.disposed&&!this.deletingSessions.has(e))throw u;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 p.dispose().catch(()=>{return}),u}})().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(),o;if(s)try{let a=await t.client.command("session.get",{sessionId:s},s);this.assertSessionActive(e,t),o=a.payload?.session&&typeof a.payload.session==="object"&&!Array.isArray(a.payload.session)?a.payload.session:void 0}catch(a){if(!_e(a))throw a}else{let a=await t.client.command("session.list",{limit:100});this.assertSessionActive(e,t),o=me(a.payload).filter(ge).sort((d,c)=>je(c)-je(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 r=Ge(o);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(h){if(!(_e(h)||h instanceof Error&&h.code==="command_failed"&&h.message===`session not found: ${t}`))throw h}this.assertSessionActive(e.remote.id,e);let o=n.metadata??{},i=n.runtimeOptions??{},r=this.sessions.get(e.remote.id)?.config,a=Object.hasOwn(o,"thinking")?o.thinking:r?.thinking,d=Object.hasOwn(o,"reasoningEffort")?o.reasoningEffort:r?.reasoningEffort,c=typeof o.autoApproveTools==="boolean"?o.autoApproveTools:r?.autoApproveTools,p=n.cwd??n.workspaceRoot??k,u=n.workspaceRoot??k;try{let h={workspaceRoot:u,cwd:p,metadata:{...o,interactive:!0},sessionConfig:{sessionId:t,providerId:o.provider??"cline",modelId:o.model??o.modelId??e.remote.metadata.modelId,workspaceRoot:u,cwd:p,systemPrompt:i.systemPrompt??o.systemPrompt??"",mode:i.mode??o.mode??"act",...typeof a==="boolean"?{thinking:a}:{},...typeof d==="string"?{reasoningEffort:d}:{},...o.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:i,...typeof c==="boolean"?{toolPolicies:{"*":{autoApprove:c}}}:{}},l=await e.client.command("session.resume",h).catch(async(m)=>{if(!(m instanceof ee)||m.code!=="unsupported_command")throw m;this.assertSessionActive(e.remote.id,e);let b=await e.client.command("session.messages",{},t);this.assertSessionActive(e.remote.id,e);let w=b.payload?.messages;if(!Array.isArray(w)||w.length===0)throw Error("The saved conversation is empty or unavailable.");return e.client.command("session.create",{...h,initialMessages:w})});if(this.assertSessionActive(e.remote.id,e),(l.payload?.session?.sessionId??l.payload?.sessionId)!==t)throw Error("Cloud Hub did not restore the requested session.")}catch(h){if(h?.code!=="session_already_exists")throw h;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=me(n.payload).filter(ge),[o]=s;if(s.length!==1||String(o?.sessionId??"").trim()!==e.innerSessionId||hn(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=me(n.payload).filter(ge);if(s.length===0)return!1;let[o]=s,i=String(o?.sessionId??"").trim();if(s.length!==1||!i||hn(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 resolveComputerUse(e){if(!sn(e))return!1;try{return await this.options.isComputerUseEnabled?.()===!0}catch(t){return this.options.logger?.debug("Cloud computer-use gate failed",{error:t}),!1}}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=this.pendingInitialTasks.get(e.remote.id)??this.restoredOptions.get(e.remote.id),i=Ye(t?.workspaceRelativePath??o?.workspaceRelativePath),r=t?.mode??o?.mode??"act";try{await t?.onSeeding?.(),this.assertSessionActive(e.remote.id,e)}catch(b){if(t)throw new et(b);throw b}let a=await this.resolveComputerUse(n),d=ai(e.remote,{computerUse:a}),c=t?.config?.thinking??s?.config.thinking,p=t?.config?.reasoningEffort??s?.config.reasoningEffort,u=!1,h=e.client.command("session.create",{workspaceRoot:k,cwd:i,...t?{initialMessages:t.messages}:{},sessionConfig:{...e.remote.metadata.taskId?.trim()?{sessionId:e.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:n,workspaceRoot:k,cwd:i,systemPrompt:t?`${gn}
20
33
 
21
- Continue from the original repository subdirectory at ${o}.`):r,mode:i,enableTools:!0,...typeof a==="boolean"?{thinking:a}:{},...typeof d==="string"?{reasoningEffort:d}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:n,interactive:!0,thinking:a??null,reasoningEffort:a===!1?null:d??null,...t?{handoff:{from:"local",sourceSessionId:t.sourceSessionId,outerSessionId:e.remote.id}}:{}},runtimeOptions:{mode:i},modelSelection:{provider:"cline",model:n},toolPolicies:{"*":{autoApprove:(t?.config?.autoApproveTools??s?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive(e.remote.id,e),onDispatch:()=>{l=!0}}),c;try{c=await f}catch(u){if(t&&!l)throw new Ge(u);if(t&&(je(u,"session.create")||We(u)))this.unconfirmedInnerCreates.add(e.remote.id);throw u}this.assertSessionActive(e.remote.id,e);let h=c.payload?.session&&typeof c.payload.session==="object"?c.payload.session:void 0,p=String(h?.sessionId??c.payload?.sessionId??"").trim();if(!p){if(t)this.unconfirmedInnerCreates.add(e.remote.id);throw Error("Cloud Hub did not return an inner session id")}if(this.unconfirmedInnerCreates.delete(e.remote.id),this.pendingInitialTasks.delete(e.remote.id),e.innerSessionId=p,e.remote.metadata.cwd=o,s)s.config.cwd=o,s.config.mode=i;this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,h),e.transcriptKnown=!t}handleEvent(e,t,n){if(this.disposed||t.disposed)return;if(t.innerSessionId&&n.sessionId&&n.sessionId!==t.innerSessionId)return;let s=n.eventId?.trim();if(s&&!(n.event==="approval.requested"&&n.sequence===void 0)){if(t.seenEventIds.has(s))return;t.seenEventIds.add(s);while(t.seenEventIds.size>To){let o=t.seenEventIds.values().next().value;if(o)t.seenEventIds.delete(o)}}if(t.bufferingEvents){if(t.bufferedEvents.push(n),t.bufferedEvents.length>Ao)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,o=n.event==="run.completed"||n.event==="run.failed"||n.event==="run.aborted",i=s&&!s.progressHydrated&&(n.event==="assistant.delta"||n.event==="reasoning.delta"||n.event==="tool.started");if(s&&(i||o)){if(s.progressHydrated=!0,o)t.externalRun=void 0;let 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 o=`${e}:${s}`,i={approvalId:s,requestId:o,sessionId:e,createdAt:new Date(typeof n?.createdAt==="number"?n.createdAt:Date.now()).toISOString(),toolCallId:String(n?.toolCallId??""),toolName:String(n?.toolName??"tool"),input:Io(n?.inputJson),iteration:typeof n?.iteration==="number"?n.iteration:void 0,agentId:typeof n?.agentId==="string"?n.agentId:void 0,conversationId:typeof n?.conversationId==="string"?n.conversationId:void 0};this.approvals.set(o,{item:i,resolve:async(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=Be(t);if(n)this.applyModel(e,n);let s=t,o=typeof s.cwd==="string"&&ue.normalize(s.cwd)===s.cwd&&(s.cwd===C||s.cwd.startsWith(`${C}/`))?s.cwd:void 0;if(o){e.remote.metadata.cwd=o;let a=this.sessions.get(e.remote.id);if(a)a.config.cwd=o}let i=this.sessions.get(e.remote.id),r=s.runtimeOptions?.mode;if(i&&(r==="act"||r==="plan"||r==="yolo"||r==="zen"))i.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 o=s.find((r)=>r.id===e),i=o?this.preserveConnectedRuntimeModel(o):void 0;if(!i){await this.disposeConnection(e).catch(()=>{return});return}if(this.knownSessions.set(e,i),t.remote=i,i.status==="failed"||i.status==="suspended"){let r=this.sessions.get(e);if(r)r.busy=!1,r.status=i.status,r.endedAt=Date.parse(i.updatedAt)||Date.now();await this.disposeConnection(e).catch(()=>{return});return}if(T(i))await this.attachExpired(i).catch(()=>{return}),await this.disposeConnection(e).catch(()=>{return})}}export{nn as CLOUD_SESSION_SYSTEM_PROMPT,rt as CloudCreationUnconfirmedError,at as CloudHandoffCreationRejectedError,_ as CloudHandoffGitPreflightError,Ge as CloudHandoffSeedRejectedError,sn as CloudHandoffSeedUnsupportedError,he as CloudHandoffTranscriptMismatchError,Ve as CloudQueueUnconfirmedError,kn as CloudSessionApi,Oo as CloudSessionController,m as CloudSessionError,Qo as buildCloudHandoffDashboardUrl,xo as buildCloudSessionSystemPrompt,Ko as clearCloudHandoffMetadata,Jo as cloudHandoffFingerprintsEqual,fe as cloudHandoffTranscriptsEqual,tn as cloudSessionToDiscoveryRecord,G as countPromptOccurrences,hn as createCloudHandoffFingerprint,it as deriveCloudSessionTitle,Eo as isCloudOuterSessionId,ae as isRootSessionRow,zt as loadCloudModels,Vo as mergeCloudHandoffMetadata,et as normalizeGitHubRemoteUrl,ce as normalizeSessionTitle,be as parseCloudProvisioningPhase,Fo as preflightCloudHandoffGit,Go as readCloudHandoffMetadata,re as readSessionRows,Xt as reconcileBufferedCloudEvents,$e as resolveSessionListTitle,Be as sessionRowModelId,Ne as stringifyMessageContent,qe as submittedPromptsFromEvents,De as updatedAt};
34
+ 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 ${k}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(i===k?"":`
35
+
36
+ Continue from the original repository subdirectory at ${i}.`)+(a?`
37
+
38
+ ${ze}`:""):d,mode:r,enableTools:!0,...typeof c==="boolean"?{thinking:c}:{},...typeof p==="string"?{reasoningEffort:p}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:n,interactive:!0,thinking:c??null,reasoningEffort:c===!1?null:p??null,...t?{handoff:{from:"local",sourceSessionId:t.sourceSessionId,outerSessionId:e.remote.id}}:{}},runtimeOptions:{mode:r},modelSelection:{provider:"cline",model:n},toolPolicies:{"*":{autoApprove:(t?.config?.autoApproveTools??s?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive(e.remote.id,e),onDispatch:()=>{u=!0}}),l;try{l=await h}catch(b){if(t&&!u)throw new et(b);if(t&&(Qe(b,"session.create")||Ke(b)))this.unconfirmedInnerCreates.add(e.remote.id);throw b}this.assertSessionActive(e.remote.id,e);let f=l.payload?.session&&typeof l.payload.session==="object"?l.payload.session:void 0,m=String(f?.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=r;this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,f),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>ri){let o=t.seenEventIds.values().next().value;if(o)t.seenEventIds.delete(o)}}if(t.bufferingEvents){if(t.bufferedEvents.push(n),t.bufferedEvents.length>ii)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,o=n.event==="run.completed"||n.event==="run.failed"||n.event==="run.aborted",i=s&&!s.progressHydrated&&(n.event==="assistant.delta"||n.event==="reasoning.delta"||n.event==="tool.started");if(s&&(i||o)){if(s.progressHydrated=!0,o)t.externalRun=void 0;let 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 o=`${e}:${s}`,i={approvalId:s,requestId:o,sessionId:e,createdAt:new Date(typeof n?.createdAt==="number"?n.createdAt:Date.now()).toISOString(),toolCallId:String(n?.toolCallId??""),toolName:String(n?.toolName??"tool"),input:ui(n?.inputJson),iteration:typeof n?.iteration==="number"?n.iteration:void 0,agentId:typeof n?.agentId==="string"?n.agentId:void 0,conversationId:typeof n?.conversationId==="string"?n.conversationId:void 0};this.approvals.set(o,{item:i,resolve:async(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=Ge(t);if(n)this.applyModel(e,n);let s=t,o=typeof s.cwd==="string"&&ye.normalize(s.cwd)===s.cwd&&(s.cwd===k||s.cwd.startsWith(`${k}/`))?s.cwd:void 0;if(o){e.remote.metadata.cwd=o;let a=this.sessions.get(e.remote.id);if(a)a.config.cwd=o}let i=this.sessions.get(e.remote.id),r=s.runtimeOptions?.mode;if(i&&(r==="act"||r==="plan"||r==="yolo"||r==="zen"))i.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 o=s.find((r)=>r.id===e),i=o?this.preserveConnectedRuntimeModel(o):void 0;if(!i){await this.disposeConnection(e).catch(()=>{return});return}if(this.knownSessions.set(e,i),t.remote=i,i.status==="failed"||i.status==="suspended"){let r=this.sessions.get(e);if(r)r.busy=!1,r.status=i.status,r.endedAt=Date.parse(i.updatedAt)||Date.now();await this.disposeConnection(e).catch(()=>{return});return}if(U(i))await this.attachExpired(i).catch(()=>{return}),await this.disposeConnection(e).catch(()=>{return})}}class fi{getConnection;snapshots=new Map;records=new Map;listeners=new Set;unsubscribe;connection;disposed=!1;serviceId;scopeGeneration=-1;revision=-1;sessionRevisions=new Map;constructor(e){this.getConnection=e}async ready(){if(this.disposed)throw Error("Cloud viewer is disposed");if(!this.connection){let e=this.getConnection().then(async(t)=>{if(this.disposed)throw Error("Cloud viewer is disposed");this.unsubscribe=t.subscribe((n)=>{if(n.event==="cloud.event")this.recover(n.payload)});try{let n=await t.command("cloud.watch");return this.checkReply(n),this.recover(n.payload),t}catch(n){throw this.unsubscribe?.(),this.unsubscribe=void 0,n}});this.connection=e,e.catch(()=>{if(this.connection===e)this.connection=void 0})}return this.connection}async connect(){await this.ready()}get scope(){return this.serviceId?{serviceId:this.serviceId,scopeGeneration:this.scopeGeneration}:void 0}recover(e){if(this.disposed||!this.acceptVersion(e))return;let t=Number(e?.revision);if(Array.isArray(e?.snapshots)){let n=e.snapshots,s=new Set(n.map((o)=>o.sessionId));for(let o of this.snapshots.keys())if((!e.sessionId||e.sessionId===o)&&!s.has(o))this.receive({type:"removed",sessionId:o},t);for(let o of n)this.receive({type:"snapshot",sessionId:o.sessionId,snapshot:o,replace:!0},t)}else this.receive(e?.event,t)}acceptVersion(e){if(typeof e?.serviceId!=="string"||typeof e.revision!=="number")return!1;if(e.serviceId===this.serviceId&&Number(e.scopeGeneration)<this.scopeGeneration)return!1;if(e.serviceId!==this.serviceId||e.scopeGeneration!==this.scopeGeneration){for(let t of this.snapshots.keys())this.receive({type:"removed",sessionId:t});this.records.clear(),this.sessionRevisions.clear(),this.serviceId=e.serviceId,this.scopeGeneration=Number(e.scopeGeneration),this.revision=-1}return this.revision=Math.max(this.revision,e.revision),!0}checkReply(e){if(!e.ok)throw Error(e.error?.message??"Cloud hub request failed")}receive(e,t=this.revision){if(this.disposed||!e)return;if(t<(this.sessionRevisions.get(e.sessionId)??-1))return;if(this.sessionRevisions.set(e.sessionId,t),e.type==="snapshot")this.snapshots.set(e.sessionId,structuredClone(e.snapshot));if(e.type==="removed")this.snapshots.delete(e.sessionId),this.records.delete(e.sessionId);let n=j(e);for(let s of this.listeners)s(n)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async call(e,t,n){let s=n?{...n}:this.scope,o=await this.ready();if(this.disposed)throw Error("Cloud viewer is disposed");let i=s??{serviceId:this.serviceId,scopeGeneration:this.scopeGeneration},r=()=>i.serviceId===this.serviceId&&i.scopeGeneration===this.scopeGeneration,a=!1,d=await o.command("cloud.command",{operation:e,args:t,scope:i},void 0,{timeoutMs:["create","send","attach"].includes(e)?null:void 0,beforeDispatch:()=>{if(this.disposed)throw Error("Cloud viewer is disposed");if(!r())throw Error("Cloud account changed before request");if(a)throw Error("Cloud request outcome is unknown; reconnect before retrying")},onDispatch:()=>{a=!0}}).catch((c)=>{let p=c instanceof Error&&c.name==="HubCommandError"&&"code"in c&&c.code!=="hub_command_timeout";if(e==="create"&&typeof t[0]==="object"&&t[0]!==null&&"initialMessage"in t[0]&&t[0].initialMessage!==void 0&&a&&!p)throw new g("request_failed","The cloud task may have started. Check your cloud tasks before submitting this draft again.");throw c});if(this.checkReply(d),!r()||d.payload?.serviceId!==i.serviceId||d.payload?.scopeGeneration!==i.scopeGeneration||!this.acceptVersion(d.payload))throw Error("Cloud account changed during request");if(this.disposed)throw Error("Cloud viewer is disposed");return d.payload?.result}create(e,t){return this.call("create",[e],t)}attach(...e){return this.call("attach",e)}send(...e){return this.call("send",e)}prepareHandoffRepository(e,t){return this.call("prepareHandoffRepository",[e],t)}refreshOrganization(){return this.call("refreshOrganization",[])}abort(...e){return this.call("abort",e)}pendingPrompts(...e){return this.call("pendingPrompts",e)}updatePendingPrompt(...e){return this.call("updatePendingPrompt",e)}removePendingPrompt(...e){return this.call("removePendingPrompt",e)}readMessages(...e){return this.call("readMessages",e)}updateTitle(...e){return this.call("updateTitle",e)}delete(...e){return this.call("delete",e)}listModels(e){return this.call("listModels",[],e)}listRepositories(...e){return this.call("listRepositories",e)}listBranches(...e){return this.call("listBranches",e)}respondApproval(...e){return this.call("respondApproval",e)}restoreCreationOptions(...e){return this.call("restoreCreationOptions",e)}getCrossScopeDiscoveryRecord(...e){return this.call("getCrossScopeDiscoveryRecord",e)}async list(){return await this.call("list",[])}async listForDiscovery(...e){let t=await this.call("listForDiscovery",e);for(let n of t)this.records.set(String(n.sessionId),structuredClone(n));return t}getCachedDiscoveryRecord(e){let t=this.records.get(e);return t?structuredClone(t):void 0}getSnapshot(e){let t=this.snapshots.get(e);return t?structuredClone(t):void 0}isCloudSession(e){return e.trim().startsWith("ses-")||this.records.has(e)||this.snapshots.has(e)}async dispose(){this.disposed=!0,this.unsubscribe?.(),this.unsubscribe=void 0;for(let e of this.snapshots.keys())for(let t of this.listeners)t({type:"removed",sessionId:e});this.snapshots.clear(),this.records.clear(),this.listeners.clear()}}var pa=["create","attach","send","abort","pendingPrompts","updatePendingPrompt","removePendingPrompt","readMessages","updateTitle","delete","list","listForDiscovery","getCrossScopeDiscoveryRecord","listModels","listRepositories","listBranches","respondApproval","restoreCreationOptions","refreshOrganization","prepareHandoffRepository"];export{pa as CLOUD_HUB_OPERATIONS,gn as CLOUD_SESSION_SYSTEM_PROMPT,yt as CloudCreationUnconfirmedError,wt as CloudHandoffCreationRejectedError,T as CloudHandoffGitPreflightError,et as CloudHandoffSeedRejectedError,bn as CloudHandoffSeedUnsupportedError,Se as CloudHandoffTranscriptMismatchError,tt as CloudQueueUnconfirmedError,Zn as CloudSessionApi,pi as CloudSessionController,g as CloudSessionError,fi as HubCloudSessionClient,$i as buildCloudHandoffDashboardUrl,ai as buildCloudSessionSystemPrompt,qi as clearCloudHandoffMetadata,Li as cloudHandoffFingerprintsEqual,Ce as cloudHandoffTranscriptsEqual,mn as cloudSessionToDiscoveryRecord,ne as countPromptOccurrences,Cn as createArtifactFetcher,_n as createArtifactPublisher,Dn as createCloudHandoffFingerprint,bt as deriveCloudSessionTitle,Gn as inspectHandoffGit,di as isCloudOuterSessionId,ge as isRootSessionRow,on as loadCloudModels,Ni as mergeCloudHandoffMetadata,W as normalizeGitHubRemoteUrl,be as normalizeSessionTitle,Ae as parseCloudProvisioningPhase,Ui as preflightCloudHandoffGit,zn as previewHandoffGit,Bi as readCloudHandoffMetadata,me as readSessionRows,pn as reconcileBufferedCloudEvents,Ve as resolveSessionListTitle,Ge as sessionRowModelId,Je as stringifyMessageContent,We as submittedPromptsFromEvents,je as updatedAt};