@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
@@ -0,0 +1,38 @@
1
+ import{Wt,Pt,Xt,me,ne,jn,$n,re,Me,qn,Gi,Zt,zn,jt,Ze,P,Z,ge}from"../index-ffna8yzn.js";import{wi,ns,xa,ba}from"../index-3qy7846d.js";import{Xo}from"../index-6dpcn5cw.js";import"../index-hkmarmve.js";import"../index-w9n2kgjk.js";import{v,e,n,t,d,a}from"../index-edf1hmcw.js";import{openAsBlob as ws}from"node:fs";import{stat as ys}from"node:fs/promises";import{basename as gs}from"node:path";import{setTimeout as Ye}from"node:timers/promises";import{execFile as Ss}from"node:child_process";import{basename as gn,resolve as Is}from"node:path";import{promisify as Cs}from"node:util";import{execFile as Us}from"node:child_process";import{randomUUID as ot}from"node:crypto";import{mkdtemp as Ms,rm as Os}from"node:fs/promises";import{tmpdir as Hs}from"node:os";import{join as nt}from"node:path";import{randomUUID as js}from"node:crypto";import{randomUUID as Ws}from"node:crypto";import{posix as ie}from"node:path";var qt=v(ns(),1),Bt=v(Xo(),1);import{spawn as Js}from"node:child_process";import{closeSync as Qs,mkdirSync as Ys,openSync as Xs,readFileSync as Zs,unlinkSync as ei}from"node:fs";import{basename as ti,dirname as si,join as ii}from"node:path";import{fileURLToPath as oi}from"node:url";import{createHash as ni,randomBytes as ri}from"node:crypto";import{mkdir as $e,open as lt,readFile as Lt,rename as ai,rm as Le,writeFile as di}from"node:fs/promises";import{dirname as zt,join as ze}from"node:path";import{join as ji}from"node:path";var Qe=30000,fs=128,ms=t({success:a(!0),data:t({url:e().url().pipe(e().refine((s)=>{let i=new URL(s);return i.protocol==="https:"&&!i.username&&!i.password})),expiresAt:e().datetime({offset:!0}).transform(Date.parse)})});function dn({request:s,cloudSessionId:i}){let o=new Map;return async function({artifactId:r,signal:c}){let l=`/api/v1/session/${encodeURIComponent(i)}/artifacts/download-url?name=${encodeURIComponent(r)}`;for(let h=0;;h++){c?.throwIfAborted();let u=o.get(r);if(!u||u.expiresAt<=Date.now()+Qe){o.delete(r);let m=await s(l,{method:"GET",redirect:"error",cache:"no-store",signal:AbortSignal.any([...c?[c]:[],AbortSignal.timeout(15000)])});if(!m.ok)throw await m.body?.cancel().catch(()=>{}),Error(`Artifact service returned HTTP ${m.status}`);let y=ms.safeParse(await m.json());if(!y.success)throw Error("Artifact service returned an invalid download URL");u=y.data.data}c?.throwIfAborted();let p=await fetch(u.url,{method:"GET",credentials:"omit",redirect:"error",cache:"no-store",signal:c});if(p.ok){if(u.expiresAt>Date.now()+Qe){if(o.delete(r),o.size>=fs){let m=o.keys().next();if(!m.done)o.delete(m.value)}o.set(r,u)}return p}if(o.delete(r),await p.body?.cancel().catch(()=>{}),p.status===403&&h===0)continue;throw Error(`Artifact download returned HTTP ${p.status}`)}}}class j extends Error{code;constructor(s,i){super(i);this.code=s}}function Xe(s,i,o,r){return{path:s,artifactId:o,error:r?.aborted?{code:"CANCELLED",message:"Publication cancelled"}:i instanceof j?{code:i.code,message:i.message}:{code:"FILE_READ_FAILED",message:"Could not read the local file"}}}var vs=t({url:e(),fields:d(e().refine((s)=>!/^(key|file)$/i.test(s)),e()),keyPrefix:e().endsWith("/"),maxBytes:n().int().positive(),expiresAt:e().refine((s)=>Number.isFinite(Date.parse(s))).transform(Date.parse)}),bs=t({success:a(!0),data:vs});async function et(s){let i=await ys(s.path);if(i.size!==s.size||i.mtimeMs!==s.modifiedAt)throw new j("FILE_CHANGED","Local file changed after it was selected")}function mn({request:s,cloudSessionId:i}){return async(o,{signal:r})=>{let c=[];async function l(){for(let u=0;u<3;u++){if(r?.throwIfAborted(),u)await Ye(250*u,void 0,{signal:r});let p;try{p=await s(`/api/v1/session/${encodeURIComponent(i)}/artifacts/upload-policy`,{method:"POST",redirect:"error",signal:AbortSignal.any([...r?[r]:[],AbortSignal.timeout(15000)])})}catch{r?.throwIfAborted();continue}if(p.status===429||p.status>=500){await p.body?.cancel().catch(()=>{});continue}if(!p.ok)throw await p.body?.cancel().catch(()=>{}),new j("CORE_REJECTED",`Artifact service returned HTTP ${p.status}`);let m;try{m=await p.json()}catch{throw r?.throwIfAborted(),new j("INVALID_RESPONSE","Artifact service returned invalid JSON")}let y=bs.safeParse(m);if(!y.success)throw new j("INVALID_RESPONSE","Invalid upload policy");return y.data.data}throw new j("CORE_UNAVAILABLE","Could not obtain an upload policy after 3 attempts")}let h;try{h=await l()}catch(u){for(let p of o)c.push(Xe(p.path,u,p.artifactId,r));return c}for(let u of o)try{if(u.size===0)throw new j("EMPTY_FILE","The upload policy does not allow empty files");for(let p=0;p<3;p++){if(r?.throwIfAborted(),p)await Ye(250*p,void 0,{signal:r});if(Date.now()>=h.expiresAt)h=await l();if(u.size>h.maxBytes)throw new j("FILE_TOO_LARGE",`File exceeds the upload policy limit of ${h.maxBytes} bytes`);await et(u);let m=new FormData;for(let[g,S]of Object.entries(h.fields))m.append(g,S);m.append("key",h.keyPrefix+u.artifactId),m.append("file",await ws(u.path,{type:h.fields["Content-Type"]}),gs(u.path));let y;try{y=await fetch(h.url,{method:"POST",body:m,redirect:"error",signal:AbortSignal.any([...r?[r]:[],AbortSignal.timeout(120000)])})}catch{r?.throwIfAborted(),await et(u)}if(y?.ok){await y.body?.cancel().catch(()=>{});break}let w=!1,b=(y?.status===400||y?.status===403)&&/expired/i.test(await y.text().catch(()=>(w=!0,"")));r?.throwIfAborted();let f=w||!y||y.status===408||y.status===429||y.status>=500;if(await y?.body?.cancel().catch(()=>{}),!b&&!f)throw new j("UPLOAD_REJECTED",`Storage rejected upload with HTTP ${y?.status}`);if(p===2)throw new j("UPLOAD_FAILED","Upload was not confirmed after 3 attempts; retry with the same artifactId");if(b)h=await l()}c.push({path:u.path,artifactId:u.artifactId})}catch(p){c.push(Xe(u.path,p,u.artifactId,r))}return c}}var ks=Cs(Ss);function As(s,i){return ks("git",s,{cwd:i.cwd,encoding:"utf8",windowsHide:!0,signal:i.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 qe(s){if(!s||typeof s!=="object"||!("stderr"in s))return"";return typeof s.stderr==="string"?s.stderr.trim():""}function xe(s){if(!s||typeof s!=="object"||!("code"in s))return;return typeof s.code==="number"?s.code:void 0}function _s(s){let i=Ts(s.cwd),o=s.git??As,r=async(l)=>(await o(l,{cwd:i,signal:s.signal})).stdout,c=async(l)=>(await r(l)).trim();return{async isInsideWorkTree(){try{return await c(["rev-parse","--is-inside-work-tree"])==="true"}catch(l){if(xe(l)===128&&/not a git repository|Kein Git-Repository/i.test(qe(l)))return!1;throw l}},remotes:()=>wi({baseDir:i}).getRemotes(!0),displayBranch:async()=>(await wi({baseDir:i}).branch()).current.trim(),symbolicBranch:()=>c(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>c(["rev-parse","HEAD"]),workspacePrefix:async()=>(await r(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>c(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(l)=>c(["config","--get",`branch.${l}.remote`]),branchMergeRef:(l)=>c(["config","--get",`branch.${l}.merge`]),remoteUrl:(l)=>c(["remote","get-url",l]),remoteRefs:(l,h)=>c(["ls-remote","--exit-code",l,h])}}function Ts(s){return Is(s)}class O extends Error{code;constructor(s,i,o){super(i,o);this.code=s,this.name="CloudHandoffGitPreflightError"}}function tt(s){let i=0,o=s.length;while(i<o&&s[i]==="/")i+=1;while(o>i&&s[o-1]==="/")o-=1;let r=s.slice(i,o);return r.toLowerCase().endsWith(".git")?r.slice(0,-4):r}function se(s){let i=s.trim();if(!i)return null;let o=i.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(o?.[1]){let r=tt(o[1]);return r.split("/").length===2?`https://github.com/${r}`:null}try{let r=new URL(i);if(r.hostname.toLowerCase()!=="github.com")return null;if(!new Set(["https:","http:","ssh:","git:"]).has(r.protocol))return null;let c=tt(r.pathname);return c.split("/").length===2?`https://github.com/${c}`:null}catch{return null}}async function G(s,i,o){try{return await s()}catch(r){let c=qe(r);throw new O(i,c?`${o} (${c})`:o,{cause:r})}}function Es(s,i){let o=`refs/heads/${i}`;for(let r of s.split(`
2
+ `)){let[c,l]=r.trim().split(/\s+/,2);if(l===o&&/^[0-9a-f]{40,64}$/i.test(c??""))return c??null}return null}function xs(s){let i=s.replace(/[\r\n]+$/,"").replace(/\/+$/,"");if(!i)return;let o=i.split("/");if(i.startsWith("/")||o.some((r)=>!r||r==="."||r===".."))throw new O("git_command_failed","Could not resolve the workspace path relative to the Git repository.");return i}async function In(s){let i=_s(s);if(!await G(i.isInsideWorkTree,"not_git_repository","Cloud handoff requires a Git repository."))throw new O("not_git_repository","Cloud handoff requires a Git working tree.");let o=xs(await G(i.workspacePrefix,"git_command_failed","Could not resolve the workspace path relative to the Git repository.")),r=await G(i.worktreeStatus,"git_command_failed","Could not inspect the Git worktree.");if(r){let f=r.split(`
3
+ `).filter(Boolean),g=f.slice(0,5).join(`
4
+ `),S=f.length>5?`
5
+ ...and ${f.length-5} more`:"";throw new O("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
6
+
7
+ ${g}${S}`)}let c;try{c=await i.symbolicBranch()}catch(f){let g=xe(f)===1,S=qe(f),C=g?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new O(g?"detached_head":"git_command_failed",S?`${C} (${S})`:C,{cause:f})}if(!c)throw new O("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[l,h,u]=await Promise.all([G(()=>i.branchRemote(c),"missing_upstream",`Branch ${c} has no upstream. Push it with -u before handing off.`),G(()=>i.branchMergeRef(c),"missing_upstream",`Branch ${c} has no upstream. Push it with -u before handing off.`),G(i.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!l||l==="."||!h.startsWith("refs/heads/"))throw new O("missing_upstream",`Branch ${c} has no remote branch upstream. Push it with -u before handing off.`);let p=h.slice(11),m=l;if(!se(l))try{m=await i.remoteUrl(l)}catch{throw new O("missing_upstream","Could not resolve the upstream remote.")}let y=se(m);if(!y)throw new O("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let w;try{w=await i.remoteRefs(l,h)}catch(f){let g=xe(f)===2,S=g?`The upstream branch ${p} 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 O(g?"remote_branch_missing":"git_command_failed",S)}let b=Es(w,p);if(!b)throw new O("remote_branch_missing",`The upstream branch ${p} was not found. Push it before handing off.`);if(b.toLowerCase()!==u.toLowerCase())throw new O("unpushed_commits",`Local HEAD does not match the upstream branch ${p}. Push the current commit before handing off.`);return{repoUrl:y,branch:p,headSha:u,...o?{workspaceRelativePath:o}:{}}}function Re(s){return s&&typeof s==="object"&&!Array.isArray(s)?s:void 0}function z(s){if(typeof s!=="string")return;return s.trim()||void 0}function Rs(s){return typeof s==="string"&&s.length>0?s:void 0}function Ps(s){let i=z(s.repoUrl),o=z(s.branch),r=z(s.headSha),c=z(s.modelId);if(!i||!o||!r||!c)throw Error("Cloud handoff fingerprint fields cannot be empty.");let l=z(s.organizationId),h=Rs(s.workspaceRelativePath),u=s.mode;return{repoUrl:i,branch:o,headSha:r,modelId:c,...l?{organizationId:l}:{},...h?{workspaceRelativePath:h}:{},...u?{mode:u}:{}}}function Cn(s,i){return s!==void 0&&i!==void 0&&s.repoUrl===i.repoUrl&&s.branch===i.branch&&s.headSha.toLowerCase()===i.headSha.toLowerCase()&&s.modelId===i.modelId&&s.organizationId===i.organizationId&&s.workspaceRelativePath===i.workspaceRelativePath&&s.mode===i.mode}function $s(s){let i=Re(s);if(!i||typeof i.repoUrl!=="string"||typeof i.branch!=="string"||typeof i.headSha!=="string"||typeof i.modelId!=="string")return;try{return Ps({repoUrl:i.repoUrl,branch:i.branch,headSha:i.headSha,modelId:i.modelId,...typeof i.organizationId==="string"?{organizationId:i.organizationId}:{},...typeof i.workspaceRelativePath==="string"?{workspaceRelativePath:i.workspaceRelativePath}:{},...i.mode==="plan"||i.mode==="yolo"||i.mode==="zen"?{mode:i.mode}:{}})}catch{return}}function kn(s){let i=Re(Re(s)?.handoff);if(!i)return;let o=z(i.toCloudSessionId),r=z(i.handedOffAt),c=i.status;if(!o||!r||c!=="pending"&&c!=="complete")return;let l=z(i.innerSessionId),h=z(i.dashboardUrl),u=$s(i.fingerprint);return{toCloudSessionId:o,handedOffAt:r,status:c,...l?{innerSessionId:l}:{},...h?{dashboardUrl:h}:{},...u?{fingerprint:u}:{}}}function An(s,i){return{...s??{},handoff:i}}function _n(s){let{handoff:i,cloudHandoffIntent:o,cloudHandoffSeedDispatched:r,...c}=s??{};return c}function Tn(s,i){let o=i.trim();if(!o)throw Error("Cloud session id cannot be empty.");let r=new URL("/agents",s);return r.searchParams.set("sessionId",o),r.toString()}function st(s){return s.map((i)=>{let o=i&&typeof i==="object"?i:{};return{role:o.role,content:o.content}})}function it(s,i){return s.length===i.length&&JSON.stringify(st(s))===JSON.stringify(st(i))}class Ut extends Error{constructor(s,i){super(`Cloud transcript verification failed (local ${s} messages, cloud ${i}).`);this.name="CloudHandoffTranscriptMismatchError"}}function Mn(s){let{id:i,repoUrl:o,remote:r,branch:c,sourceBranch:l,files:h,commits:u}=s;return{id:i,repoUrl:o,remote:r,branch:c,sourceBranch:l,files:h,commits:u}}async function A(s,i,o={}){try{return await new Promise((r,c)=>{let l=Us("git",i,{cwd:s,env:{...process.env,...o.env,GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_GRAFT_FILE:"/dev/null"},encoding:"utf8",maxBuffer:8388608,timeout:o.timeout??60000},(h,u)=>h?c(h):r(u.trimEnd()));if(o.input!==void 0)l.stdin?.on("error",c),l.stdin?.end(o.input)})}catch(r){let c=r instanceof Error&&"code"in r?r.code:void 0,l=c===null&&r instanceof Error&&"killed"in r&&r.killed===!0?`timed out after ${(o.timeout??60000)/1000} seconds`:`failed${typeof c==="number"?` (exit code ${c})`:""}. Check Git authentication, permissions, and repository state`;throw Error(`Git ${i[0]} ${l}.`)}}async function Ds(s,i){try{return await A(s,["config","--get",i])}catch{return""}}function rt(s){return/(^|\/)(\.env(?:\.[^/]*)?|\.npmrc|\.yarnrc\.yml|\.netrc|\.pgpass|\.pypirc|\.aws\/credentials|id_rsa|id_ed25519|credentials\.json)$|\.(pem|key|p12|pfx|jks|keystore)$/i.test(s)&&!/\.(example|sample|template)$/i.test(s)}async function qs(s,i){let o=(await A(s,["remote","get-url","--all",i])).split(`
8
+ `),r=(await A(s,["remote","get-url","--push","--all",i])).split(`
9
+ `),c=se(o[0]??""),l=r[0];if(c&&l&&o.length===1&&r.length===1&&se(l)===c)return{repoUrl:c,pushUrl:l};return}async function On(s,i){let o=await A(s,["rev-parse","--show-toplevel"]).catch(()=>{throw Error("Could not read the Git repository. Open a Git repository and check access before using /cloud.")}),r=(await A(s,["rev-parse","--show-prefix"])).replace(/\/$/,"");if((await A(o,["ls-files","-v","-z"])).split("\x00").some((k)=>/^[a-zS] /.test(k)))throw Error("Cloud preparation cannot include files marked skip-worktree or assume-unchanged. Review these flags and local changes before retrying /cloud.");let c=await A(o,["symbolic-ref","--short","HEAD"]).catch(()=>{throw Error("Could not read the current branch. Check out a Git branch before using /cloud.")}),l=await A(o,["rev-parse","HEAD"]),h=await A(o,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--no-renames"]),u=h.split("\x00").filter(Boolean).map((k)=>({status:k.slice(0,2),path:k.slice(3)})),p=(await A(o,["ls-files","--stage","-z"])).split("\x00").filter((k)=>k.startsWith("160000 ")).map((k)=>k.slice(k.indexOf("\t")+1));if(u.some((k)=>k.status.includes("U")||["AA","DD"].includes(k.status)||p.includes(k.path)))throw Error("Resolve conflicts or changes inside submodules before continuing in cloud.");if(u.some(({path:k})=>rt(k)))throw Error("Potentially sensitive files need review before cloud preparation. Keep private files out of the changes and unpublished history before retrying /cloud.");let m=await A(o,["write-tree"]),y=await Ms(nt(Hs(),"cline-handoff-index-")),w;try{let k={GIT_INDEX_FILE:nt(y,"index")};await A(o,["read-tree",m],{env:k}),await A(o,["add","-A","--",":/"],{env:k}),w=await A(o,["write-tree"],{env:k})}finally{await Os(y,{recursive:!0,force:!0})}if((await A(o,["ls-tree","-r","-z",w])).split("\x00").filter((k)=>k.startsWith("160000 ")).map((k)=>k.slice(k.indexOf("\t")+1)).some((k)=>!p.includes(k)))throw Error("Nested Git repositories cannot be included in automatic cloud preparation. Review them before continuing.");if(await A(o,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--no-renames"])!==h||await A(o,["rev-parse","HEAD"])!==l||await A(o,["write-tree"])!==m)throw Error("The repository changed while preparing the preview. Run /cloud again.");i?.();let b=await Ds(o,`branch.${c}.remote`)||"origin";if(b==="."||b.startsWith("-"))throw Error("Choose a GitHub remote before continuing in cloud.");let f=await qs(o,b);if(!f)throw Error("Cloud preparation requires one GitHub repository shared by the fetch and push destination. Review the remote configuration first.");let{repoUrl:g}=f,S=(await A(o,["ls-remote","--heads",b])).split(`
10
+ `).map((k)=>k.split(/\s/)[0]??"").filter((k)=>/^[0-9a-f]{40,64}$/.test(k)),C=[],_=S.includes(l);if(!_&&S.length)try{let k={GIT_NO_LAZY_FETCH:"1"},D=(await A(o,["cat-file","--batch-check=%(objectname) %(objecttype)"],{input:`${S.join(`
11
+ `)}
12
+ `,env:k})).split(`
13
+ `),B=S.filter((R,x)=>D[x]===`${R} commit`);if(B.length)_=await A(o,["rev-list","--count","--stdin"],{input:`${[l,...B.map((R)=>`^${R}`)].join(`
14
+ `)}
15
+ `,env:k})==="0"}catch{}if(!_){if(S.length)await A(o,["fetch","--no-prune","--no-tags","--no-write-fetch-head","--no-recurse-submodules","--refmap=","--stdin",b],{input:`${S.join(`
16
+ `)}
17
+ `});let k=`${[l,...S.map((D)=>`^${D}`)].join(`
18
+ `)}
19
+ `;if(C=(await A(o,["log","--format=%h %s","--stdin"],{input:k})).split(`
20
+ `).filter(Boolean),(await A(o,["log","--format=","--name-only","-z","--root","-c","--no-renames","--stdin"],{input:k})).split("\x00").some(rt))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:ot(),root:o,workspaceRelativePath:r,repoUrl:g,remote:b,branch:`cline/handoff-${ot().slice(0,12)}`,sourceBranch:c,headSha:l,treeSha:w,files:u,commits:C}}var Bs=610000,Ls=3000,V=15000,zs="CLOUD_SESSION_ERROR:",Mt="__cline_create_request__:";function Ns(s){return(s.trim().split(`
21
+ `)[0]??"").trim().slice(0,72)}class I extends Error{code;detail;connectUrl;status;constructor(s,i,o,r){super(`${zs}${JSON.stringify({code:s,message:i,connectUrl:o})}`);this.code=s,this.detail=i,this.connectUrl=o,this.status=r,this.name="CloudSessionError"}}class Ot extends I{constructor(s){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=s}}class Ht extends Error{constructor(s){super(s instanceof Error?s.message:"Cloud handoff creation was rejected.",{cause:s});this.name="CloudHandoffCreationRejectedError"}}function Pe(s){let i=s.length;while(i>0&&s[i-1]==="/")i--;return s.slice(0,i)}function Gs(s){return`${Mt}${s}`.slice(0,255)}function at(s){return s?.startsWith(Mt)===!0}function Dt(s){switch(s){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return s;default:return}}function he(s){let i=ne(s.replace(/^workos:/,""));return typeof i?.sub==="string"&&i.sub.trim()?i.sub.trim():void 0}function dt(s){return new Promise((i,o)=>{if(s.aborted){o(s.reason);return}let r=()=>{clearTimeout(c),o(s.reason)},c=setTimeout(()=>{s.removeEventListener("abort",r),i()},Ls);s.addEventListener("abort",r,{once:!0})})}function Fs(s,i){if(s&&typeof s==="object"){let o=s.error;if(typeof o==="string"&&o.trim())return o.trim()}return i}function pe(s,i,o,r){let c=Fs(i,`Cloud session request failed (${s})`);if(s===401)return new I("authentication_required",c);if(s===404)return new I("session_not_found",c);if(s===410)return new I("session_expired",c);if(s===412)return new I("github_not_connected",c,r??`${Pe(o)}/dashboard/integrations`);if(s===403&&c.trim().toLowerCase()==="forbidden")return new I("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,s);return new I("request_failed",c,void 0,s)}class Vs{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(s){this.options=s,this.apiBaseUrl=Pe(s.apiBaseUrl),this.appBaseUrl=Pe(s.appBaseUrl),this.fetchImpl=s.fetch??fetch,this.createTimeoutMs=s.createTimeoutMs??Bs}async request(s,i={},o,r,c){let l=!1,h;while(!0){let u;try{u=typeof r==="string"?r:await this.options.getAuthToken()}catch(y){if(h)throw pe(401,void 0,this.appBaseUrl,o);throw y}if(!u?.trim())throw new I("authentication_required","Sign in to Cline before starting a cloud session.");if(u.trim()===h)throw new I("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof r==="object"){if(r.subject?he(u.trim())!==r.subject:u.trim()!==r.token)throw new I("authentication_required","The signed-in account changed during cloud session creation.");r.token=u.trim()}c?.();let p=await this.fetchImpl(`${this.apiBaseUrl}${s}`,{...i,signal:i.signal??AbortSignal.timeout(V),headers:{Accept:"application/json",Authorization:`Bearer ${u.trim()}`,...i.body?{"Content-Type":"application/json"}:{},...i.headers}}),m=p.status===204?void 0:await p.json().catch(()=>{return});if(!p.ok){if(p.status===401&&typeof r==="object"&&!l&&r.subject){l=!0,h=u.trim();continue}throw pe(p.status,m,this.appBaseUrl,o)}return m?.data}}async list(s){return await this.listWithToken(s)}async listWithToken(s,i,o=!1){let r=s?.trim()?`?organizationId=${encodeURIComponent(s.trim())}`:"";return(await this.request(`/api/v1/session${r}`,{},void 0,i)??[]).flatMap((c)=>{if(!c||typeof c!=="object"||typeof c.id!=="string")return[];return[{...c,title:!o&&at(c.title)?void 0:c.title,repoContext:c.repoContext&&typeof c.repoContext==="object"?c.repoContext:{},metadata:{...c.metadata&&typeof c.metadata==="object"?c.metadata:{},...!o&&at(c.title)?{createRequestTitle:c.title}:{}}}]})}async listRepositories(s){let i=s?.trim(),o=i?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,r=i?`/api/v1/organizations/${encodeURIComponent(i)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let c=await this.request(r)??[];return{connected:!0,connectUrl:o,repositories:c.flatMap((l)=>{let h=Number(l.id),u=String(l.html_url??l.clone_url??"").trim();if(!Number.isSafeInteger(h)||h<=0||!u)return[];let p=String(l.name??"").trim();return[{id:h,name:p,fullName:String(l.full_name??(p||u)).trim(),url:u,defaultBranch:String(l.default_branch??"").trim()}]})}}catch(c){if(c instanceof I&&c.code==="session_not_found")return{connected:!1,connectUrl:o,repositories:[]};throw c}}async listBranches(s,i,o={}){if(!Number.isSafeInteger(s)||s<=0)throw new I("request_failed","Select a GitHub repository before loading branches.");let r=i?.trim(),c=r?`/api/v1/organizations/${encodeURIComponent(r)}/integrations/github/repositories/${s}/branches`:`/api/v1/integrations/github/repositories/${s}/branches`,l=new URLSearchParams,h=o.query?.trim(),u=o.cursor?.trim();if(h)l.set("query",h);if(u)l.set("cursor",u);let p=l.size>0?`${c}?${l}`:c;try{let m=await this.request(p),y=Array.isArray(m)?m:Array.isArray(m?.items)?m.items:[],w=h?.toLowerCase();return{available:!0,branches:y.flatMap((b)=>{let f=String(b.name??"").trim();return f&&(!Array.isArray(m)||!w||f.toLowerCase().includes(w))?[f]:[]}),nextToken:Array.isArray(m)?"":String(m?.nextToken??"").trim()}}catch(m){if(m instanceof I&&m.code==="session_not_found")return{available:!1,branches:[]};throw m}}async status(s,i={}){return await this.request(`/api/v1/session/${encodeURIComponent(s)}/status`,{signal:i.signal?AbortSignal.any([i.signal,AbortSignal.timeout(V)]):void 0},void 0,i.authToken)}async create(s){if(s.handoff&&typeof s.handoff.onCreating!=="function")throw new I("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let i=(await this.options.getAuthToken())?.trim();if(!i)throw new I("authentication_required","Sign in to Cline before starting a cloud session.");let o={token:i,subject:he(i)},r=Gs(s.requestId?.trim()||js()),c=s.handoff?`${o.subject??i}/${s.organizationId??""}/${s.requestId?.trim()??""}`:void 0;if(s.handoff&&!s.requestId?.trim())throw new I("request_failed","A stable request id is required for cloud handoff creation.");let l=async()=>(await this.listWithToken(s.organizationId??void 0,o,!0)).filter((w)=>w.title===r&&w.repoContext.repoUrl===s.repoUrl&&w.metadata.modelId===s.modelId&&(!s.branch?.trim()||w.repoContext.branch===s.branch.trim())),h=async(w)=>{if(w.status==="failed"||w.expiredAt&&Date.parse(w.expiredAt)<=Date.now()){let f=new I(w.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(w.id,o)}catch(g){if(!(g instanceof I&&(g.code==="session_not_found"||g.code==="session_expired")))throw AggregateError([f,g],"The unusable recovered cloud handoff workspace could not be removed.")}if(c)this.unconfirmedHandoffCreates.delete(c),this.completedHandoffCreates.delete(c);throw await s.handoff?.onOuterSessionRemoved?.(w.id),f}await s.handoff?.onOuterSessionCreated(w.id,{created:!1});let b={sessionId:w.id,status:w.status,sandboxUrl:w.sandboxUrl,cleanupAuthToken:o.token};if(c)this.unconfirmedHandoffCreates.delete(c),this.completedHandoffCreates.set(c,b);return b};if(c){let w=await l();if(w.length>1)throw new I("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(w[0])return await h(w[0]);let b=this.completedHandoffCreates.get(c);if(b){try{await this.request(`/api/v1/session/${encodeURIComponent(b.sessionId)}/status`,{},void 0,o)}catch(f){if(f instanceof I&&(f.code==="session_not_found"||f.code==="session_expired"))await s.handoff?.onOuterSessionRemoved?.(b.sessionId),this.completedHandoffCreates.delete(c),this.unconfirmedHandoffCreates.delete(c);throw f}return await s.handoff?.onOuterSessionCreated(b.sessionId,{created:!1}),{...b,cleanupAuthToken:o.token}}if(this.unconfirmedHandoffCreates.has(c))throw new I("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(c)}try{await s.handoff?.onCreating()}catch(w){if(c)this.unconfirmedHandoffCreates.delete(c);throw w}let u=new AbortController,p=setTimeout(()=>u.abort(),this.createTimeoutMs),m,y=!1;try{let w=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:s.modelId,repoUrl:s.repoUrl,...s.sandboxType?{sandboxType:s.sandboxType}:{},title:r,...s.branch?.trim()?{branch:s.branch.trim()}:{},...s.organizationId?.trim()?{organizationId:s.organizationId.trim()}:{}}),signal:u.signal},s.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,o,()=>{y=!0}),b=w?.sessionId?.trim();if(!b)throw new I("request_failed","The cloud session service returned no session id.");m=b,await this.persistHandoffOuterSession(s,b,o,c);let f={sessionId:b,status:w.status?.trim()||"provisioning",sandboxUrl:w.sandboxUrl?.trim()??"",cleanupAuthToken:o.token};if(c)this.unconfirmedHandoffCreates.delete(c),this.completedHandoffCreates.set(c,f);return f}catch(w){if(m)throw w;let b=!y||w instanceof I&&(w.status!==void 0&&w.status>=400&&w.status<500&&w.status!==408&&w.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(w.code));if(c&&b)throw this.unconfirmedHandoffCreates.delete(c),new Ht(w);if(u.signal.aborted||!(w instanceof I)||w instanceof I&&w.code==="request_failed"&&(w.status===void 0||w.status>=500||w.status===408||w.status===409)){let f=[];try{f=await l()}catch(S){if(s.handoff)throw AggregateError([w,S],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(!s.handoff&&!b&&f.length!==1)throw new Ot(w);if(f.length>1)throw new I("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let g=f[0];if(g){if(s.handoff)return await h(g);return{sessionId:g.id,status:g.status,sandboxUrl:g.sandboxUrl,cleanupAuthToken:o.token}}}else if(c)this.unconfirmedHandoffCreates.delete(c);throw w}finally{clearTimeout(p)}}async persistHandoffOuterSession(s,i,o,r){if(!s.handoff)return;try{await s.handoff.onOuterSessionCreated(i,{created:!0})}catch(c){try{await this.deleteWithAuth(i,o.token)}catch(l){if(!(l instanceof I&&(l.code==="session_not_found"||l.code==="session_expired")))throw AggregateError([c,l],`Cloud session ${i} was created but its recovery record could not be saved or its sandbox removed.`)}if(r)this.unconfirmedHandoffCreates.delete(r);throw await s.handoff.onOuterSessionRemoved?.(i),c}}async waitUntilReady(s,i,o){i=AbortSignal.any([i,AbortSignal.timeout(this.createTimeoutMs)]);let r=await this.options.getAuthToken(),c=r?{token:r,subject:he(r)}:void 0;while(!i.aborted){let l;try{l=await this.request(`/api/v1/session/${encodeURIComponent(s)}/status`,{signal:AbortSignal.any([i,AbortSignal.timeout(V)])},void 0,c)}catch(u){if(i.aborted)throw u;if(u instanceof I&&u.code!=="request_failed")throw u;await dt(i);continue}let h=l?.status?.trim().toLowerCase();if(o?.({phase:Dt(l?.phase)}),h==="ready"||h==="active")return;if(h==="failed")throw new I("session_failed",l?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(h!=="provisioning")throw new I("request_failed","The cloud session service returned an unexpected provisioning status.");await dt(i)}throw i.reason}async resume(s,i){return await this.request(`/api/v1/session/${encodeURIComponent(s)}/resume`,{method:"POST",signal:i?AbortSignal.any([i,AbortSignal.timeout(V)]):void 0})}async delete(s,i){await this.deleteWithAuth(s,i)}async deleteWithAuth(s,i){let o;try{await this.request(`/api/v1/session/${encodeURIComponent(s)}`,{method:"DELETE"},void 0,i)}catch(r){if(!(r instanceof I)||r.code!=="session_not_found"&&r.code!=="session_expired")throw r;o=r}for(let[r,c]of this.completedHandoffCreates)if(c.sessionId===s)this.completedHandoffCreates.delete(r),this.unconfirmedHandoffCreates.delete(r);if(o)throw o}async updateTitle(s,i){return await this.request(`/api/v1/session/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify({title:i})})}async history(s){let i=await this.options.getAuthToken();if(!i?.trim())throw new I("authentication_required","Sign in to Cline to load this session's history.");let o=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(s)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${i.trim()}`},signal:AbortSignal.timeout(V)});if(o.status===404)return null;let r=await o.json().catch(()=>{return});if(!o.ok)throw pe(o.status,r,this.appBaseUrl);if(!r||typeof r!=="object"||!("version"in r)||r.version!==1||!("messages"in r)||!Array.isArray(r.messages))throw new I("request_failed","Invalid archived session history");return r.messages}}var je={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"]},Ks="session_not_found";class Be extends Error{sessionId;code="session_not_found";constructor(s,i){super(i??(s?`session not found: ${s}`:"session not found"));this.sessionId=s,this.name="SessionNotFoundError"}}function ct(s){return s instanceof Be||typeof s==="object"&&s!==null&&"code"in s&&s.code==="session_not_found"}var ci="CLINE_HUB_DISCOVERY_PATH",li="CLINE_HUB_BUILD_ID",ui="CLINE_HUB_BUILD_EPOCH_MS",hi=30000,pi=15000,ut=100;function fi(s){return s.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function mi(s){return ni("sha256").update(s).digest("hex").slice(0,12)}function yi(s){if(!Number.isInteger(s)||!s||s<=0)return!1;try{return process.kill(s,0),!0}catch(i){return i instanceof Error&&"code"in i?String(i.code)==="EPERM":!1}}function ht(s){return new Promise((i)=>setTimeout(i,s))}function gi(s){return`${s}.lock`}async function vi(s){try{let i=JSON.parse(await Lt(ze(s,"owner.json"),"utf8"));if(typeof i.pid!=="number"||typeof i.acquiredAt!=="string")return;return{pid:i.pid,acquiredAt:i.acquiredAt}}catch{return}}async function fe(s){await Le(s,{recursive:!0,force:!0}).catch(()=>{return})}function ce(){let s=process.env[li]?.trim();if(s)return s;return"sdk-v1-5440fffc790ba5c6e5fa7cf89479eda8b49b27304efecf0ecb12ca78ad581c61".trim()||`source-${String(je.version)}`}function bi(){let s=Number(process.env[ui]);if(Number.isFinite(s)&&s>0)return s;return Number.isFinite(1793312823572)?1793312823572:void 0}function Nt(s,i=ce()){let o=Pt(s);if(!o.compatible)return o;let r=s.buildId?.trim();if(!r)return{compatible:!1,reason:"missing_build"};if(r!==i)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function pt(s){return typeof s==="number"&&Number.isFinite(s)&&s>0?s:void 0}function ft(s){let i=s?.trim().split(/[-+]/,1)[0];if(!i)return;let o=i.split(".").map((r)=>Number(r));if(o.length===0||o.some((r)=>!Number.isInteger(r)||r<0))return;return o}function Si(s,i){for(let o=0;o<Math.max(s.length,i.length);o++){let r=s[o]??0,c=i[o]??0;if(r!==c)return r<c?-1:1}return 0}function Ii(s,i){let o=s.buildId?.trim(),r=i.buildId?.trim();if(o&&r&&o===r)return 0;let c=pt(s.buildEpochMs),l=pt(i.buildEpochMs);if(c!==void 0&&l!==void 0&&c!==l)return c<l?-1:1;let h=ft(s.coreVersion),u=ft(i.coreVersion);if(h&&u){let p=Si(h,u);if(p!==0)return p}if(o&&r&&o!==r)return o<r?-1:1;return 0}function Ci(){return{buildId:ce(),buildEpochMs:bi(),coreVersion:String(je.version)}}function Gt(s,i){let o=i?.self??Ci(),r=Nt(s,o.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return Ii(o,s)<=0}function ki(s=process.argv[1]?.trim()||process.cwd()){let i=`hub-${mi(s)}`,o=process.env[ci]?.trim()||ze(Z(),"locks","hub","owners",`${fi(i)}.json`);return{ownerId:i,discoveryPath:o}}async function J(s,i={}){try{let o;try{o=await Lt(s,"utf8")}catch(c){if(c.code==="ENOENT")return;throw c}let r;try{r=JSON.parse(o)}catch{throw Error(`Invalid JSON in Hub discovery record: ${s}`)}if(!r||typeof r.hubId!=="string"||typeof r.protocolVersion!=="string"||typeof r.authToken!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string"||typeof r.startedAt!=="string"||typeof r.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${s}`);return{hubId:r.hubId,protocolVersion:r.protocolVersion,minClientProtocolVersion:typeof r.minClientProtocolVersion==="string"?r.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof r.maxClientProtocolVersion==="string"?r.maxClientProtocolVersion:void 0,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter((c)=>typeof c==="string"):void 0,coreVersion:typeof r.coreVersion==="string"?r.coreVersion:void 0,buildId:typeof r.buildId==="string"?r.buildId:void 0,buildEpochMs:typeof r.buildEpochMs==="number"?r.buildEpochMs:void 0,authToken:r.authToken,host:r.host,port:r.port,url:r.url,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:r.startedAt,updatedAt:r.updatedAt}}catch(o){if(i.onError==="throw")throw o;return}}async function Ai(s,i){await Vt(s,async()=>{let o=zt(s);await $e(o,{recursive:!0});let r=`${s}.${process.pid}.${ri(6).toString("hex")}.tmp`,c;try{c=await lt(r,"wx",384),await c.writeFile(`${JSON.stringify(i,null,2)}
22
+ `,{encoding:"utf8"}),await c.sync(),await c.close(),c=void 0,await ai(r,s);let l;try{l=await lt(o,"r"),await l.sync()}catch{}finally{await l?.close().catch(()=>{return})}}catch(l){throw await c?.close().catch(()=>{return}),await Le(r,{force:!0}).catch(()=>{return}),l}})}async function le(s){await Vt(s,async()=>{await Le(s,{force:!0}).catch(()=>{return})})}async function Ft(s,i,o){let r=gi(s);await $e(zt(r),{recursive:!0});let c=Date.now()+pi;while(!0){try{await $e(r,{recursive:!1})}catch(l){if((l instanceof Error&&"code"in l?String(l.code):"")!=="EEXIST")throw l;let h=await vi(r);if(!h){if(Date.now()>=c){await fe(r);continue}await ht(ut);continue}let u=Date.now()-Date.parse(h.acquiredAt);if(!yi(h.pid)||u>hi){await fe(r);continue}if(Date.now()>=c)throw Error(`Timed out waiting for hub ${i} lock ${r}`);await ht(ut);continue}try{return await di(ze(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
23
+ `,"utf8"),await o()}finally{await fe(r)}}}function Vt(s,i){return Ft(`${s}.mutation`,"discovery mutation",i)}function _i(s,i){return Ft(s,"startup",i)}async function Kt(s,i){Ze();try{let o=await fetch(i?.authToken?Ei(s):Jt(s),{headers:i?.authToken?{authorization:`Bearer ${i.authToken}`}:void 0,signal:i?.signal});if(!o.ok)return;let r=await o.json();if(typeof r.protocolVersion!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string")return;return{protocolVersion:r.protocolVersion,minClientProtocolVersion:typeof r.minClientProtocolVersion==="string"?r.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof r.maxClientProtocolVersion==="string"?r.maxClientProtocolVersion:void 0,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter((c)=>typeof c==="string"):void 0,coreVersion:typeof r.coreVersion==="string"?r.coreVersion:void 0,buildId:typeof r.buildId==="string"?r.buildId:void 0,buildEpochMs:typeof r.buildEpochMs==="number"?r.buildEpochMs:void 0,host:r.host,port:r.port,url:r.url,hubId:typeof r.hubId==="string"?r.hubId:void 0,authToken:typeof r.authToken==="string"?r.authToken:void 0,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:typeof r.startedAt==="string"?r.startedAt:void 0,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:void 0}}catch{return}}function Ti(s,i,o="/hub"){return new URL(`ws://${s}:${i}${o}`).toString()}function Jt(s){let i=new URL(s);return i.protocol=i.protocol==="wss:"?"https:":"http:",i.pathname="/health",i.search="",i.toString()}function Ei(s){let i=new URL(Jt(s));return i.pathname="/status",i.toString()}var xi="CLINE_HUB_HOST",Ri="CLINE_HUB_PORT",Pi="CLINE_HUB_PATHNAME",$i="127.0.0.1",Ui=jn,Mi="/hub";function mt(s){return re(s)==="development"?$n:Ui}function Oi(s={}){return(s.env??process.env)[xi]?.trim()||$i}function Hi(s={}){let i=(s.env??process.env)[Ri]?.trim();if(!i)return mt(s);let o=Number.parseInt(i,10);if(!Number.isInteger(o)||o<1||o>65535)return mt(s);return o}function Di(s={}){return(s.env??process.env)[Pi]?.trim()||Mi}function qi(s={},i={}){return{host:s.host??Oi(i),port:s.port??Hi(i),pathname:s.pathname??Di(i)}}var Bi="shared:cline",Li="CLINE_HUB_DISCOVERY_PATH",zi="hub-production";function Ne(s=Bi){return ki(`${s}@${ce()}`)}function Qt(){return{ownerId:zi,discoveryPath:process.env[Li]?.trim()||ji(Z(),"locks","hub","production.json")}}var wt=15000,Ni=200,yt=3000,Fi=100,Vi=[100,250,500,1000,2000],Yt="--cline-hub-daemon",Wi=3,Ki=60000,gt=new Map;function Ji(s,i=Date.now()){let o=gt.get(s);if(!o||i-o.windowStartedAt>Ki)return gt.set(s,{count:1,windowStartedAt:i}),!0;return o.count+=1,o.count<=Wi}function Qi(s){return[...s.host?["--host",s.host]:[],...typeof s.port==="number"?["--port",String(s.port)]:[],...s.pathname?["--pathname",s.pathname]:[]]}function Yi(){try{let s=ii(Z(),"logs","hub-daemon.log");return Ys(si(s),{recursive:!0}),{fd:Xs(s,"a"),logPath:s}}catch{return}}function Xi(){return re()==="production"?Qt():Ne()}function W(s){return Gt(s)}function Zi(s){try{let i=JSON.parse(Zs(`${s}.superseded`,"utf8"));return{url:typeof i.url==="string"?i.url:void 0,authToken:typeof i.authToken==="string"?i.authToken:void 0,pid:typeof i.pid==="number"?i.pid:void 0}}catch{return}}function we(s){try{ei(`${s}.superseded`)}catch{}}function vt(s,i,o){if(!i||i.url!==o)return s;return{...s,authToken:s.authToken??i.authToken,pid:s.pid??i.pid}}async function K(s,i){try{return await Kt(s,{authToken:i})}catch{return}}async function bt(s,i){let o=Date.now()+i;while(Date.now()<o){if(!(await K(s))?.url)return!0;await new Promise((r)=>setTimeout(r,Fi))}return!1}async function Ge(s,i){if(!Ji(s.url))return!1;await X(s.url,s.authToken,"retired by newer install").catch(()=>!1),await To(s.url,s.authToken).catch(()=>!1);let o=await bt(s.url,yt);if(!o&&s.pid&&eo(s.pid)){try{process.kill(s.pid,"SIGTERM")}catch{}o=await bt(s.url,yt)}if(o)await le(i).catch(()=>{return});return o}function eo(s){try{return process.kill(s,0),!0}catch(i){return i?.code==="EPERM"}}async function to(s){try{let i=await os(s.url,s.authToken);return i.activeSessionCount>0||(i.activePluginRequests??0)>0||(i.activeCloudCommands??0)>0}catch{return!1}}async function ye(s,i){if(W(s))return"reusable";let o=await X(s.url,s.authToken,"retired by newer install").catch(()=>!1);if(await to(s)){if(o)await X(s.url,s.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Ge(s,i);if(!r&&o)await X(s.url,s.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function so(s){if(re()!=="production")return;let i=Ne();if(i.discoveryPath===s.discoveryPath)return;let o=await J(i.discoveryPath);if(o?.url)await Ge(o,i.discoveryPath);else await le(i.discoveryPath).catch(()=>{return})}function io(){let s=import.meta.url.endsWith(".ts")?"ts":"js";return oi(new URL(`./entry.${s}`,import.meta.url))}function oo(s,i){if(qn(s))return[Yt];return[...i&&s.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],s]}var Q;function no(s,i){let o,r;if(Q)o=Q.command,r=Q.args??[Yt];else{let c=process.execPath?.trim();if(!c)throw Error("unable to resolve runtime executable for hub daemon");let l=ti(c).toLowerCase().includes("bun");o=c,r=oo(io(),l)}return{launcher:o,args:[...r,"--cwd",s,...Qi(i),...i.manageConnectors===!1?["--no-connectors"]:[]],cwd:s,env:{...zn(Me({...process.env,...Q?.env}),ro()),CLINE_NO_INTERACTIVE:"1",[Zt]:"1"}}}function ro(){let s=Gi(),i=s?.name?.trim();return i?{client:i,version:s?.version,transport:"local"}:void 0}function ao(s){if(!s||typeof s!=="object")return!1;if(("code"in s?s.code:void 0)==="ETXTBSY")return!0;let i="message"in s?s.message:void 0;return typeof i==="string"&&i.includes("ETXTBSY")}function co(s,i={}){if(jt())return;let o=no(s,i),r=Yi();try{Js(o.launcher,o.args,{detached:!0,stdio:r?["ignore",r.fd,r.fd]:"ignore",env:o.env,cwd:o.cwd,windowsHide:!0}).unref()}finally{if(r)Qs(r.fd)}}async function lo(s,i={}){for(let o=0;;o++)try{co(s,i);return}catch(r){let c=Vi[o];if(!ao(r)||c===void 0)throw r;await new Promise((l)=>setTimeout(l,c))}}async function uo(s,i,o={}){let r=o.host!==void 0||o.port!==void 0||o.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),c=qi(o),l=Ti(c.host,c.port,c.pathname),h=(f)=>{if(!r)We(f.url,f.authToken);return f};await so(s).catch(()=>{return});let u=await J(s.discoveryPath),p=u?.url?void 0:Zi(s.discoveryPath),m=!1;if(u?.url){let f=u.authToken;if(!f)m=!0,await Ge(u,s.discoveryPath);else{let g=await K(u.url,f);if(g?.url&&W(g)&&await N(g.url,{authToken:f}))return we(s.discoveryPath),h({url:g.url,authToken:f});if(g?.url){if(await ye({...g,authToken:f},s.discoveryPath)==="deferred_busy"&&await N(g.url,{authToken:f}))return h({url:g.url,authToken:f})}else await le(s.discoveryPath).catch(()=>{return})}}let y=await K(l);if(y?.url){let f=vt(y,u??p,l);if(W(y)){let S=[y.authToken,u?.authToken,p?.authToken].filter((C)=>typeof C==="string"&&C.trim().length>0);for(let C of S){if(!await N(y.url,{authToken:C}))continue;let _={hubId:y.hubId??`repaired-${y.port}`,protocolVersion:y.protocolVersion,minClientProtocolVersion:y.minClientProtocolVersion,maxClientProtocolVersion:y.maxClientProtocolVersion,capabilities:y.capabilities,coreVersion:y.coreVersion,buildId:y.buildId,authToken:C,host:y.host,port:y.port,url:y.url,pid:y.pid??u?.pid??p?.pid,startedAt:y.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await Ai(s.discoveryPath,_)}catch{}return we(s.discoveryPath),h({url:y.url,authToken:C})}throw Error(`A compatible Cline Hub is already running at ${l}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${m?" 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 ye(f,s.discoveryPath);if(g==="deferred_busy"){for(let S of[f.authToken,u?.authToken].filter((C)=>typeof C==="string"&&C.trim().length>0))if(await N(y.url,{authToken:S}))return h({url:y.url,authToken:S});if(o.allowPortFallback!==!0&&c.port!==0)throw Error(`An older Cline Hub is running at ${l} 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"&&o.allowPortFallback!==!0&&c.port!==0)throw Error(`An incompatible Cline Hub is already running at ${l} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let w=o.allowPortFallback===!0&&c.port!==0?{...c,port:0}:c;await o.beforeSpawn?.(),await lo(i,{...w,manageConnectors:o.manageConnectors});let b=Date.now()+wt;while(Date.now()<b){let f=await J(s.discoveryPath);if(f?.url&&f.authToken){let S=await K(f.url,f.authToken);if(S?.url&&W(S)&&await N(S.url,{authToken:f.authToken}))return we(s.discoveryPath),h({url:S.url,authToken:f.authToken})}let g=await K(l);if(g?.url&&!W(g)){let S=vt(g,f??p,l),C=await ye(S,s.discoveryPath);if(C==="deferred_busy"&&f?.authToken&&await N(g.url,{authToken:f.authToken}))return h({url:g.url,authToken:f.authToken});if(C==="failed"&&o.allowPortFallback!==!0&&c.port!==0)throw Error(`An incompatible Cline Hub is still running at ${l} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((S)=>setTimeout(S,Ni))}throw Error(`Timed out after ${wt}ms waiting for detached hub startup.`)}async function ho(s,i={}){let o=Xi();return await _i(o.discoveryPath,async()=>uo(o,s,i))}function po(){return re()==="production"?Qt():Ne()}function fo(){let s=globalThis.WebSocket;if(!s)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return s}function mo(s){let i=new URL(s);i.protocol=s.protocol==="wss:"?"https:":"http:";let o=xa(i.toString());if(!o)return;return s.protocol==="wss:"?new Bt.HttpsProxyAgent(o):new qt.HttpProxyAgent(o)}function es(s){if(typeof s==="string")return s;if(s instanceof Uint8Array)return Buffer.from(s).toString();if(s instanceof ArrayBuffer)return Buffer.from(s).toString();if(Array.isArray(s))return Buffer.concat(s.map((i)=>Buffer.from(i))).toString();if(s&&typeof s==="object"&&"data"in s&&typeof s.data<"u")return es(s.data);return String(s)}function wo(s){if(typeof s==="string")return s;if(s instanceof Uint8Array)return Buffer.from(s).toString("utf8");if(s instanceof ArrayBuffer)return Buffer.from(s).toString("utf8");return""}function St(s){let i=s,o=wo(i.reason);return new U("hub_connection_closed",i.code||o?`Hub connection closed (code=${i.code??0}${o?`, reason=${o}`:""})`:Ue,{closeCode:i.code,closeReason:o||void 0})}function ve(s,i){if(s instanceof U)return s;if(s instanceof Error)return new U("hub_connect_failed",s.message);if(s&&typeof s==="object"&&"error"in s&&s.error instanceof Error)return new U("hub_connect_failed",s.error.message);let o=s&&typeof s==="object"&&"message"in s&&typeof s.message==="string"?s.message.trim():"";if(o)return new U("hub_connect_failed",o);let r=s&&typeof s==="object"&&"type"in s&&typeof s.type==="string"?s.type.trim():"";return new U("hub_connect_failed",r?`Failed to connect to hub at ${i.toString()} (${r} event before socket open).`:`Failed to connect to hub at ${i.toString()}.`)}var be="*",Y=8000,yo="cline-hub-auth.",ts=new Map,ss=new Set,go=3000,Ue="Hub connection closed",vo=250,bo=5000,It=0.5;class U extends Error{code;details;constructor(s,i,o){super(i);this.code=s,this.details=o,this.name="HubTransportError"}}function So(s){return s instanceof U}class oe extends Error{command;code;constructor(s,i,o){super(o);this.command=s,this.code=i,this.name="HubCommandError"}}function Fe(s,i={}){let o=s.searchParams.get("authToken")?.trim();if(s.searchParams.delete("authToken"),o)return o;if(i.skipRegistry)return;let r=Ve(s.toString());return r?ts.get(r):void 0}function Io(s){try{let i=new URL(s).hostname.toLowerCase().replace(/^\[|\]$/g,"");return i==="localhost"||i==="127.0.0.1"||i==="::1"}catch{return!1}}function Ve(s){if(!Io(s))return;let i=new URL(is(s));return i.search="",i.hash="",i.toString()}function Ct(s){let i=Ve(s);return!!i&&ss.has(i)}function We(s,i){let o=Ve(s);if(o){if(ss.add(o),i?.trim())ts.set(o,i)}return s}class ue{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new U("hub_connection_closed",Ue);sawSocketClose=!1;registered=!1;capabilities;constructor(s){if(this.options=s,s.authToken?.trim()&&s.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=s.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=s.url,this.capabilities=[...s.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(s){if(this.capabilities=s.map((i)=>({...i})),!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 s=new URL(this.currentUrl),i=this.options.authToken?.trim()||Fe(s,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(s.hash="",i&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let o=++this.connectGeneration,r=this.openSocket(s,i,o),c;this.connectPromise=r.then(async(h)=>{if(c=h,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(je.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),o!==this.connectGeneration||this.closedByClient){try{h.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let u of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(u));this.reconnectAttempt=0});let l=this.connectPromise;try{await l}catch(h){if(this.connectPromise===l)this.connectPromise=void 0;if(c&&this.socket===c){this.lastCloseError=ve(h,s),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{c.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw h}}async openSocket(s,i,o){let r=this.options.resolveConnectionHeaders,c;if(r){let m;try{c=await Promise.race([Promise.resolve().then(()=>r()),new Promise((y,w)=>{m=setTimeout(()=>{w(new U("hub_connect_timeout",`Timed out resolving hub connection headers after ${Y}ms`))},Y)})])}catch(y){let w=y instanceof U?y:new U("hub_connect_failed",y instanceof Error?y.message:String(y));if(o===this.connectGeneration)this.lastCloseError=w;throw w}finally{clearTimeout(m)}}if(o!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(c&&Object.keys(c).some((m)=>m.toLowerCase()==="sec-websocket-protocol")){let m=new U("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(o===this.connectGeneration)this.lastCloseError=m;throw m}let l;try{l=c?mo(s):void 0}catch(m){let y=ve(m,s);if(o===this.connectGeneration)this.lastCloseError=y;throw y}let h=c?new ba(s.toString(),{headers:{...c},agent:l}):new(fo())(s.toString(),i?[`${yo}${i}`]:void 0);this.socket=h;let u=!1,p=new Promise((m,y)=>{let w=!1,b=setTimeout(()=>{if(w)return;w=!0,u=!0;let f=new U("hub_connect_timeout",`Timed out connecting to hub after ${Y}ms`);if(this.socket===h)this.lastCloseError=f,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{h.close()}catch{}y(f)},Y);h.addEventListener("open",()=>{if(w)return;w=!0,clearTimeout(b),m()}),h.addEventListener("error",(f)=>{if(w)return;w=!0,clearTimeout(b);let g=ve(f,s);if(this.socket===h)this.lastCloseError=g,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;y(g)}),h.addEventListener("close",(f)=>{if(w)return;w=!0,clearTimeout(b);let g=u?this.lastCloseError:St(f);if(this.socket===h){if(!u)this.lastCloseError=g,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}y(g)})});return h.addEventListener("message",(m)=>{this.handleFrame(JSON.parse(es(m)))}),h.addEventListener("close",(m)=>{if(this.socket!==h)return;if(!u)this.lastCloseError=St(m),this.sawSocketClose=!0;this.registered=!1;for(let y of this.pendingReplies.values())y.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await p,h}subscribe(s,i){let o=i?.sessionId?.trim()||void 0,r={listener:s,sessionId:o};return this.listeners.add(r),this.adjustSubscriptionCount(o,1),()=>{if(!this.listeners.delete(r))return;this.adjustSubscriptionCount(o,-1)}}async command(s,i,o,r){let c=0,l=!1,h={...r,onDispatch:(p)=>{l=!0,r?.onDispatch?.(p)}},u=s!=="client.register"&&s!=="client.unregister";while(!0)try{return await this.commandOnce(s,i,o,h)}catch(p){if(!u||l&&r?.retryAfterDispatch===!1||c>=1||!await this.recoverLocalHubTransport(p))throw p;c+=1}}async commandOnce(s,i,o,r,c=!0){if(c)await this.connect();r?.beforeDispatch?.();let l=P("hubreq_");r?.onDispatch?.(l);let h=Xt(s,r?.timeoutMs),u=new Promise((m,y)=>{let w=h===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(l))return;y(new oe(s,"hub_command_timeout",`Hub command ${s} timed out after ${h}ms (hub=${this.currentUrl}, requestId=${l}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},h);this.pendingReplies.set(l,{resolve:(b)=>{if(w)clearTimeout(w);m(b)},reject:(b)=>{if(w)clearTimeout(w);y(b)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:s,requestId:l,clientId:this.clientId,sessionId:o,timeoutMs:h,payload:i}})}catch(m){throw this.pendingReplies.delete(l),m}let p=await u;if(!p.ok){if(p.error?.code===Ks){let m=o??(typeof i?.sessionId==="string"?i.sessionId:void 0);throw new Be(m,p.error.message)}throw new oe(s,p.error?.code,p.error?.message??`Hub command ${s} failed`)}return p}async recoverLocalHubTransport(s){if(!Ct(this.currentUrl)||!So(s))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let i=await kt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!i)return!1;return this.currentUrl=i,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 s=Math.min(vo*2**this.reconnectAttempt,bo),i=Math.round(s*(1-It)+Math.random()*s*It);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},i)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Ct(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let s=await kt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(s){this.currentUrl=s,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let s=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,s)this.lastCloseError=new U("hub_connection_closed",Ue);for(let i of this.pendingReplies.values())i.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!s)return;this.sawSocketClose=!1,this.socket=void 0;try{s.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(s){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new U("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(s))}sendSubscriptionFrame(s,i){let o=s==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(i)):void 0;this.sendFrame({kind:s,clientId:this.clientId,...i?{sessionId:i}:{},...o!==void 0?{sinceSequence:o}:{}})}adjustSubscriptionCount(s,i){let o=this.subscriptionKeyForSessionId(s),r=(this.subscriptionCounts.get(o)??0)+i;if(r<=0){if(this.subscriptionCounts.delete(o),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(i<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",s);return}if(this.subscriptionCounts.set(o,r),i>0&&r===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",s)}subscriptionKeyForSessionId(s){return s??be}subscriptionSessionIdFromKey(s){return s===be?void 0:s}handleFrame(s){switch(s.kind){case"reply":{let i=s.envelope.requestId;if(!i)return;let o=this.pendingReplies.get(i);if(!o)return;this.pendingReplies.delete(i),o.resolve(s.envelope);return}case"event":{let i=s.envelope.sequence;if(typeof i==="number"){let o=s.envelope.sessionId?.trim();for(let r of[be,o]){if(!r||!this.subscriptionCounts.has(r))continue;let c=this.lastEventSequenceByKey.get(r)??0;if(i>c)this.lastEventSequenceByKey.set(r,i)}}for(let o of this.listeners){if(o.sessionId&&o.sessionId!==s.envelope.sessionId?.trim())continue;o.listener(s.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function is(s){let i=new URL(s);if(i.protocol==="http:")i.protocol="ws:";else if(i.protocol==="https:")i.protocol="wss:";return i.toString()}async function N(s,i){let o=new ue({url:s,authToken:i?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:i?.workspaceRoot,cwd:i?.cwd});try{return await o.connect(),!0}catch{return!1}finally{o.close()}}async function Oe(s,i){let o=is(s),r=await Kt(o,{authToken:i?.authToken});if(!r)return{status:"unreachable",url:o};if(i?.requireCurrentBuild){let c=ce(),l=Nt(r,c);if(!l.compatible&&!Gt(r))return{status:l.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:o}}else if(!Pt(r).compatible)return{status:"protocol_mismatch",url:o};if(i?.verifyConnection===!0&&!await N(o,{workspaceRoot:i.workspaceRoot,cwd:i.cwd,authToken:i.authToken}))return{status:"unreachable",url:o};return{status:"compatible",url:o}}function Co(s){let i=s&&typeof s==="object"&&Array.isArray(s.sessions)?s.sessions:[],o=0,r=new Set;for(let l of i){if(!l||typeof l!=="object")continue;let h=l.participants;if(!Array.isArray(h)||h.length===0)continue;o+=1;for(let u of h){let p=u&&typeof u==="object"?u.clientId:void 0;if(typeof p==="string"&&p.trim())r.add(p)}}let c=(l)=>{let h=s&&typeof s==="object"?s[l]:void 0;return typeof h==="number"&&Number.isInteger(h)&&h>0?h:0};return{activeSessionCount:o,participantClientCount:r.size,activePluginRequests:c("activePluginRequests"),activeCloudCommands:c("activeCloudCommands")}}async function os(s,i,o){let r=new ue({url:s,authToken:i,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:o?.workspaceRoot,cwd:o?.cwd});try{let c=await r.command("session.list",{limit:500},void 0,{timeoutMs:go});return Co(c.payload)}finally{await r.dispose().catch(()=>{return})}}async function ko(s,i,o){try{let r=await os(s,i,o);return r.activeSessionCount===0&&r.activePluginRequests===0&&r.activeCloudCommands===0}catch{return!1}}async function Ao(s,i){let o=`${s.discoveryPath}.superseded`,r=await J(o);if(!r?.url||!r.authToken)return;let c=await Oe(r.url,{authToken:r.authToken});if(c.status!=="compatible")return;if(await ko(c.url,r.authToken,i))return;return We(c.url,r.authToken)}async function _o(s={}){if(s.endpoint?.trim()){let c=await Oe(s.endpoint);return c.status==="compatible"?c.url:void 0}let i=po(),o=await J(i.discoveryPath);if(!o?.url)return await Ao(i,s);let r=await Oe(o.url,{authToken:o.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return We(r.url,o.authToken);if(r.status==="protocol_mismatch")await le(i.discoveryPath).catch(()=>{return});return}async function kt(s={}){let i=await _o(s);if(i&&await N(i,{workspaceRoot:s.workspaceRoot,cwd:s.cwd}))return i;if(s.endpoint?.trim())return;try{return(await ho(s.workspaceRoot??process.cwd())).url}catch(o){s.onStartupError?.(o);return}}async function X(s,i,o,r){Ze();let c=new URL(s),l=i?.trim()||Fe(c);if(c.protocol==="ws:")c.protocol="http:";else if(c.protocol==="wss:")c.protocol="https:";if(c.pathname="/drain",c.hash="",o)c.searchParams.set("reason",o);if(r?.off)c.searchParams.set("off","1");return(await fetch(c,{method:"POST",headers:l?{authorization:`Bearer ${l}`}:void 0})).ok}async function To(s,i){Ze();let o=new URL(s),r=i?.trim()||Fe(o);if(o.protocol==="ws:")o.protocol="http:";else if(o.protocol==="wss:")o.protocol="https:";return o.pathname="/shutdown",o.hash="",(await fetch(o,{method:"POST",headers:r?{authorization:`Bearer ${r}`}:void 0})).ok}function Eo(s){let i=ge.cline?.models?.[s];return i?Wt(i):!1}var rs="## 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 xo(s,i){if(!s||typeof s!=="object")return;let o=s,r=typeof o.id==="string"?o.id.trim():"";if(!r)return;let c=typeof o.display_name==="string"?o.display_name.trim():typeof o.displayName==="string"?o.displayName.trim():"",l=typeof o.name==="string"?o.name.trim():"";return{id:r,name:c||l||r,catalogId:i}}function Se(s,i){return Array.isArray(s)?s.flatMap((o)=>{let r=xo(o,i);return r?[r]:[]}):[]}async function Ro(s,i={}){let o=s.trim(),r=o.length;while(r>0&&o[r-1]==="/")r--;let c=o.slice(0,r),l=async(S)=>{let C=await(i.fetchImpl??fetch)(`${c}${S}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!C.ok)throw Error(`HTTP ${C.status}`);return await C.json()},h,u;try{[h,u]=await Promise.all([l("/api/v1/ai/cline/models"),l("/api/v1/ai/cline/recommended-models")])}catch(S){throw Error("Could not load the cloud model catalog.",{cause:S})}let p=h&&typeof h==="object"?h:void 0,m=Se(Array.isArray(h)?h:p?.data,"cline"),y=u&&typeof u==="object"?u:void 0,w=y?.data&&typeof y.data==="object"?y.data:y,b=Se(w?.clinePass,"cline-pass"),f=Se(w?.clineCloud,"cline-cloud"),g=new Set;return[...i.isOrganizationSession?[]:b,...f,...m].filter((S)=>{if(g.has(S.id))return!1;return g.add(S.id),!0})}var Po=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function $o(s){switch(s){case"user":case"assistant":case"tool":case"system":case"status":case"error":return s;default:return"assistant"}}function Uo(s){return s.metadata&&typeof s.metadata==="object"&&!Array.isArray(s.metadata)?s.metadata:void 0}function Mo(s){let i=s?.userRunSpan;return typeof i==="number"&&Number.isInteger(i)&&i>=0?i:void 0}function Oo(s){if(typeof s.content==="string")return{hasAttachment:!1,text:s.content};if(!Array.isArray(s.content))return{hasAttachment:!1,text:"unknown"};let i=!1,o=!1,r=[];for(let c of s.content){if(!c||typeof c!=="object"||Array.isArray(c))continue;let l=c;if(l.type==="text"&&typeof l.text==="string")r.push(l.text);else if(l.type==="tool_result"||l.type==="tool-result")o=!0;else if(l.type==="file"||l.type==="image")i=!0}return{hasAttachment:i&&!o,text:r.join(`
24
+ `)}}function Ho(s){let i=me(s);return i.startsWith("[TASK RESUMPTION]")||i==="The user approved switching to act mode. Continue with the approved plan now."}function Do(s){if($o(s.role)!=="user")return 0;let i=Uo(s),o=typeof i?.kind==="string"?i.kind:void 0,r=Mo(i);if(o==="compaction"||o==="compaction_summary")return r??1;if(r!==void 0)return r;if(o&&Po.has(o))return 0;let c=Oo(s);if(!c.hasAttachment&&!me(c.text))return 0;if(!c.hasAttachment&&Ho(c.text))return 0;return 1}function qo(s){return Do(s)>0}function Ie(s){return Array.isArray(s?.sessions)?s.sessions.filter((i)=>Boolean(i)&&typeof i==="object"&&!Array.isArray(i)):[]}function At(s){let i=s.updatedAt;return typeof i==="number"?i:Date.parse(String(i??""))||0}function _t(s){let i=s?.metadata&&typeof s.metadata==="object"?s.metadata:void 0;return String(i?.model??s?.model??"").trim()}function Ce(s){let i=s.metadata&&typeof s.metadata==="object"?s.metadata:void 0;return!String(i?.parentSessionId??s.parentSessionId??"").trim()}function as(s,i="text"){if(!s||typeof s!=="object"||Array.isArray(s))return"";let o=s.content;if(typeof o==="string")return i==="text"?o.trim():"";if(!Array.isArray(o))return"";return o.map((r)=>r&&typeof r==="object"&&!Array.isArray(r)?i==="thinking"&&r.type==="redacted_thinking"?"[redacted]":String(r[i]??""):"").join("").trim()}function ee(s){let i=s.trim(),o=i.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(o?o[1]:i).trim()}function ae(s,i,o){let r=ee(o);return s.filter((c)=>Boolean(c)&&typeof c==="object"&&!Array.isArray(c)&&String(c.role??"").toLowerCase()==="user"&&(r!==""||qo(c))&&ee(as(c))===r).length+i.filter((c)=>ee(c.prompt)===r).length}function ds(s){return s.flatMap((i)=>{if(i.event!=="session.pending_prompt_submitted")return[];let o=i.payload?.prompt&&typeof i.payload.prompt==="object"&&!Array.isArray(i.payload.prompt)?i.payload.prompt:void 0,r=String(o?.id??"").trim();if(!r)return[];return[{id:r,prompt:String(o?.prompt??""),steer:o?.delivery==="steer",attachmentCount:typeof o?.attachmentCount==="number"?o.attachmentCount:0,userImages:Array.isArray(o?.userImages)?o.userImages.filter((c)=>typeof c==="string"):void 0}]})}var jo=new Set(["run.completed","run.aborted","run.failed"]),Bo=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function Tt(s,i){return s.filter((o)=>Boolean(o)&&typeof o==="object"&&!Array.isArray(o)&&String(o.role??"").toLowerCase()==="assistant").map((o)=>as(o,i)).filter(Boolean)}function Et(s,i,o="text"){let r=new Map;for(let c of Tt(i,o))r.set(c,(r.get(c)??0)+1);return Tt(s,o).filter((c)=>{let l=r.get(c)??0;if(l===0)return!0;if(l===1)r.delete(c);else r.set(c,l-1);return!1})}function de(s,i,o=new Set){if(!s||typeof s!=="object")return o;if(Array.isArray(s)){for(let l of s)de(l,i,o);return o}let r=s,c=i==="tool_use"?r.id:r.tool_use_id;if(r.type===i&&typeof c==="string")o.add(c);for(let l of Object.values(r))de(l,i,o);return o}function xt(s,i="assistant"){let o="",r="";for(let c of s)if(c.event===`${i}.delta`)r+=i==="reasoning"&&c.payload?.redacted&&!c.payload?.text?"[redacted]":typeof c.payload?.text==="string"?c.payload.text:"";else if(c.event===`${i}.finished`){let l=c.payload?.[i==="assistant"?"text":"reasoning"],h=typeof l==="string"&&l?l:r;if(h)o=h;r=""}return(o||r).trim()}function Lo(s,i,o={}){let r=o.queueSnapshotApplied!==!1,c=Et(i,o.baselineMessages??[]),l=Et(i,o.baselineMessages??[],"thinking"),h=de(i,"tool_use"),u=de(i,"tool_result"),p=new Set(s.slice(0,o.messagesSnapshotEventCutoff??s.length)),m=new Set,y=new Map;for(let S of s.slice(0,o.messagesSnapshotEventCutoff??s.length)){let C=ds([S])[0];if(!C)continue;let _=ee(C.prompt),k=y.get(_)??Math.max(0,ae(i,[],_)-ae(o.baselineMessages??[],[],_));if(y.set(_,Math.max(0,k-1)),k>0)m.add(S)}let w=[...r?s.slice(o.queueSnapshotEventCutoff??s.length):s].reverse().find((S)=>S.event==="session.pending_prompts"),b=[],f=[],g=(S)=>{if(f.length===0)return;let C=f.filter((M)=>p.has(M)),_=(M)=>{if(!S)return-1;let T=[...C].reverse().findIndex((hs)=>hs.event===`${M}.finished`),F=T<0?-1:C.length-1-T;return F>=0||f.at(-1)?.event==="run.aborted"?F:C.length-1},k=_("assistant"),D=_("reasoning"),B=xt(C.slice(0,k+1)),R=B?c.findIndex((M)=>M.endsWith(B)):-1,x=R>=0;if(x)c.splice(R,1);let q=xt(C.slice(0,D+1),"reasoning"),H=q?l.findIndex((M)=>M.endsWith(q)):-1;if(H>=0)l.splice(H,1);for(let[M,T]of f.entries()){if(m.has(T)){b.push({...T,payload:{...T.payload,transcriptReflected:!0}});continue}if(p.has(T)&&Bo.has(T.event)&&(T.event.startsWith("reasoning.")?H>=0&&M<=D:x&&M<=k))continue;if(T.event==="session.pending_prompts"&&T!==w)continue;if(p.has(T)&&T.event.startsWith("tool.")){let F=String(T.payload?.toolCallId??"").trim();if(u.has(F)||T.event==="tool.started"&&h.has(F))continue}b.push(T)}f=[]};for(let S of s)if(f.push(S),jo.has(S.event))g(!0);return g(!1),b}function te(s){let i=structuredClone(s),o=(r)=>{if(!r||typeof r!=="object"||Object.isFrozen(r))return;for(let c of Object.values(r))o(c);Object.freeze(r)};return o(i),i}function Ke(s){let i=s?.trim();return i?me(i).slice(0,120):void 0}function cs(s){if(typeof s==="string")return s;if(Array.isArray(s)){let i=[];for(let o of s){if(typeof o==="string"){if(o.trim())i.push(o);continue}if(!o||typeof o!=="object")continue;let r=o,c=typeof r.type==="string"?r.type:"",l=c==="text"?String(r.text??""):c==="thinking"?String(r.thinking??""):c==="tool_use"?`[tool] ${String(r.name??"tool_call")}`:c==="tool_result"?`[tool_result]
25
+ ${cs(r.content)}`:c==="image"?"[image]":c==="redacted_thinking"?"[redacted_thinking]":typeof r.text==="string"?r.text:"";if(l.trim())i.push(l)}return i.join(`
26
+ `)}if(s&&typeof s==="object"){let i=s;if(typeof i.text==="string")return i.text}return""}function zo(s){let i=Ke(s??void 0);if(!i)return;return i.split(`
27
+ `)[0]?.trim().slice(0,70)||void 0}function No(s){for(let i of["user","assistant"])for(let o of s){if(!o||typeof o!=="object")continue;let r=o;if(r.role!==i)continue;let c=Ke(cs(r.content));if(!c)continue;return c.split(`
28
+ `)[0]?.trim().slice(0,70)||void 0}return}function Go(s){let i=s.metadata&&typeof s.metadata==="object"?Ke(s.metadata.title):void 0;if(i)return i.slice(0,70);let o=zo(s.prompt);if(o)return o;let r=s.messages?No(s.messages):void 0;if(r)return r;return`Session ${s.sessionId.slice(-6)}`}function Fo(s,i,o,r){let c=i.payload??{},l=()=>{let u=o.get(r);if(u===void 0||!s.messages[u]||s.messages[u]?.role!=="assistant")u=s.messages.length,s.messages.push({role:"assistant",content:[]}),o.set(r,u);let p=s.messages[u];if(!Array.isArray(p.content))p.content=[];return p.content},h=(u,p,m)=>{let y=l(),w=y.at(-1);if(w?.type===u)w[p]=`${w[p]??""}${m}`;else y.push({type:u,[p]:m})};switch(i.event){case"assistant.delta":if(typeof c.text==="string")h("text","text",c.text);return;case"reasoning.delta":if(typeof c.text==="string"&&c.text)h("thinking","thinking",c.text);else if(c.redacted===!0)l().push({type:"redacted_thinking",data:""});return;case"assistant.finished":o.delete(r);return;case"assistant.media":if(c.media)l().push({type:"media",media:structuredClone(c.media)});return;case"tool.started":{let u=String(c.toolCallId??"");if(u&&!s.messages.some((p)=>Array.isArray(p.content)&&p.content.some((m)=>m.type==="tool_use"&&m.id===u)))l().push({type:"tool_use",id:u,name:String(c.toolName??"tool"),input:structuredClone(c.input??{})});return}case"tool.finished":{let u=String(c.toolCallId??"");if(u&&!s.messages.some((p)=>Array.isArray(p.content)&&p.content.some((m)=>m.type==="tool_result"&&m.tool_use_id===u)))s.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:u,content:typeof c.output==="string"?c.output:JSON.stringify(c.output??""),is_error:Boolean(c.error)}]}),o.delete(r);return}case"usage.updated":s.usage=structuredClone(c.totals??c.delta??{});return;case"session.pending_prompts":{let u=Array.isArray(c.prompts)?c.prompts:[];s.promptsInQueue=u.map((p)=>({id:String(p.id??""),prompt:String(p.prompt??""),steer:p.delivery==="steer",attachmentCount:typeof p.attachmentCount==="number"?p.attachmentCount:0,userImages:Array.isArray(p.userImages)?p.userImages.filter((m)=>typeof m==="string"):void 0})).filter((p)=>p.id&&(p.prompt||p.attachmentCount));return}case"session.pending_prompt_submitted":{let u=c.prompt,p=String(u?.id??"");if(!p||s.lastQueuedPromptStartId===p)return;if(s.lastQueuedPromptStartId=p,s.promptsInQueue=s.promptsInQueue.filter((m)=>m.id!==p),c.transcriptReflected!==!0)s.messages.push({role:"user",content:[{type:"text",text:String(u?.prompt??"")}]});s.busy=!0,s.status="running",s.endedAt=void 0,o.delete(r);return}case"run.started":case"session.attached":case"session.updated":{if(typeof i.sequence==="number"&&s.lastHubStatusSequence!==void 0&&i.sequence<s.lastHubStatusSequence)return;if(typeof i.sequence==="number")s.lastHubStatusSequence=i.sequence;let u=c.session,p=typeof u?.status==="string"?u.status:i.event==="run.started"?"running":s.status,m=p==="pending"?"running":p;if(i.event==="session.updated"&&m==="running"&&s.endedAt!==void 0&&!s.busy)return;let y=s.busy;if(s.status=m,s.busy=m==="running",i.event==="run.started"){if(!y)o.delete(r);s.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof i.sequence==="number"&&s.lastHubStatusSequence!==void 0&&i.sequence<s.lastHubStatusSequence)return;if(typeof i.sequence==="number")s.lastHubStatusSequence=i.sequence;s.status=typeof c.reason==="string"?c.reason:i.event==="run.failed"?"error":i.event==="run.aborted"?"aborted":"completed",s.busy=!1,s.endedAt=Date.now(),o.delete(r);return}}}function ke(s){return s instanceof Error&&s.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String(s.code))}function Ae(s,i){return s instanceof Error&&s.name==="HubCommandError"&&s.code==="hub_command_timeout"&&(!i||s.command===i)}var E="/workspace",Vo=30000,Wo=2000,Ko=2000,ls="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 Jo(s,i={}){let o=`cline/${(s.metadata.taskId?.trim()||s.id).slice(-8).toLowerCase()}`,r=s.sandboxType==="resumable"||s.metadata.sandboxType==="resumable";return`${ls}
29
+
30
+ Do all work for this task on the branch \`${o}\`: create it from the current checkout before your first change (or check it out if it already exists), and never commit directly to the default branch. `+(r?"Commit and push only when the user asks. ":`SAVE YOUR WORK: This sandbox is temporary. Push your progress to origin so it remains available outside the sandbox. The branch \`${o}\` 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 ${o}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks."+(i.computerUse?`
31
+
32
+ ${rs}`:"")}function _e(s){if(!s)return E;if(ie.isAbsolute(s)||s.includes("\\")||s.split("/").some((o)=>!o||o==="."||o===".."))throw new I("request_failed","The handoff workspace path must stay inside the repository.");let i=ie.join(E,s);if(!i.startsWith(`${E}/`))throw new I("request_failed","The handoff workspace path must stay inside the repository.");return i}function Je(s){let i=s.metadata.cwd;return typeof i==="string"&&ie.normalize(i)===i&&(i===E||i.startsWith(`${E}/`))?i:E}function Rt(s){let i=s?.metadata&&typeof s.metadata==="object"?s.metadata:void 0,o=i?.handoff&&typeof i.handoff==="object"?i.handoff:void 0;return String(o?.sourceSessionId??"").trim()}class He extends Error{constructor(s){super(s instanceof Error?s.message:"Cloud conversation creation was not dispatched.",{cause:s});this.name="CloudHandoffSeedRejectedError"}}class De extends I{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 us 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 L(s){let i=s.expiredAt?Date.parse(s.expiredAt):Number.NaN;return Number.isFinite(i)&&i<=Date.now()}function Qo(s){return s.trim().startsWith("ses-")}function Yo(s,i){let o=new URL(`/api/v1/session/${encodeURIComponent(i)}`,s);return o.protocol=o.protocol==="https:"?"wss:":"ws:",o.toString()}function Te(s){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:s.metadata.modelId??"",modelId:s.metadata.modelId??"",repoUrl:s.repoContext.repoUrl??"",branch:s.repoContext.branch??"",cwd:Je(s),workspaceRoot:E},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse(s.createdAt)||Date.now(),endedAt:L(s)&&s.expiredAt?Date.parse(s.expiredAt):void 0,status:s.status,attachedViaHub:!0}}function Ee(s,i,o){return{sessionId:s.id,origin:"cloud",executionTarget:"cloud",status:i,provider:"cline",model:s.metadata.modelId??"",repoUrl:s.repoContext.repoUrl??"",branch:s.repoContext.branch??"",cwd:Je(s),workspaceRoot:E,...o?.trim()?{prompt:o.trim()}:{},metadata:{origin:"cloud",repoUrl:s.repoContext.repoUrl??"",git:{url:s.repoContext.repoUrl??"",branch:s.repoContext.branch??""}}}}function $t(s){return{sessionId:s.id,origin:"cloud",executionTarget:"cloud",status:s.status,provider:"cline",model:s.metadata.modelId??"",cwd:Je(s),workspaceRoot:E,repoUrl:s.repoContext.repoUrl??"",branch:s.repoContext.branch??"",startedAt:s.createdAt,...s.lastActivityAt?{lastActivityAt:s.lastActivityAt}:{},endedAt:L(s)?s.expiredAt??void 0:s.status==="failed"?s.lastActivityAt??s.createdAt:void 0,updatedAt:s.updatedAt,...s.title?.trim()?{title:s.title.trim()}:{},metadata:{...s.title?.trim()?{title:s.title.trim()}:{},origin:"cloud",...s.metadata.provisioningPhase?{provisioningPhase:s.metadata.provisioningPhase}:{},repoUrl:s.repoContext.repoUrl??"",git:{url:s.repoContext.repoUrl??"",branch:s.repoContext.branch??""}}}}function Zo(s){if(typeof s!=="string")return s;try{return JSON.parse(s)}catch{return s}}function en(s,i){let o=[...s??[]],r=new Set(o.map((c)=>c.id));for(let c of i)if(!r.has(c.id))o.push(c);return o}class tn{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(s){this.options=s,this.pendingInitialTasks=s.pendingInitialTasks??new Map,this.createHubClient=s.createHubClient??((i)=>new ue(i))}restoreCreationOptions(s,i){if(this.restoredOptions.set(s,structuredClone(i)),this.pendingInitialTasks.has(s))this.pendingInitialTasks.set(s,{...this.pendingInitialTasks.get(s),...structuredClone(i)});let o=this.sessions.get(s);if(o)Object.assign(o.config,structuredClone(i))}seedSessionState(s,i){if(!this.sessions.has(s))this.sessions.set(s,structuredClone(i))}stateFromRecord(s){let i=Te(s);return Object.assign(i.config,this.pendingInitialTasks.get(s.id),this.restoredOptions.get(s.id)),i}getSnapshot(s){let i=this.knownSessions.get(s),o=this.sessions.get(s)??(i?this.stateFromRecord(i):void 0);if(!o)return;let r=this.connections.get(s);return te({...o,sessionId:s,record:i,approvals:Array.from(this.approvals.values()).filter((c)=>c.item.sessionId===s).map((c)=>c.item),connectionState:this.detachedSessions.has(s)||this.disposed?"detached":r?.reconnectResolution||r?.rehydrationPromise?"reconnecting":r?r.connected?"connected":r.reconnecting?"reconnecting":"connecting":this.connectionPromises.has(s)?"connecting":"detached",transcriptKnown:r?.transcriptKnown??Boolean(i&&L(i))})}subscribe(s,i){let o=(r)=>{if(!i||r.sessionId===i)s(r)};return this.listeners.add(o),()=>{this.listeners.delete(o)}}publish(s){let i=s.type==="snapshot"?Object.freeze(s):te(s);for(let o of this.listeners)try{o(i)}catch(r){this.options.logger?.error?.("Cloud session subscriber failed",{error:r})}}publishSnapshot(s,i=!1,o){this.cancelScheduledSnapshot(s);let r=this.getSnapshot(s);if(r)this.publish({type:"snapshot",sessionId:s,snapshot:r,replace:i,cause:o});else this.publish({type:"removed",sessionId:s})}snapshotTimers=new Map;cancelScheduledSnapshot(s){clearTimeout(this.snapshotTimers.get(s)),this.snapshotTimers.delete(s)}scheduleSnapshot(s){if(this.disposed||this.detachedSessions.has(s)||this.snapshotTimers.has(s))return;let i=setTimeout(()=>this.publishSnapshot(s),100);i.unref?.(),this.snapshotTimers.set(s,i)}notify(s,i){let o=String(i.sessionId??"");if(s==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:o,message:String(i.message??"Cloud synchronization failed")});else this.publishSnapshot(o,s==="cloud_session_rehydrated",s==="chat_session_status"?"status":s==="chat_session_ended"?"ended":s==="tool_approval_state"?"approvals":void 0)}applyLiveEvent(s,i){let o=this.sessions.get(s);if(o)Fo(o,i,this.streamingMessages,s)}async respondApproval(s,i,o){this.assertSessionActive(s);let r=this.approvals.get(`${s}:${i}`);if(!r){if(!this.connections.has(s))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new I("request_failed","This approval was already resolved or is no longer available.")}await r.resolve(o)}async detach(s){this.detachedSessions.add(s),this.sessionGenerations.set(s,(this.sessionGenerations.get(s)??0)+1),this.connectionPromises.delete(s),this.sendAbortTokens.set(s,Symbol()),this.abortProvisioningControllers(s,Error("Cloud viewer detached")),await this.disposeConnection(s),this.publishSnapshot(s)}isCloudSession(s){return Qo(s)||this.knownSessions.has(s)||this.connections.has(s)||this.sessions.get(s)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord(s){let i=this.knownSessions.get(s);return i?$t(i):void 0}async getCrossScopeDiscoveryRecord(s){let i=this.getCachedDiscoveryRecord(s);if(!i)return;try{let o=(await this.options.api.status(s)).status?.trim();return o?{...i,status:o}:i}catch(o){if(o instanceof I&&(o.code==="session_not_found"||o.code==="session_expired")){this.knownSessions.delete(s),this.unlistedSessions.delete(s),this.pendingInitialTasks.delete(s);return}return i}}async list(){return await this.listInOrganization(await this.resolveActiveOrganizationId())}async listInOrganization(s){if(this.disposed)throw Error("Cloud session controller was disposed");let i=(h)=>this.sessions.get(h)?.title??this.knownSessions.get(h)?.title,o=new Map([...this.knownSessions.keys(),...this.sessions.keys()].map((h)=>[h,i(h)])),r=(h)=>{let u=i(h.id);if(this.titleWrites.has(h.id)||u!==o.get(h.id))h.title=u??h.title},c=(await this.options.api.list(s)).map((h)=>this.preserveConnectedRuntimeModel(h));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedOrganizationId=s,this.lastListedSessions=c;for(let h of c)r(h),this.knownSessions.set(h.id,h),this.unlistedSessions.delete(h.id);await Promise.all(Array.from(this.unlistedSessions.entries()).filter(([,h])=>h.organizationId===s).map(([h])=>this.getCrossScopeDiscoveryRecord(h)));let l=await Promise.all(c.map(async(h)=>{if(h.status!=="provisioning")return h;let u=await this.options.api.status(h.id).catch(()=>{return}),p=u?.status?.trim();if(!p)return h;return{...h,status:p,metadata:{...h.metadata,...Dt(u?.phase)?{provisioningPhase:u?.phase}:{},...u?.statusReason?.trim()?{statusReason:u.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let h of l){r(h),this.knownSessions.set(h.id,h);let u=this.sessions.get(h.id);if(u)u.title=h.title;if(u?.status==="provisioning"&&h.status!=="provisioning")u.status=h.status;let p=this.connections.get(h.id);if(p)p.remote=h;let m=L(h);if(m||h.status==="failed"||h.status==="suspended"){if(u)u.busy=!1,u.status=m?"expired":h.status,u.endedAt=m?Date.parse(h.expiredAt??"")||Date.now():Math.max(u.endedAt??0,Date.parse(h.lastActivityAt??h.createdAt)||0)||void 0;if(p)this.disposeConnection(h.id).catch(()=>{return})}}this.lastListedOrganizationId=s,this.lastListedSessions=l;for(let h of l)if(this.sessions.has(h.id))this.publishSnapshot(h.id);return te(l)}async handoffTargetExists(s){try{return await this.options.api.status(s),!0}catch(i){if(i instanceof I&&(i.code==="session_not_found"||i.code==="session_expired"))return!1;throw i}}preserveConnectedRuntimeModel(s){let i=this.connections.get(s.id)?.remote.metadata,o=i?.cwd??this.knownSessions.get(s.id)?.metadata.cwd;return{...s,metadata:{...s.metadata,...i?.modelId?{modelId:i.modelId}:{},...o?{cwd:o}:{}}}}async refreshOrganization(){await this.resolveActiveOrganizationId({fresh:!0})}async resolveActiveOrganizationId(s){return await this.options.getActiveOrganizationId?.(s)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listModels(){if(this.disposed)throw Error("Cloud session manager was disposed");let s=await this.resolveActiveOrganizationId({fresh:!0}),i=await Ro(this.options.apiBaseUrl,{isOrganizationSession:Boolean(s)});if(this.disposed)throw Error("Cloud session manager was disposed");return i}async prepareHandoffRepository(s){let i=await this.resolveActiveOrganizationId(),o=await this.options.api.listRepositories(i);if(!o.connected)throw new I("github_not_connected","Connect GitHub before handing this session off to cloud.",o.connectUrl);let r=(c)=>c.trim().replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();if(!o.repositories.some((c)=>r(c.url)===r(s)))throw new I("github_not_connected",`The GitHub integration cannot access ${s}. Grant repository access before handing off.`,o.connectUrl);return i?{organizationId:i}:{}}async listBranches(s,i={}){return await this.options.api.listBranches(s,await this.resolveActiveOrganizationId(),i)}async listForDiscovery(s={}){let i,o=(async()=>{let u=await this.resolveActiveOrganizationId();i={organizationId:u};let p=this.discoveryRefresh?.organizationId===u?this.discoveryRefresh?.promise:void 0;if(!p){let m=this.listInOrganization(u).finally(()=>{if(this.discoveryRefresh?.promise===m)this.discoveryRefresh=void 0});this.discoveryRefresh={organizationId:u,promise:m},p=m}return{organizationId:u,records:await p}})(),r=()=>i?{organizationId:i.organizationId,records:this.lastListedOrganizationId===i.organizationId?this.lastListedSessions:[]}:void 0,c;if(s.timeoutMs===void 0)c=await o;else{let u;try{c=await Promise.race([o.catch((p)=>{if(!(p instanceof I&&p.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:p});return r()}),new Promise((p)=>{u=setTimeout(()=>p(r()),Math.max(0,s.timeoutMs??0))})])}finally{if(u!==void 0)clearTimeout(u)}}if(!c)return[];let{organizationId:l,records:h}=c;return[...new Map([...Array.from(this.unlistedSessions.values()).filter((u)=>u.organizationId===l).map((u)=>u.record),...h].map((u)=>[u.id,u])).values()].map((u)=>{let p=$t(u),m=this.sessions.get(u.id);if(!m)return p;let y=m.title?.trim()||u.title?.trim();return{...p,status:m.status,prompt:m.prompt,endedAt:m.endedAt!==void 0?new Date(m.endedAt).toISOString():p.endedAt,metadata:{...p.metadata??{},title:Go({sessionId:u.id,metadata:y?{title:y}:void 0,prompt:m.prompt,messages:m.messages})}}})}async create(s){let i=s.requestId?.trim();if(!i)return this.createSession(s);let o=this.createRequests.get(i);if(o)return o;let r=this.createSession(s).finally(()=>{if(this.createRequests.get(i)===r)this.createRequests.delete(i)});return this.createRequests.set(i,r),r}async createSession(s){let{initialMessage:i,...o}=s;if(!i)return this.createOnce(o);let r=!1,c,l={lifecycle:{beforeDispatch:()=>{r=!0}},settled:new Promise((p)=>{c=p})},h,u;try{h=await this.createOnce({...o,initialPrompt:i.text},(m)=>{if(u=m,!this.initialSends.has(m))this.initialSends.set(m,l)});let p=await this.send(h.sessionId,i.text,"queue",s.modelId,i.images,l.lifecycle);return c(),{...h,initialSend:p}}catch(p){let m={dispatched:r,message:p instanceof Error?p.message:String(p),...p instanceof Error&&"detail"in p&&typeof p.detail==="string"?{detail:p.detail}:{}};if(c(m),!h)throw p;return{...h,initialSend:m}}finally{if(u&&this.initialSends.get(u)===l)this.initialSends.delete(u)}}trackProvisioningController(s,i){let o=this.provisioningControllers.get(s);if(!o)o=new Set,this.provisioningControllers.set(s,o);return o.add(i),()=>{if(o.delete(i),o.size===0)this.provisioningControllers.delete(s)}}abortProvisioningControllers(s,i){let o=this.provisioningControllers.get(s);if(!o?.size)return!1;for(let r of o)r.abort(i);return!0}async waitUntilReady(s){this.detachedSessions.delete(s),this.assertSessionActive(s);let i=new AbortController,o=this.trackProvisioningController(s,i);try{await this.options.api.waitUntilReady(s,AbortSignal.any([i.signal,AbortSignal.timeout(610000)])),i.signal.throwIfAborted(),this.assertSessionActive(s),await this.refreshKnownSession(s)}finally{o()}}async seedHandoff(s,i){_e(i.workspaceRelativePath),this.detachedSessions.delete(s);let o=await this.ensureConnection(s,{createInner:!0,handoffSeed:i});if(!o.innerSessionId)throw Error("Cloud Hub did not return an inner session id");return{innerSessionId:o.innerSessionId}}async verifyHandoffTranscript(s,i,o={}){let r=await this.ensureConnection(s),c=r.innerSessionId;if(!c)throw Error("Cloud Hub did not return an inner session id");let l=await r.client.command("session.messages",{sessionId:c},c);this.assertSessionActive(s,r);let h=l.payload?.messages;if(!Array.isArray(h))throw Error("Cloud runtime returned no transcript after seeding.");if(i.length>0&&h.length===0)throw new us;if(!(o.allowAppendedMessages?h.length>=i.length&&it(i,h.slice(0,i.length)):it(i,h)))throw new Ut(i.length,h.length);r.transcriptKnown=!0;let u=this.sessions.get(s);if(u)u.messages=structuredClone(h),this.authoritativeMessages.set(s,structuredClone(h)),this.streamingMessages.delete(s),this.publishSnapshot(s,!0)}async createOnce(s,i){if(this.disposed)throw Error("Cloud session manager was disposed");let o=_e(s.workspaceRelativePath),r=s.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):s.organizationId??void 0,c=s.handoff,l=!c,h=await this.options.api.create({...s,organizationId:r,...c&&{handoff:{...c,onOuterSessionCreated:async(S,C)=>{l=C?.created===!0,await c.onOuterSessionCreated(S,C)}}}});if(!h?.sessionId?.trim())throw new I("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(l&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(h.sessionId,h.cleanupAuthToken,s.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let u={id:h.sessionId,sandboxType:s.sandboxType,status:h.status,sandboxUrl:h.sandboxUrl,repoContext:{repoUrl:s.repoUrl,...s.branch?.trim()?{branch:s.branch.trim()}:{}},metadata:{modelId:s.modelId,cwd:o},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};i?.(u.id),this.knownSessions.set(u.id,u),this.unlistedSessions.set(u.id,{record:u,organizationId:r});let{autoApproveTools:p,thinking:m,reasoningEffort:y,mode:w,workspaceRelativePath:b}=s;this.pendingInitialTasks.set(u.id,{autoApproveTools:p,thinking:m,reasoningEffort:y,mode:w??"act",workspaceRelativePath:b});let f=this.stateFromRecord(u);f.prompt=s.initialPrompt?.trim()||void 0,f.config.mode=s.mode??"act",this.sessions.set(u.id,f);let g;try{if(s.handoff){let S=await s.handoff.resolveMessages();this.assertSessionActive(u.id),g=(await this.seedHandoff(u.id,{sourceSessionId:s.handoff.sourceSessionId,messages:S,mode:s.mode,workspaceRelativePath:s.workspaceRelativePath,config:{autoApproveTools:s.autoApproveTools,thinking:s.thinking,reasoningEffort:s.reasoningEffort},onSeeding:s.handoff.onSeeding})).innerSessionId}}catch(S){if(this.disposed&&l&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(u.id,h.cleanupAuthToken,s.handoff?.onOuterSessionRemoved);throw S}return this.assertSessionActive(u.id),this.notify("chat_session_status",{sessionId:u.id,status:f.status}),{sessionId:u.id,origin:"cloud",executionTarget:"cloud",status:u.status,provider:"cline",model:s.modelId,repoUrl:s.repoUrl,branch:s.branch??"",cwd:o,workspaceRoot:E,...g?{innerSessionId:g}:{},...f.prompt?{prompt:f.prompt}:{}}}async deleteProvisionedSessionAfterDispose(s,i,o){this.knownSessions.delete(s),this.unlistedSessions.delete(s),this.pendingInitialTasks.delete(s),this.sessions.delete(s),await this.options.api.delete(s,i).then(()=>o?.(s)).catch((r)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:s,error:r})})}async attach(s,i){let o=this.sessionGenerations.get(s)??0;if(this.detachedSessions.delete(s),i)this.restoreCreationOptions(s,i);let r=await this.ensureKnownSession(s);if(this.assertSessionActive(s),o!==(this.sessionGenerations.get(s)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has(s))this.sessions.set(s,this.stateFromRecord(r));if(r.status==="provisioning"||r.status==="failed")return Ee(r,r.status,this.sessions.get(s)?.prompt);if(L(r))return await this.disposeConnection(s),await this.attachExpired(r);let c;try{c=await this.ensureConnection(s)}catch(u){let p=await this.refreshKnownSession(s);if(p&&L(p))return await this.disposeConnection(s),await this.attachExpired(p);throw u}await this.ensureAttached(c);let l=c.remote,h=this.sessions.get(s);return Ee(l,h?.status??l.status,h?.prompt)}async send(s,i,o,r,c,l){let h=this.sendAbortTokens.get(s),u=this.initialSends.get(s);if(u&&l!==u.lifecycle){if(await u.settled)throw new I("request_failed","The initial cloud prompt was not confirmed. Check the cloud task before sending another message.")}let p=this.knownSessions.get(s);if(p&&L(p))throw new I("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let m=await this.ensureConnection(s,{createInner:!0}),y=()=>this.disposed||m.disposed||this.deletingSessions.has(s)||this.sendAbortTokens.get(s)!==h,w=()=>{if(y())throw Error("Cloud session prompt cancelled")};if(w(),await m.reconnectResolution,w(),await this.ensureAttached(m),await m.reconnectResolution,w(),!m.transcriptKnown)await this.rehydrateAfterTransportDrop(s,m);w(),await this.updateModel(m,r),await m.reconnectResolution,w();let b=m.innerSessionId;if(!b)throw Error("Cloud Hub session was not initialized");let f=this.sessions.get(s),g=o??(f?.busy?"queue":void 0),S=ae(f?.messages??[],f?.promptsInQueue??[],i),C=g!=="queue"&&g!=="steer",_=f&&g!=="queue"?{role:"user",content:[{type:"text",text:i}]}:void 0;if(f&&_)f.messages=[...f.messages,_];let k=()=>{if(f&&_)f.messages=f.messages.filter((x)=>x!==_),this.publishSnapshot(s)};if(f&&C){let x=f.status!=="running";if(f.busy=!0,f.status="running",x)this.publishSnapshot(s,!1,"status")}let D=new Set,B=!1,R=()=>{if(B||y())return;B=!0,this.publish({type:"prompt_accepted",sessionId:s,prompt:i,delivery:g})};try{let x=await m.client.command("session.send_input",{prompt:i,delivery:g,...c?.length?{attachments:{userImages:c}}:{}},b,{timeoutMs:g==="queue"?Vo:null,onDispatch:(H)=>{D.add(H),m.pendingInputs??=new Map,m.pendingInputs.set(H,{clientId:m.client.getClientId(),ownsBusyState:C,accept:R})},beforeDispatch:()=>{if(w(),m.innerSessionId!==b)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.");if(l?.beforeDispatch?.(),f&&C)f.prompt||=i;let H=this.knownSessions.get(s);if(H&&!H.title?.trim()&&!this.titleWrites.has(s)){let M=Ns(i);if(M){if(H.title=M,f)f.title=M;let T=this.options.api.updateTitle?.(s,M).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get(s)===T)this.titleWrites.delete(s)});if(T)this.titleWrites.set(s,T)}}}});R();let q=g==="queue"||g!=="steer"&&x.payload?.result===void 0;if(q)k();return{sessionId:s,ok:!0,...q?{queued:!0}:{},result:x.payload?.result}}catch(x){if(y())throw k(),x;if(ke(x)||Ae(x,"session.send_input")){let q;try{q=await this.rehydrateAfterTransportDrop(s,m)}catch(H){if(w(),k(),f&&C)f.busy=!1,f.status="error";if(g==="queue")throw new De;throw H}if(w(),g==="queue")throw new De;if(g==="steer")throw new I("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(ae(q.messages,en(q.prompts,q.submittedPrompts),i)<=S)throw new I("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:s,ok:!0,...g==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:q.status}}if(k(),f&&C)f.busy=!1,f.status="error";throw this.publishSnapshot(s),x}finally{for(let x of D)m.pendingInputs?.delete(x)}}async updateModel(s,i){let o=i?.trim();if(!o||s.remote.metadata.modelId===o)return;let r=s.innerSessionId;if(!r)throw Error("Cloud Hub session was not initialized");await s.client.command("session.update_connection",{sessionId:r,updates:{modelId:o}},r,{beforeDispatch:()=>{if(this.assertSessionActive(s.remote.id,s),s.innerSessionId!==r)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive(s.remote.id,s),this.applyModel(s,o)}applyModel(s,i){s.remote.metadata.modelId=i;let o=this.sessions.get(s.remote.id);if(o)o.config.model=i,o.config.modelId=i}async rehydrateAfterTransportDrop(s,i){if(this.assertSessionActive(s,i),i.rehydrationPromise)return i.rehydrationRerunRequested=!0,await i.rehydrationPromise;let o=(async()=>{let r;do i.rehydrationRerunRequested=!1,r=await this.performTransportRehydration(s,i),this.assertSessionActive(s,i);while(i.rehydrationRerunRequested&&!this.disposed);return r})().finally(()=>{if(i.rehydrationPromise===o)i.rehydrationPromise=void 0,this.publishSnapshot(s)});return i.rehydrationPromise=o,await o}async performTransportRehydration(s,i){this.assertSessionActive(s,i);let o=i.innerSessionId;if(!o)throw Error("Cloud Hub session was not initialized");i.bufferingEvents=!0,i.bufferedEvents=[],i.bufferedEventsDropped=0;try{await this.ensureAttached(i),this.assertSessionActive(s,i);let r=await i.client.command("session.get",{includeSnapshot:!0},o);this.assertSessionActive(s,i);let c=r.payload?.session&&typeof r.payload.session==="object"&&!Array.isArray(r.payload.session)?r.payload.session:void 0;this.applySessionModel(i,c);let l=this.sessions.get(s),h=this.authoritativeMessages.get(s)??[],u=String(c?.status??l?.status??"running").trim(),p=u==="pending"?"running":u;if(p==="running"&&!i.transcriptKnown&&!i.pendingInputs?.size)i.externalRun??={progressHydrated:!0};let m=()=>i.client.command("session.messages",{sessionId:o},o),y=await m().catch((R)=>{if(!Ae(R,"session.messages"))throw R;return this.assertSessionActive(s,i),m()});if(this.assertSessionActive(s,i),!Array.isArray(y.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let w=y.payload.messages,b=i.bufferedEventsDropped+i.bufferedEvents.length,f=await i.client.command("session.pending_prompts",{sessionId:o},o).catch(()=>{return});this.assertSessionActive(s,i);let g=i.bufferedEventsDropped+i.bufferedEvents.length;if(l){let R=l.status!==p;if(this.authoritativeMessages.set(s,structuredClone(w)),l.messages=structuredClone(w),this.streamingMessages.delete(s),l.status=p,l.busy=p==="running",R)if(p==="completed"||p==="failed"||p==="aborted")l.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:s,reason:p==="failed"?"error":p});else this.notify("chat_session_status",{sessionId:s,status:p})}let S=f!==void 0&&f.ok!==!1&&Array.isArray(f.payload?.prompts),C=S?this.applyQueueSnapshot(s,f):void 0;i.transcriptKnown=!0;let _=w;this.assertSessionActive(s,i),this.notify("cloud_session_rehydrated",{sessionId:s,status:p,transcriptKnown:!0,messages:_}),this.assertSessionActive(s,i);let k=i.bufferedEvents,D=ds(k),B=Lo(k,w,{queueSnapshotApplied:S,queueSnapshotEventCutoff:Math.max(0,g-i.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,b-i.bufferedEventsDropped),baselineMessages:h});i.bufferedEvents=[],i.bufferingEvents=!1,i.syncFailureNotified=!1;for(let R of B)this.forwardEvent(s,i,R);return{status:p,messages:w,prompts:C,submittedPrompts:D}}catch(r){let c=i.bufferedEvents;i.bufferedEvents=[],i.bufferingEvents=!1,this.assertSessionActive(s,i);for(let l of c)this.forwardEvent(s,i,l);if(!i.syncFailureNotified)i.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:s,message:r instanceof Error?r.message:String(r)});throw r}}async abort(s){if(this.sendAbortTokens.set(s,Symbol()),this.abortProvisioningControllers(s,Error("Cloud session prompt cancelled")))return{sessionId:s,ok:!0};let i=await this.ensureConnection(s),o=()=>{if(this.disposed||i.disposed)throw Error("Cloud session connection was disposed")};if(o(),await i.client.connect(),await i.reconnectResolution,o(),await this.resolveInnerSession(s,i),i.innerSessionId){await this.ensureAttached(i),await i.reconnectResolution,o();let c=i.innerSessionId;if(!c)throw Error("Cloud Hub session was not initialized");await i.client.command("run.abort",{sessionId:c},c,{beforeDispatch:()=>{if(o(),i.innerSessionId!==c)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}o();let r=this.sessions.get(s);if(r)r.busy=!1,r.status="aborted";return this.publishSnapshot(s),{sessionId:s,ok:!0}}async pendingPrompts(s){if(this.knownSessions.get(s)?.status==="provisioning")return{sessionId:s,promptsInQueue:[]};if(!(await this.ensureConnection(s)).innerSessionId)return{sessionId:s,promptsInQueue:[]};let i=await this.queueCommand(s,"session.pending_prompts",{});return{sessionId:s,promptsInQueue:this.applyQueueSnapshot(s,i)}}async updatePendingPrompt(s,i,o){let r=await this.queueCommand(s,"session.update_pending_prompt",{promptId:i,...o});return{sessionId:s,updated:r.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot(s,r)}}async removePendingPrompt(s,i){let o=await this.queueCommand(s,"session.remove_pending_prompt",{promptId:i});return{sessionId:s,removed:o.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot(s,o)}}async queueCommand(s,i,o){let r=await this.ensureConnection(s),c=r.innerSessionId;if(!c)throw Error("Cloud Hub session was not initialized");await r.client.connect(),await r.reconnectResolution,await this.ensureAttached(r),await r.reconnectResolution;let l=await r.client.command(i,{sessionId:c,...o},c,{beforeDispatch:()=>{if(this.assertSessionActive(s,r),r.innerSessionId!==c)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive(s,r),l}applyQueueSnapshot(s,i){if(!Array.isArray(i.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let o=i.payload.prompts.map((c)=>({id:typeof c.id==="string"?c.id:"",prompt:typeof c.prompt==="string"?c.prompt:"",steer:c.delivery==="steer",attachmentCount:typeof c.attachmentCount==="number"?c.attachmentCount:0,userImages:Array.isArray(c.userImages)?c.userImages.filter((l)=>typeof l==="string"):void 0})).filter((c)=>c.id),r=this.sessions.get(s);if(r)r.promptsInQueue=o;return this.publishSnapshot(s,!1,"queue"),o}async readMessages(s){let i=this.knownSessions.get(s);if(i?.status==="provisioning"||i?.status==="failed")return[];if(i&&L(i))return await this.loadArchivedMessages(i)??[];try{let o=await this.ensureConnection(s);if(!o.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop(s,o)).messages}catch(o){let r=await this.refreshKnownSession(s)??i;if(r){let c=await this.loadArchivedMessages(r).catch(()=>null);if(c!==null)return c}throw o}}async updateTitle(s,i){let o=this.titleWrites.get(s),r=(async()=>{await o?.catch(()=>{}),this.assertSessionActive(s),await this.options.api.updateTitle(s,i);let c=this.knownSessions.get(s);if(c)c.title=i;let l=this.sessions.get(s);if(l)l.title=i;this.publishSnapshot(s)})();this.titleWrites.set(s,r);try{await r}finally{if(this.titleWrites.get(s)===r)this.titleWrites.delete(s)}}async delete(s){this.deletingSessions.add(s),this.abortProvisioningControllers(s);try{let i=this.connectionPromises.get(s);if(i)await i.catch(()=>{return});await this.disposeConnection(s);try{await this.options.api.delete(s)}catch(o){let r=o instanceof I?o.code:"";if(r!=="session_not_found"&&r!=="session_expired")throw o}this.knownSessions.delete(s),this.unlistedSessions.delete(s),this.pendingInitialTasks.delete(s),this.sessions.delete(s),this.authoritativeMessages.delete(s),this.restoredOptions.delete(s),this.publish({type:"removed",sessionId:s}),this.sendAbortTokens.delete(s);for(let[o,r]of this.approvals)if(r.item.sessionId===s)this.approvals.delete(o)}finally{this.deletingSessions.delete(s)}}async dispose(){this.disposed=!0;for(let i of this.snapshotTimers.keys())this.cancelScheduledSnapshot(i);this.sendAbortTokens.clear();for(let i of this.provisioningControllers.values())for(let o of i)o.abort();this.provisioningControllers.clear();let s=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[i,o]of this.approvals)if(s.has(o.item.sessionId))this.approvals.delete(i);for(let i of s)this.sessions.delete(i),this.knownSessions.delete(i),this.publish({type:"removed",sessionId:i});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((i)=>this.disposeConnection(i)))}async attachExpired(s){let i=this.sessions.get(s.id)??Te(s);return i.busy=!1,i.status="expired",this.sessions.set(s.id,i),await this.loadArchivedMessages(s).catch(()=>{return}),Ee(s,"expired")}async loadArchivedMessages(s){let i=this.sessionGenerations.get(s.id),o=await this.options.api.history(s.id);if(this.assertSessionActive(s.id),this.sessionGenerations.get(s.id)!==i)throw Error("Cloud session attachment changed while loading history");if(o===null)return null;let r=this.sessions.get(s.id)??Te(s);return r.messages=structuredClone(o),this.sessions.set(s.id,r),this.authoritativeMessages.set(s.id,structuredClone(r.messages)),this.publishSnapshot(s.id,!0),o}async refreshKnownSession(s){let i=await this.resolveActiveOrganizationId(),o=await this.options.api.list(i).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!o)return this.knownSessions.get(s);for(let r of o)this.knownSessions.set(r.id,r);return o.find((r)=>r.id===s)}async ensureKnownSession(s){let i=this.knownSessions.get(s);if(i)return i;let o=(await this.list()).find((r)=>r.id===s);if(!o)throw new I("session_not_found",`Cloud session ${s} was not found.`);return this.knownSessions.get(s)??structuredClone(o)}assertSessionActive(s,i){if(this.disposed||i?.disposed||this.detachedSessions.has(s)||i?.generation!==void 0&&i.generation!==(this.sessionGenerations.get(s)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has(s))throw new I("session_not_found","This cloud session is being deleted.")}async ensureConnection(s,i={}){let o=this.sessionGenerations.get(s)??0,r=()=>{if(this.assertSessionActive(s),o!==(this.sessionGenerations.get(s)??0))throw Error("Cloud viewer detached during connection")};r();let c=this.connectionPromises.get(s),l=c?await c:this.connections.get(s);if(l?.remote.status==="suspended")return await this.disposeConnection(s),r(),await this.ensureConnection(s,i);if(l){if(this.assertSessionActive(s,l),await l.reconnectResolution,this.assertSessionActive(s,l),!l.innerSessionId)await l.client.connect(),await l.reconnectResolution,this.assertSessionActive(s,l),await this.resolveInnerSession(s,l,Boolean(i.handoffSeed)),this.assertSessionActive(s,l);if(i.handoffSeed&&l.innerSessionId)await this.assertHandoffConnectionReusable(l,i.handoffSeed);if(i.createInner&&!l.innerSessionId)await this.createInnerSession(l,i.handoffSeed);return this.assertSessionActive(s,l),l}let h=(async()=>{let u=await this.ensureKnownSession(s);if(r(),!this.pendingInitialTasks.has(s)&&(u.sandboxType==="resumable"||u.metadata.sandboxType==="resumable"||u.status==="suspended")){let w=await this.options.api.status(s).catch(async(f)=>{if(!(f instanceof I?f.code==="request_failed"&&(f.status===void 0||f.status===408||f.status===429||f.status>=500):f instanceof TypeError||f instanceof Error&&f.name==="TimeoutError"))throw f;return r(),await this.refreshKnownSession(s).catch(()=>{return})});if(r(),w?.status)u.status=w.status;let b=this.sessions.get(s);if(b?.status==="suspended"&&["provisioning","ready","active"].includes(u.status))b.status=u.status,b.busy=!1,b.endedAt=void 0}if(u.status==="suspended"){let w=new AbortController,b=this.trackProvisioningController(s,w);try{try{u=await this.options.api.resume(s,w.signal)}catch(g){if(!(g instanceof I)||g.status!==409)throw g;r(),w.signal.throwIfAborted();let S=await this.options.api.status(s,{signal:w.signal});if(S.status!=="provisioning"&&S.status!=="ready"&&S.status!=="active")throw g;u={...u,status:S.status}}r(),w.signal.throwIfAborted(),this.knownSessions.set(s,u);let f=this.sessions.get(s);if(f)f.status=u.status,f.busy=!1,f.endedAt=void 0;this.publishSnapshot(s,!1,"status")}finally{b()}}if(u.status==="provisioning"){let w=new AbortController,b=this.trackProvisioningController(s,w);try{if(await this.options.api.waitUntilReady(s,w.signal,({phase:g})=>{u.metadata.provisioningPhase=g,this.notify("chat_session_status",{sessionId:s,status:"provisioning",phase:g})}),this.disposed)throw Error("Cloud session manager was disposed");if(u=await this.refreshKnownSession(s)??u,w.signal.throwIfAborted(),u.status==="provisioning")u.status="ready";let f=this.sessions.get(s);if(f?.status==="provisioning")f.status="idle",f.busy=!1,f.endedAt=void 0}catch(f){if(f instanceof I&&f.code==="session_failed"){if(u.status="failed",u.metadata.statusReason=f.detail,u.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set(s,u);let g=this.sessions.get(s);if(g)g.status="error";this.notify("chat_session_status",{sessionId:s,status:"error"})}throw f}finally{b()}}if(r(),u.status==="failed")throw new I("session_failed",u.metadata.statusReason||"The cloud sandbox could not be prepared.");if(L(u))throw new I("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set(s,this.sessions.get(s)??this.stateFromRecord(u));let p,m=0,y=this.createHubClient({url:Yo(this.options.apiBaseUrl,s),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${s}-${Ws()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:E,cwd:E,resolveConnectionHeaders:async()=>{r();let w=m>0;if(m+=1,p)p.connected=!1,p.reconnecting=w,this.publishSnapshot(s);if(w){let f=p;if(f&&!f.disposed){f.transcriptKnown=!1,f.innerSessionId=void 0;let g=(async()=>{if(await this.resolveInnerSession(s,f),f.innerSessionId)await this.rehydrateAfterTransportDrop(s,f)})().catch(()=>this.disposeConnectionIfSessionGone(s,f)).finally(()=>{if(f.reconnectResolution===g)f.reconnectResolution=void 0,f.connected=f.transcriptKnown,this.publishSnapshot(s)});f.reconnectResolution=g}}let b=await this.options.getAuthToken();if(!b?.trim())throw new I("authentication_required","Sign in to Cline to reconnect this cloud session.");return r(),{Authorization:`Bearer ${b.trim()}`}}});p={generation:o,remote:u,client:y,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},p.unsubscribe=y.subscribe(()=>{},{sessionId:u.metadata.taskId?.trim()||s}),this.connections.set(s,p);try{if(await y.connect(),p.connected=!0,this.publishSnapshot(s),this.assertSessionActive(s,p),await this.resolveInnerSession(s,p,Boolean(i.handoffSeed)),this.assertSessionActive(s,p),i.handoffSeed&&p.innerSessionId)await this.assertHandoffConnectionReusable(p,i.handoffSeed);if(i.createInner&&!p.innerSessionId)await this.createInnerSession(p,i.handoffSeed);return this.assertSessionActive(s,p),p}catch(w){if(ke(w)&&!this.disposed&&!p.disposed&&!this.deletingSessions.has(s))throw w;if(this.connections.get(s)===p)this.connections.delete(s);if(p.disposed=!0,p.unsubscribe(),!this.disposed&&o===(this.sessionGenerations.get(s)??0))this.clearPendingApprovals(s);throw await y.dispose().catch(()=>{return}),w}})().finally(()=>{if(this.connectionPromises.get(s)===h)this.connectionPromises.delete(s)});return this.connectionPromises.set(s,h),await h}async resolveInnerSession(s,i,o=!1){if(this.assertSessionActive(s,i),i.innerSessionId)return;let r=i.remote.metadata.taskId?.trim(),c;if(r)try{let u=await i.client.command("session.get",{sessionId:r},r);this.assertSessionActive(s,i),c=u.payload?.session&&typeof u.payload.session==="object"&&!Array.isArray(u.payload.session)?u.payload.session:void 0}catch(u){if(!ct(u))throw u}else{let u=await i.client.command("session.list",{limit:100});this.assertSessionActive(s,i),c=Ie(u.payload).filter(Ce).sort((p,m)=>At(m)-At(p))[0]}let l=String(c?.sessionId??"").trim();if(!l||!c){if(!o&&!this.pendingInitialTasks.has(s))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}if(i.remote.sandboxType==="resumable"||i.remote.metadata.sandboxType==="resumable")await this.restoreSavedInnerSession(i,l,c),this.assertSessionActive(s,i);this.pendingInitialTasks.delete(s),i.innerSessionId=l,this.subscribeToInnerSession(s,i);let h=_t(c);if(h)this.applyModel(i,h);await this.ensureAttached(i)}async restoreSavedInnerSession(s,i,o){let r=()=>s.client.command("session.update_connection",{sessionId:i,updates:{}},i);try{await r();return}catch(b){if(!(ct(b)||b instanceof Error&&b.code==="command_failed"&&b.message===`session not found: ${i}`))throw b}this.assertSessionActive(s.remote.id,s);let c=o.metadata??{},l=o.runtimeOptions??{},h=this.sessions.get(s.remote.id)?.config,u=Object.hasOwn(c,"thinking")?c.thinking:h?.thinking,p=Object.hasOwn(c,"reasoningEffort")?c.reasoningEffort:h?.reasoningEffort,m=typeof c.autoApproveTools==="boolean"?c.autoApproveTools:h?.autoApproveTools,y=o.cwd??o.workspaceRoot??E,w=o.workspaceRoot??E;try{let b={workspaceRoot:w,cwd:y,metadata:{...c,interactive:!0},sessionConfig:{sessionId:i,providerId:c.provider??"cline",modelId:c.model??c.modelId??s.remote.metadata.modelId,workspaceRoot:w,cwd:y,systemPrompt:l.systemPrompt??c.systemPrompt??"",mode:l.mode??c.mode??"act",...typeof u==="boolean"?{thinking:u}:{},...typeof p==="string"?{reasoningEffort:p}:{},...c.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:l,...typeof m==="boolean"?{toolPolicies:{"*":{autoApprove:m}}}:{}},f=await s.client.command("session.resume",b).catch(async(g)=>{if(!(g instanceof oe)||g.code!=="unsupported_command")throw g;this.assertSessionActive(s.remote.id,s);let S=await s.client.command("session.messages",{},i);this.assertSessionActive(s.remote.id,s);let C=S.payload?.messages;if(!Array.isArray(C)||C.length===0)throw Error("The saved conversation is empty or unavailable.");return s.client.command("session.create",{...b,initialMessages:C})});if(this.assertSessionActive(s.remote.id,s),(f.payload?.session?.sessionId??f.payload?.sessionId)!==i)throw Error("Cloud Hub did not restore the requested session.")}catch(b){if(b?.code!=="session_already_exists")throw b;this.assertSessionActive(s.remote.id,s),await r()}}async assertHandoffConnectionReusable(s,i){let o=await s.client.command("session.list",{limit:100});this.assertSessionActive(s.remote.id,s);let r=Ie(o.payload).filter(Ce),[c]=r;if(r.length!==1||String(c?.sessionId??"").trim()!==s.innerSessionId||Rt(c)!==i.sourceSessionId)throw new I("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.")}async createInnerSession(s,i){if(this.assertSessionActive(s.remote.id,s),s.innerSessionCreation){if(await s.innerSessionCreation,i)await this.assertHandoffConnectionReusable(s,i);return}let o=(async()=>{if(i&&await this.adoptExistingHandoffSession(s,i)){this.unconfirmedInnerCreates.delete(s.remote.id);return}if(i?.recoverOnly||this.unconfirmedInnerCreates.has(s.remote.id))throw new I("request_failed","Cloud conversation creation is still unconfirmed. Wait for it to appear before trying again.");await this.createInnerSessionOnce(s,i)})().finally(()=>{s.innerSessionCreation=void 0});return s.innerSessionCreation=o,await o}async adoptExistingHandoffSession(s,i){let o=await s.client.command("session.list",{limit:100});this.assertSessionActive(s.remote.id,s);let r=Ie(o.payload).filter(Ce);if(r.length===0)return!1;let[c]=r,l=String(c?.sessionId??"").trim();if(r.length!==1||!l||Rt(c)!==i.sourceSessionId)throw new I("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return s.innerSessionId=l,this.subscribeToInnerSession(s.remote.id,s),this.applySessionModel(s,c),await this.ensureAttached(s),!0}async resolveComputerUse(s){if(!Eo(s))return!1;try{return await this.options.isComputerUseEnabled?.()===!0}catch(i){return this.options.logger?.debug("Cloud computer-use gate failed",{error:i}),!1}}async createInnerSessionOnce(s,i){let o=s.remote.metadata.modelId?.trim();if(!o)throw Error("Cloud session is missing its model id");let r=this.sessions.get(s.remote.id),c=this.pendingInitialTasks.get(s.remote.id)??this.restoredOptions.get(s.remote.id),l=_e(i?.workspaceRelativePath??c?.workspaceRelativePath),h=i?.mode??c?.mode??"act";try{await i?.onSeeding?.(),this.assertSessionActive(s.remote.id,s)}catch(C){if(i)throw new He(C);throw C}let u=await this.resolveComputerUse(o),p=Jo(s.remote,{computerUse:u}),m=i?.config?.thinking??r?.config.thinking,y=i?.config?.reasoningEffort??r?.config.reasoningEffort,w=!1,b=s.client.command("session.create",{workspaceRoot:E,cwd:l,...i?{initialMessages:i.messages}:{},sessionConfig:{...s.remote.metadata.taskId?.trim()?{sessionId:s.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:o,workspaceRoot:E,cwd:l,systemPrompt:i?`${ls}
33
+
34
+ This session was handed off from a local workspace to a fresh Linux clone of ${s.remote.repoContext.repoUrl??"the repository"}@${s.remote.repoContext.branch??"the selected branch"} at ${E}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(l===E?"":`
35
+
36
+ Continue from the original repository subdirectory at ${l}.`)+(u?`
37
+
38
+ ${rs}`:""):p,mode:h,enableTools:!0,...typeof m==="boolean"?{thinking:m}:{},...typeof y==="string"?{reasoningEffort:y}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:o,interactive:!0,thinking:m??null,reasoningEffort:m===!1?null:y??null,...i?{handoff:{from:"local",sourceSessionId:i.sourceSessionId,outerSessionId:s.remote.id}}:{}},runtimeOptions:{mode:h},modelSelection:{provider:"cline",model:o},toolPolicies:{"*":{autoApprove:(i?.config?.autoApproveTools??r?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive(s.remote.id,s),onDispatch:()=>{w=!0}}),f;try{f=await b}catch(C){if(i&&!w)throw new He(C);if(i&&(Ae(C,"session.create")||ke(C)))this.unconfirmedInnerCreates.add(s.remote.id);throw C}this.assertSessionActive(s.remote.id,s);let g=f.payload?.session&&typeof f.payload.session==="object"?f.payload.session:void 0,S=String(g?.sessionId??f.payload?.sessionId??"").trim();if(!S){if(i)this.unconfirmedInnerCreates.add(s.remote.id);throw Error("Cloud Hub did not return an inner session id")}if(this.unconfirmedInnerCreates.delete(s.remote.id),this.pendingInitialTasks.delete(s.remote.id),s.innerSessionId=S,s.remote.metadata.cwd=l,r)r.config.cwd=l,r.config.mode=h;this.subscribeToInnerSession(s.remote.id,s),this.applySessionModel(s,g),s.transcriptKnown=!i}handleEvent(s,i,o){if(this.disposed||i.disposed)return;if(i.innerSessionId&&o.sessionId&&o.sessionId!==i.innerSessionId)return;let r=o.eventId?.trim();if(r&&!(o.event==="approval.requested"&&o.sequence===void 0)){if(i.seenEventIds.has(r))return;i.seenEventIds.add(r);while(i.seenEventIds.size>Ko){let c=i.seenEventIds.values().next().value;if(c)i.seenEventIds.delete(c)}}if(i.bufferingEvents){if(i.bufferedEvents.push(o),i.bufferedEvents.length>Wo)i.bufferedEvents.shift(),i.bufferedEventsDropped+=1,this.options.logger?.log("Cloud sync event buffer reached its limit",{sessionId:s,severity:"warn"});return}this.forwardEvent(s,i,o)}forwardEvent(s,i,o){if(this.disposed||i.disposed)return;if(o.event==="session.attached"||o.event==="session.updated"||o.event==="session.created")this.applySessionModel(i,o.payload?.session);if(o.event==="approval.requested"){this.handleApprovalRequested(s,i,o);return}if(o.event==="approval.resolved"){let h=String(o.payload?.approvalId??"").trim();if(h)this.removeApproval(s,h);return}if(o.event==="run.started"){let h=this.sessions.get(s)?.busy,u=o.payload?.requestId,p=typeof u==="string"?i.pendingInputs?.get(u):void 0;if(p&&o.payload?.clientId===p.clientId){if(p.accept(),p.ownsBusyState)i.externalRun=void 0}else if(typeof o.payload?.clientId==="string")i.externalRun??={progressHydrated:Boolean(h)}}let r=i.externalRun,c=o.event==="run.completed"||o.event==="run.failed"||o.event==="run.aborted",l=r&&!r.progressHydrated&&(o.event==="assistant.delta"||o.event==="reasoning.delta"||o.event==="tool.started");if(r&&(l||c)){if(r.progressHydrated=!0,c)i.externalRun=void 0;let h=Boolean(i.rehydrationPromise);if(this.rehydrateAfterTransportDrop(s,i).catch((u)=>{if(this.disposed||i.disposed)return;this.notify("cloud_session_sync_failed",{sessionId:s,message:u instanceof Error?u.message:"Cloud transcript refresh failed"})}),!h){i.bufferedEvents.push(o);return}}if(this.applyLiveEvent(s,o),this.publish({type:"hub_event",sessionId:s,event:{...o,sessionId:s}}),o.event==="assistant.delta"||o.event==="reasoning.delta"||o.event==="tool.updated")this.scheduleSnapshot(s);else this.publishSnapshot(s)}handleApprovalRequested(s,i,o){this.storePendingApproval(s,i,o.payload),this.sendApprovalSnapshot(s)}storePendingApproval(s,i,o){let r=String(o?.approvalId??"").trim();if(!r)return;let c=`${s}:${r}`,l={approvalId:r,requestId:c,sessionId:s,createdAt:new Date(typeof o?.createdAt==="number"?o.createdAt:Date.now()).toISOString(),toolCallId:String(o?.toolCallId??""),toolName:String(o?.toolName??"tool"),input:Zo(o?.inputJson),iteration:typeof o?.iteration==="number"?o.iteration:void 0,agentId:typeof o?.agentId==="string"?o.agentId:void 0,conversationId:typeof o?.conversationId==="string"?o.conversationId:void 0};this.approvals.set(c,{item:l,resolve:async(h)=>{if(this.disposed||i.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");if(await this.ensureAttached(i),this.disposed||i.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");await i.client.command("approval.respond",{approvalId:r,approved:h.approved,reason:h.reason},i.innerSessionId)}})}removeApproval(s,i){this.approvals.delete(`${s}:${i}`),this.sendApprovalSnapshot(s)}clearPendingApprovals(s){for(let[i,o]of this.approvals)if(o.item.sessionId===s)this.approvals.delete(i);this.sendApprovalSnapshot(s)}sendApprovalSnapshot(s){this.notify("tool_approval_state",{sessionId:s,items:Array.from(this.approvals.values()).filter((i)=>i.item.sessionId===s).map((i)=>i.item)})}async ensureAttached(s){if(this.assertSessionActive(s.remote.id,s),!s.innerSessionId)return;let i=await s.client.command("session.attach",{sessionId:s.innerSessionId},s.innerSessionId);this.assertSessionActive(s.remote.id,s),this.applySessionModel(s,i.payload?.session)}subscribeToInnerSession(s,i){let o=i.innerSessionId;if(!o)return;i.unsubscribe(),this.clearPendingApprovals(s),i.unsubscribe=i.client.subscribe((r)=>this.handleEvent(s,i,r),{sessionId:o})}applySessionModel(s,i){if(!i||typeof i!=="object"||Array.isArray(i))return;let o=_t(i);if(o)this.applyModel(s,o);let r=i,c=typeof r.cwd==="string"&&ie.normalize(r.cwd)===r.cwd&&(r.cwd===E||r.cwd.startsWith(`${E}/`))?r.cwd:void 0;if(c){s.remote.metadata.cwd=c;let u=this.sessions.get(s.remote.id);if(u)u.config.cwd=c}let l=this.sessions.get(s.remote.id),h=r.runtimeOptions?.mode;if(l&&(h==="act"||h==="plan"||h==="yolo"||h==="zen"))l.config.mode=h}async disposeConnection(s){this.cancelScheduledSnapshot(s);let i=this.connections.get(s);if(this.connections.delete(s),!i)return;i.disposed=!0,i.pendingInputs?.clear(),i.unsubscribe(),this.clearPendingApprovals(s),await i.client.dispose()}async disposeConnectionIfSessionGone(s,i){if(i.disposed||this.disposed)return;let o;try{o=await this.resolveActiveOrganizationId()}catch{return}let r=await this.options.api.list(o).catch(()=>{return});if(!r||i.disposed)return;let c=r.find((h)=>h.id===s),l=c?this.preserveConnectedRuntimeModel(c):void 0;if(!l){await this.disposeConnection(s).catch(()=>{return});return}if(this.knownSessions.set(s,l),i.remote=l,l.status==="failed"||l.status==="suspended"){let h=this.sessions.get(s);if(h)h.busy=!1,h.status=l.status,h.endedAt=Date.parse(l.updatedAt)||Date.now();await this.disposeConnection(s).catch(()=>{return});return}if(L(l))await this.attachExpired(l).catch(()=>{return}),await this.disposeConnection(s).catch(()=>{return})}}class sn{getConnection;snapshots=new Map;records=new Map;listeners=new Set;unsubscribe;connection;disposed=!1;serviceId;scopeGeneration=-1;revision=-1;sessionRevisions=new Map;constructor(s){this.getConnection=s}async ready(){if(this.disposed)throw Error("Cloud viewer is disposed");if(!this.connection){let s=this.getConnection().then(async(i)=>{if(this.disposed)throw Error("Cloud viewer is disposed");this.unsubscribe=i.subscribe((o)=>{if(o.event==="cloud.event")this.recover(o.payload)});try{let o=await i.command("cloud.watch");return this.checkReply(o),this.recover(o.payload),i}catch(o){throw this.unsubscribe?.(),this.unsubscribe=void 0,o}});this.connection=s,s.catch(()=>{if(this.connection===s)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(s){if(this.disposed||!this.acceptVersion(s))return;let i=Number(s?.revision);if(Array.isArray(s?.snapshots)){let o=s.snapshots,r=new Set(o.map((c)=>c.sessionId));for(let c of this.snapshots.keys())if((!s.sessionId||s.sessionId===c)&&!r.has(c))this.receive({type:"removed",sessionId:c},i);for(let c of o)this.receive({type:"snapshot",sessionId:c.sessionId,snapshot:c,replace:!0},i)}else this.receive(s?.event,i)}acceptVersion(s){if(typeof s?.serviceId!=="string"||typeof s.revision!=="number")return!1;if(s.serviceId===this.serviceId&&Number(s.scopeGeneration)<this.scopeGeneration)return!1;if(s.serviceId!==this.serviceId||s.scopeGeneration!==this.scopeGeneration){for(let i of this.snapshots.keys())this.receive({type:"removed",sessionId:i});this.records.clear(),this.sessionRevisions.clear(),this.serviceId=s.serviceId,this.scopeGeneration=Number(s.scopeGeneration),this.revision=-1}return this.revision=Math.max(this.revision,s.revision),!0}checkReply(s){if(!s.ok)throw Error(s.error?.message??"Cloud hub request failed")}receive(s,i=this.revision){if(this.disposed||!s)return;if(i<(this.sessionRevisions.get(s.sessionId)??-1))return;if(this.sessionRevisions.set(s.sessionId,i),s.type==="snapshot")this.snapshots.set(s.sessionId,structuredClone(s.snapshot));if(s.type==="removed")this.snapshots.delete(s.sessionId),this.records.delete(s.sessionId);let o=te(s);for(let r of this.listeners)r(o)}subscribe(s){return this.listeners.add(s),()=>this.listeners.delete(s)}async call(s,i,o){let r=o?{...o}:this.scope,c=await this.ready();if(this.disposed)throw Error("Cloud viewer is disposed");let l=r??{serviceId:this.serviceId,scopeGeneration:this.scopeGeneration},h=()=>l.serviceId===this.serviceId&&l.scopeGeneration===this.scopeGeneration,u=!1,p=await c.command("cloud.command",{operation:s,args:i,scope:l},void 0,{timeoutMs:["create","send","attach"].includes(s)?null:void 0,beforeDispatch:()=>{if(this.disposed)throw Error("Cloud viewer is disposed");if(!h())throw Error("Cloud account changed before request");if(u)throw Error("Cloud request outcome is unknown; reconnect before retrying")},onDispatch:()=>{u=!0}}).catch((m)=>{let y=m instanceof Error&&m.name==="HubCommandError"&&"code"in m&&m.code!=="hub_command_timeout";if(s==="create"&&typeof i[0]==="object"&&i[0]!==null&&"initialMessage"in i[0]&&i[0].initialMessage!==void 0&&u&&!y)throw new I("request_failed","The cloud task may have started. Check your cloud tasks before submitting this draft again.");throw m});if(this.checkReply(p),!h()||p.payload?.serviceId!==l.serviceId||p.payload?.scopeGeneration!==l.scopeGeneration||!this.acceptVersion(p.payload))throw Error("Cloud account changed during request");if(this.disposed)throw Error("Cloud viewer is disposed");return p.payload?.result}create(s,i){return this.call("create",[s],i)}attach(...s){return this.call("attach",s)}send(...s){return this.call("send",s)}prepareHandoffRepository(s,i){return this.call("prepareHandoffRepository",[s],i)}refreshOrganization(){return this.call("refreshOrganization",[])}abort(...s){return this.call("abort",s)}pendingPrompts(...s){return this.call("pendingPrompts",s)}updatePendingPrompt(...s){return this.call("updatePendingPrompt",s)}removePendingPrompt(...s){return this.call("removePendingPrompt",s)}readMessages(...s){return this.call("readMessages",s)}updateTitle(...s){return this.call("updateTitle",s)}delete(...s){return this.call("delete",s)}listModels(s){return this.call("listModels",[],s)}listRepositories(...s){return this.call("listRepositories",s)}listBranches(...s){return this.call("listBranches",s)}respondApproval(...s){return this.call("respondApproval",s)}restoreCreationOptions(...s){return this.call("restoreCreationOptions",s)}getCrossScopeDiscoveryRecord(...s){return this.call("getCrossScopeDiscoveryRecord",s)}async list(){return await this.call("list",[])}async listForDiscovery(...s){let i=await this.call("listForDiscovery",s);for(let o of i)this.records.set(String(o.sessionId),structuredClone(o));return i}getCachedDiscoveryRecord(s){let i=this.records.get(s);return i?structuredClone(i):void 0}getSnapshot(s){let i=this.snapshots.get(s);return i?structuredClone(i):void 0}isCloudSession(s){return s.trim().startsWith("ses-")||this.records.has(s)||this.snapshots.has(s)}async dispose(){this.disposed=!0,this.unsubscribe?.(),this.unsubscribe=void 0;for(let s of this.snapshots.keys())for(let i of this.listeners)i({type:"removed",sessionId:s});this.snapshots.clear(),this.records.clear(),this.listeners.clear()}}var dr=["create","attach","send","abort","pendingPrompts","updatePendingPrompt","removePendingPrompt","readMessages","updateTitle","delete","list","listForDiscovery","getCrossScopeDiscoveryRecord","listModels","listRepositories","listBranches","respondApproval","restoreCreationOptions","refreshOrganization","prepareHandoffRepository"];export{dr as CLOUD_HUB_OPERATIONS,ls as CLOUD_SESSION_SYSTEM_PROMPT,Ot as CloudCreationUnconfirmedError,Ht as CloudHandoffCreationRejectedError,O as CloudHandoffGitPreflightError,He as CloudHandoffSeedRejectedError,us as CloudHandoffSeedUnsupportedError,Ut as CloudHandoffTranscriptMismatchError,De as CloudQueueUnconfirmedError,Vs as CloudSessionApi,tn as CloudSessionController,I as CloudSessionError,sn as HubCloudSessionClient,Tn as buildCloudHandoffDashboardUrl,Jo as buildCloudSessionSystemPrompt,_n as clearCloudHandoffMetadata,Cn as cloudHandoffFingerprintsEqual,it as cloudHandoffTranscriptsEqual,$t as cloudSessionToDiscoveryRecord,ae as countPromptOccurrences,dn as createArtifactFetcher,mn as createArtifactPublisher,Ps as createCloudHandoffFingerprint,Ns as deriveCloudSessionTitle,On as inspectHandoffGit,Qo as isCloudOuterSessionId,Ce as isRootSessionRow,Ro as loadCloudModels,An as mergeCloudHandoffMetadata,se as normalizeGitHubRemoteUrl,Ke as normalizeSessionTitle,Dt as parseCloudProvisioningPhase,In as preflightCloudHandoffGit,Mn as previewHandoffGit,kn as readCloudHandoffMetadata,Ie as readSessionRows,Lo as reconcileBufferedCloudEvents,Go as resolveSessionListTitle,_t as sessionRowModelId,cs as stringifyMessageContent,ds as submittedPromptsFromEvents,At as updatedAt};
@@ -0,0 +1 @@
1
+ import{gl}from"./index-sdvqs19c.js";import{lt}from"./index-ffna8yzn.js";import{AsyncLocalStorage as v}from"node:async_hooks";import{accessSync as f,existsSync as y,constants as m}from"node:fs";import{createRequire as g}from"node:module";import{delimiter as w,dirname as u,join as d}from"node:path";var l=new v;async function S(){let e=process,r=new Set,t=(o,n)=>{if(o==="uncaughtException"&&l.getStore()===r)r.add(n)};e.on("newListener",t);try{return await l.run(r,()=>import("./index-v4-qqb2kabr.js"))}finally{e.removeListener("newListener",t);for(let o of r)e.removeListener("uncaughtException",o)}}var P=new Set(["doGenerate","doStream","doEmbed"]),p=Promise.resolve();function c(e){return e.options??{}}function h(e){let r=process.platform==="win32"?[".exe",".cmd",".bat",""]:[""];for(let t of(process.env.PATH??"").split(w)){if(!t)continue;for(let o of r){let n=d(t,`${e}${o}`);try{return f(n,m.X_OK),n}catch{}}}return}function C(){let e=process.platform==="linux"?[`${process.platform}-${process.arch}`,`${process.platform}-${process.arch}-musl`]:[`${process.platform}-${process.arch}`],r=process.platform==="win32"?"claude.exe":"claude",t=[d(u(process.execPath),"noop.js"),import.meta.url];for(let o of t)for(let n of e)try{let i=g(o).resolve(`@anthropic-ai/claude-agent-sdk-${n}/package.json`),s=d(u(i),r);return f(s,m.X_OK),s}catch{}return h("claude")}async function N(e){let r;try{({createClaudeCode:r}=await import("./index-t75m2pgm.js"))}catch(s){throw Error("The Claude Code provider requires the optional 'ai-sdk-provider-claude-code' package. Install it alongside @cline/llms to use this provider.",{cause:s})}let{cwd:t,...o}=c(e),n={...o.defaultSettings??{}};if(n.pathToClaudeCodeExecutable===void 0){let s=C();if(s!==void 0)n.pathToClaudeCodeExecutable=s}if(n.cwd===void 0&&typeof t==="string"&&t.length>0&&y(t))n.cwd=t;if(n.settingSources===void 0)n.settingSources=["user","project"];if(n.permissionMode===void 0)n.permissionMode="acceptEdits";let i=r({...o,defaultSettings:n});return{operations:{language:(s)=>i(s)}}}async function j(e){let r;try{({createCodexExec:r}=await import("./index-v80fh3x3.js"))}catch(o){throw Error("The OpenAI Codex provider requires the optional 'ai-sdk-provider-codex-cli' package. Install it alongside @cline/llms to use this provider.",{cause:o})}let t=r(c(e));return{operations:{language:(o)=>t(o)}}}async function E(e){let r=["SIGINT","SIGTERM"],t=new Map(r.map((n)=>[n,new Set(process.listeners(n))])),o=await e();for(let n of r)for(let i of process.listeners(n))if(!t.get(n)?.has(i))process.removeListener(n,i);return o}async function F(e){let r=await E(async()=>{let{createOpencode:t}=await import("./index-8qjtgvqw.js");return t(c(e))});return{operations:{language:(t)=>r(t)}}}async function V(e){let r=await lt(e),t=gl({baseURL:e.baseUrl,headers:e.headers,fetch:e.fetch,...c(e)});return{operations:{language:(o)=>t(o,{apiKey:r})}}}function a(e,r){let t=e[r];return typeof t==="string"&&t.trim().length>0?t.trim():void 0}function R(e){return e.replace(/\/+$/,"").replace(/\/oauth\/token$/i,"")}function I(e,r){return Boolean(e.apiKey?.trim()||e.baseUrl?.trim()||a(r,"clientId")||a(r,"clientSecret")||a(r,"tokenUrl"))}function x(e,r){let t=a(r,"clientId"),o=a(r,"clientSecret")??e.apiKey?.trim(),n=a(r,"tokenUrl"),i=e.baseUrl?.trim();if(!t||!o||!n||!i){if(!I(e,r))return;let s=[!t?"sap.clientId":void 0,!o?"sap.clientSecret":void 0,!n?"sap.tokenUrl":void 0,!i?"baseUrl":void 0].filter(Boolean);throw Error(`SAP AI Core provider is missing required configuration: ${s.join(", ")}.`)}return JSON.stringify({clientid:t,clientsecret:o,serviceurls:{AI_API_URL:i.replace(/\/+$/,"")},url:R(n)})}function k(e){let r=e.api;if(r==="orchestration"||r==="foundation-models")return r;if(e.useOrchestrationMode===!1)return"foundation-models";return"orchestration"}async function b(e,r){if(!e)return await r();let t=p.catch(()=>{}),o;p=new Promise((i)=>{o=i}),await t;let n=process.env.AICORE_SERVICE_KEY;process.env.AICORE_SERVICE_KEY=e;try{return await r()}finally{K(n),o()}}function A(e){return P.has(e)}function K(e){if(e===void 0){delete process.env.AICORE_SERVICE_KEY;return}process.env.AICORE_SERVICE_KEY=e}function T(e,r){if(!r||!e||typeof e!=="object")return e;return new Proxy(e,{get(t,o,n){let i=Reflect.get(t,o,n);if(typeof i!=="function"||!A(o))return i;return(...s)=>b(r,()=>i.apply(t,s))}})}async function Y(e){let r=c(e),t=x(e,r),o=a(r,"deploymentId"),{createSAPAIProvider:n}=await S(),i=n({name:e.providerId,...o?{deploymentId:o}:{resourceGroup:a(r,"resourceGroup")},api:k(r),...typeof r.defaultSettings==="object"&&r.defaultSettings!==null&&!Array.isArray(r.defaultSettings)?{defaultSettings:r.defaultSettings}:{},requestConfig:{headers:{"ai-client-type":"Cline"},adapter:"fetch",...e.fetch?{fetch:e.fetch}:{},maxBodyLength:Number.POSITIVE_INFINITY,maxContentLength:Number.POSITIVE_INFINITY}});return{operations:{language:(s)=>T(i(s),t)}}}export{N as createClaudeCodeProviderModule,V as createDifyProviderModule,j as createOpenAICodexProviderModule,F as createOpenCodeProviderModule,Y as createSapAiCoreProviderModule};
@@ -0,0 +1 @@
1
+ import{Jl,Vr,On,eu}from"./index-w55v4n1n.js";import{Yl}from"./index-1jwj53tz.js";import{createRequire as d}from"module";var i=d(import.meta.url),u=class extends Yl{ClientClass;constructor(e){super();this.ClientClass=e}createClient(e,r,a){let t=this.mergeModelParams(r,a);return{client:new this.ClientClass(Jl(e,r.modelVersion),e.destination),mergedParams:On(t)?t:void 0}}async executeCall(e,r,a,t){let s=this.buildRequest(r,e.mergedParams);return e.client.run(s,t)}extractEmbeddings(e){return e._data.data.slice().sort((t,s)=>t.index-s.index).map((t)=>eu(t.embedding))}extractResponseMetadata(e){return Vr(e,"rawResponse")}extractTokenCount(e){return e._data.usage.total_tokens}getUrl(){return"sap-ai:foundation-models/embeddings"}buildRequest(e,r){return{...r??{},input:e}}};export{u as FoundationModelsEmbeddingModelStrategy};
@@ -0,0 +1 @@
1
+ import{Jl,Xl,Zl}from"./index-w55v4n1n.js";import{Ks}from"./index-4tgv599k.js";import{createRequire as p}from"module";var g=p(import.meta.url),m=[...Ks.COMMON_PARAM_MAPPINGS,{camelCaseKey:"logprobs",outputKey:"logprobs"},{camelCaseKey:"topLogprobs",outputKey:"top_logprobs"},{camelCaseKey:"logitBias",outputKey:"logit_bias"},{camelCaseKey:"user",outputKey:"user"},{camelCaseKey:"n",outputKey:"n"}],M=class extends Ks{ClientClass;constructor(t){super();this.ClientClass=t}buildRequest(t,s,o,e){let a=[],n=Zl(o.tools);a.push(...n.warnings);let{responseFormat:r,warning:l}=Xl(o.responseFormat,s.responseFormat);if(l)a.push(l);let{toolChoice:i}=e;return{request:{messages:e.messages,...e.modelParams,...n.tools?.length?{tools:n.tools}:{},...i?{tool_choice:i}:{},...r?{response_format:r}:{},...s.dataSources?.length?{data_sources:s.dataSources}:{}},warnings:a}}createClient(t,s,o){let e=Jl(t,s.modelVersion);return new this.ClientClass(e,t.destination)}async executeApiCall(t,s,o){let e=await t.run(s,o),{requestId:a,responseMetadata:n}=this.extractMetadata(e);return{getContent:()=>e.getContent(),getFinishReason:()=>e.getFinishReason(),getTokenUsage:()=>e.getTokenUsage(),getToolCalls:()=>e.getToolCalls(),rawResponse:{headers:e.rawResponse.headers},requestId:a,responseMetadata:n}}async executeStreamCall(t,s,o,e,a,n){let r=await t.stream(s,o,a),{requestId:l,responseHeaders:i,responseMetadata:u}=this.extractMetadata(r);return{cancel:()=>{r.stream.controller.abort()},getFinishReason:()=>r.getFinishReason(),requestId:l,responseHeaders:i,responseMetadata:u,stream:r.stream}}getCompletionDataPath(){return[]}getParamMappings(){return m}getUrl(){return"sap-ai:foundation-models"}};export{M as FoundationModelsLanguageModelStrategy};
@@ -0,0 +1 @@
1
+ import{Pc}from"./index-0ahmqye5.js";import{A}from"./index-4etvmc8g.js";import{i,c}from"./index-edf1hmcw.js";var d=i(function(r){Object.defineProperty(r,"__esModule",{value:!0});r.getMachineId=void 0;var n=c("fs"),u=Pc(),t=A();async function a(){try{return(await n.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(e){t.diag.debug(`error reading machine id: ${e}`)}try{return(await u.execAsync("kenv -q smbios.system.uuid")).stdout.trim()}catch(e){t.diag.debug(`error reading machine id: ${e}`)}return}r.getMachineId=a});export default d();
@@ -0,0 +1 @@
1
+ import{Cc}from"./index-94jdgxt6.js";import{A}from"./index-4etvmc8g.js";import{i,c}from"./index-edf1hmcw.js";var d=i(function(r){Object.defineProperty(r,"__esModule",{value:!0});r.getMachineId=void 0;var n=c("fs"),u=Cc(),t=A();async function a(){try{return(await n.promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(e){t.diag.debug(`error reading machine id: ${e}`)}try{return(await u.execAsync("kenv -q smbios.system.uuid")).stdout.trim()}catch(e){t.diag.debug(`error reading machine id: ${e}`)}return}r.getMachineId=a});export default d();
@@ -0,0 +1,2 @@
1
+ import{Cc}from"./index-94jdgxt6.js";import{A}from"./index-4etvmc8g.js";import{i}from"./index-edf1hmcw.js";var o=i(function(r){Object.defineProperty(r,"__esModule",{value:!0});r.getMachineId=void 0;var d=Cc(),u=A();async function a(){try{let t=(await d.execAsync('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split(`
2
+ `).find((s)=>s.includes("IOPlatformUUID"));if(!t)return;let n=t.split('" = "');if(n.length===2)return n[1].slice(0,-1)}catch(e){u.diag.debug(`error reading machine id: ${e}`)}return}r.getMachineId=a});export default o();
@@ -0,0 +1,2 @@
1
+ import{Pc}from"./index-0ahmqye5.js";import{A}from"./index-4etvmc8g.js";import{i}from"./index-edf1hmcw.js";var o=i(function(r){Object.defineProperty(r,"__esModule",{value:!0});r.getMachineId=void 0;var d=Pc(),u=A();async function a(){try{let t=(await d.execAsync('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split(`
2
+ `).find((s)=>s.includes("IOPlatformUUID"));if(!t)return;let n=t.split('" = "');if(n.length===2)return n[1].slice(0,-1)}catch(e){u.diag.debug(`error reading machine id: ${e}`)}return}r.getMachineId=a});export default o();
@@ -0,0 +1 @@
1
+ import{A}from"./index-4etvmc8g.js";import{i,c}from"./index-edf1hmcw.js";var u=i(function(t){Object.defineProperty(t,"__esModule",{value:!0});t.getMachineId=void 0;var s=c("fs"),d=A();async function o(){let n=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let a of n)try{return(await s.promises.readFile(a,{encoding:"utf8"})).trim()}catch(e){d.diag.debug(`error reading machine id: ${e}`)}return}t.getMachineId=o});export default u();
@@ -0,0 +1 @@
1
+ import{A}from"./index-4etvmc8g.js";import{i,c}from"./index-edf1hmcw.js";var u=i(function(t){Object.defineProperty(t,"__esModule",{value:!0});t.getMachineId=void 0;var s=c("fs"),d=A();async function o(){let n=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let a of n)try{return(await s.promises.readFile(a,{encoding:"utf8"})).trim()}catch(e){d.diag.debug(`error reading machine id: ${e}`)}return}t.getMachineId=o});export default u();
@@ -0,0 +1 @@
1
+ import{A}from"./index-4etvmc8g.js";import{i}from"./index-edf1hmcw.js";var r=i(function(e){Object.defineProperty(e,"__esModule",{value:!0});e.getMachineId=void 0;var d=A();async function n(){d.diag.debug("could not read machine-id: unsupported platform");return}e.getMachineId=n});export default r();
@@ -0,0 +1 @@
1
+ import{A}from"./index-4etvmc8g.js";import{i}from"./index-edf1hmcw.js";var r=i(function(e){Object.defineProperty(e,"__esModule",{value:!0});e.getMachineId=void 0;var d=A();async function n(){d.diag.debug("could not read machine-id: unsupported platform");return}e.getMachineId=n});export default r();
@@ -0,0 +1 @@
1
+ import{Cc}from"./index-94jdgxt6.js";import{A}from"./index-4etvmc8g.js";import{i,c}from"./index-edf1hmcw.js";var p=i(function(n){Object.defineProperty(n,"__esModule",{value:!0});n.getMachineId=void 0;var s=c("process"),o=Cc(),d=A();async function u(){let e="%windir%\\System32\\REG.exe";if(s.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in s.env)e="%windir%\\sysnative\\cmd.exe /c "+e;try{let t=(await o.execAsync(`${e} QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`)).stdout.split("REG_SZ");if(t.length===2)return t[1].trim()}catch(r){d.diag.debug(`error reading machine id: ${r}`)}return}n.getMachineId=u});export default p();
@@ -0,0 +1 @@
1
+ import{Pc}from"./index-0ahmqye5.js";import{A}from"./index-4etvmc8g.js";import{i,c}from"./index-edf1hmcw.js";var p=i(function(n){Object.defineProperty(n,"__esModule",{value:!0});n.getMachineId=void 0;var s=c("process"),o=Pc(),d=A();async function u(){let e="%windir%\\System32\\REG.exe";if(s.arch==="ia32"&&"PROCESSOR_ARCHITEW6432"in s.env)e="%windir%\\sysnative\\cmd.exe /c "+e;try{let t=(await o.execAsync(`${e} QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`)).stdout.split("REG_SZ");if(t.length===2)return t[1].trim()}catch(r){d.diag.debug(`error reading machine id: ${r}`)}return}n.getMachineId=u});export default p();
@@ -0,0 +1 @@
1
+ import{lt}from"./index-ffna8yzn.js";import{bl}from"./index-5hwscy9s.js";import"./index-cyyvppz9.js";var s=/^v\d+(?:alpha|beta)?\d*$/i;function l(r){let e=r?.trim().replace(/\/+$/,"");if(!e)return;let t=e.slice(e.lastIndexOf("/")+1);return s.test(t)?e:`${e}/v1beta`}async function m(r,e){let t=await lt(r),a=bl({apiKey:t,baseURL:l(r.baseUrl),headers:r.headers,fetch:r.fetch,name:e.provider.id});return{buildModelTools:(o)=>{let i={};for(let n of o)if(n.name==="web_search")i.web_search={tool:a.tools.googleSearch({})};return i},operations:{language:(o)=>a(o),imageGeneration:(o)=>a.image(o)}}}export{m as createGoogleProviderModule};