@cline/core 0.0.95 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ClineCore.d.ts +6 -1
- package/dist/account/rpc.d.ts +3 -1
- package/dist/cline-core/runtime-services.d.ts +4 -2
- package/dist/cloud/controller.d.ts +5 -2
- package/dist/cloud/hub-client.d.ts +51 -0
- package/dist/cloud/hub-protocol.d.ts +18 -0
- package/dist/cloud/index.d.ts +2 -0
- package/dist/cloud/index.js +16 -16
- package/dist/cloud/types.d.ts +4 -1
- package/dist/extensions/context/compaction-shared.d.ts +1 -0
- package/dist/extensions/context/compaction.d.ts +7 -0
- package/dist/extensions/context/summarize-conversation.d.ts +7 -0
- package/dist/extensions/context/summary-generation.d.ts +14 -0
- package/dist/extensions/mcp/apps.d.ts +16 -0
- package/dist/extensions/mcp/client.d.ts +1 -0
- package/dist/extensions/mcp/index.d.ts +5 -1
- package/dist/extensions/mcp/manager.d.ts +2 -1
- package/dist/extensions/mcp/session-apps.d.ts +28 -0
- package/dist/extensions/mcp/types.d.ts +22 -0
- package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
- package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
- package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
- package/dist/hub/client/index.d.ts +6 -0
- package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
- package/dist/hub/client/plugin-commands.d.ts +4 -0
- package/dist/hub/client/session-client.d.ts +2 -0
- package/dist/hub/daemon/entry.js +241 -228
- package/dist/hub/index.d.ts +1 -0
- package/dist/hub/index.js +231 -218
- package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
- package/dist/hub/server/cloud-session-service.d.ts +50 -0
- package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
- package/dist/hub/server/handlers/context.d.ts +13 -2
- package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
- package/dist/hub/server/hub-server-options.d.ts +3 -0
- package/dist/hub/server/hub-server-transport.d.ts +2 -0
- package/dist/index.d.ts +8 -4
- package/dist/index.js +278 -258
- package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
- package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-b1d8eb67.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-33qvrctr.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-paabhz8w.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-yhsfqcy1.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +21 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/community-gqgs7446.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-822304b0.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-hky2m2yx.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-sqf1kd37.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-tx1kp6xn.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-6cpgjxme.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-fxchqbze.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-m3bzwmzc.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-pr9sb5fr.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-nckraycx.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-w91yq3tm.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-xdyxc2tf.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-yxsvs11a.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/google-pgdk2dm9.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1160 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1147 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-02jpyn9y.js +85 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0cb4390m.js +137 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0f8xrhgt.js +209 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1f8vb421.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-28c7m0fv.js +16 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-2em3jg4q.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4n1zpzbe.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-54eea0ex.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5j92dtg5.js +16 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6akf3a5d.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6k6ep10s.js +136 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-71ym4q6s.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-91p1ghfk.js +14 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9qkpjy7x.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9swk4nej.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-aa2s5myc.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ae0ajw38.js +13 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bxvyzjhc.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bzy863k0.js +6 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d96n0s70.js +20 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-dsd6vt8c.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-e2q4azd9.js +119 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-egd18jj2.js +4 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-eh83hr16.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ev9r2dy3.js +1204 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f2mvvryf.js +190 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7gn5v3f.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7s1a560.js +12 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkhq3jtz.js +21 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-j8r18nfg.js +15 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-jhny555h.js +6 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m1gpa2eg.js +146 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m2ad6tgj.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m7mks2jq.js +4 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-mcnngj50.js +62 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-n2srkkh0.js +39 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nbs1tsny.js +142 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nqjnz7m4.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rmhzyxr8.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rtzf3vvk.js +6 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sw74pcm3.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t3eanyjj.js +3 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-tseksj1v.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v0ctpcdr.js +12 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-dx8bd4wq.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v695918t.js +14 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v96yy1pw.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vfm7r9wk.js +65 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xecthgrg.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xn1xhp06.js +9 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yfdscfdx.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yrnwqsdt.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-3mgy2y9y.js +473 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-w1xrs0vd.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-9tppg77c.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-y658kpzy.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-cmhqd91b.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-qkjjf8mm.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-8z6y9d1h.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-cfmja1ez.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-1t7n5sxj.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-k6yqgnyd.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-6rdyebbq.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/token-1h068py9.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-7jchft51.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-qfxfsrn4.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
- package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
- package/dist/plugin-runtime/package.json +1 -0
- package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
- package/dist/remote/remote-environments.d.ts +1 -0
- package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
- package/dist/runtime/host/local-runtime-host.d.ts +10 -0
- package/dist/runtime/host/runtime-host.d.ts +6 -0
- package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
- package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
- package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
- package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
- package/dist/services/llms/cline-recommended-models.d.ts +2 -0
- package/dist/services/local-runtime-bootstrap.d.ts +1 -0
- package/dist/services/plugin-command-api.d.ts +47 -0
- package/dist/services/plugin-commands.d.ts +25 -27
- package/dist/services/skills-cli.d.ts +2 -0
- package/dist/services/telemetry/core-events.d.ts +26 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/services/telemetry/run-health.d.ts +40 -0
- package/dist/services/telemetry/stall-signals.d.ts +12 -0
- package/dist/types/config.d.ts +1 -0
- package/dist/types/session.d.ts +7 -0
- package/package.json +6 -5
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import{Mt,ei,me,ne,Fn,jn,re,We,$n,Hi,ti,qn,zt,Xe,P,Z}from"../index-e2q4azd9.js";import{ki,ms,ya,xa}from"../index-v695918t.js";import{er}from"../index-xn1xhp06.js";import{v}from"../index-mcnngj50.js";import{execFile as Wt}from"node:child_process";import{basename as En,resolve as Kt}from"node:path";import{promisify as Qt}from"node:util";import{randomUUID as os}from"node:crypto";import{randomUUID as ps}from"node:crypto";import{posix as W}from"node:path";var It=v(ms(),1),Ct=v(er(),1);import{spawn as ws}from"node:child_process";import{closeSync as ys,mkdirSync as gs,openSync as vs,readFileSync as bs,unlinkSync as Ss}from"node:fs";import{basename as Is,dirname as Cs,join as As}from"node:path";import{fileURLToPath as ks}from"node:url";import{createHash as _s,randomBytes as Ts}from"node:crypto";import{mkdir as Ie,open as Ke,readFile as At,rename as Es,rm as xe,writeFile as Ps}from"node:fs/promises";import{dirname as kt,join as $e}from"node:path";import{join as ai}from"node:path";var Jt=Qt(Wt);function Yt(e,t){return Jt("git",e,{cwd:t.cwd,encoding:"utf8",windowsHide:!0,signal:t.signal,timeout:15000,maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND||"ssh -o BatchMode=yes"}})}function Ee(e){if(!e||typeof e!=="object"||!("stderr"in e))return"";return typeof e.stderr==="string"?e.stderr.trim():""}function ve(e){if(!e||typeof e!=="object"||!("code"in e))return;return typeof e.code==="number"?e.code:void 0}function Xt(e){let t=Zt(e.cwd),s=e.git??Yt,i=async(o)=>(await s(o,{cwd:t,signal:e.signal})).stdout,n=async(o)=>(await i(o)).trim();return{async isInsideWorkTree(){try{return await n(["rev-parse","--is-inside-work-tree"])==="true"}catch(o){if(ve(o)===128&&/not a git repository|Kein Git-Repository/i.test(Ee(o)))return!1;throw o}},remotes:()=>ki({baseDir:t}).getRemotes(!0),displayBranch:async()=>(await ki({baseDir:t}).branch()).current.trim(),symbolicBranch:()=>n(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>n(["rev-parse","HEAD"]),workspacePrefix:async()=>(await i(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>n(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(o)=>n(["config","--get",`branch.${o}.remote`]),branchMergeRef:(o)=>n(["config","--get",`branch.${o}.merge`]),remoteUrl:(o)=>n(["remote","get-url",o]),remoteRefs:(o,r)=>n(["ls-remote","--exit-code",o,r])}}function Zt(e){return Kt(e)}class k extends Error{code;constructor(e,t,s){super(t,s);this.code=e,this.name="CloudHandoffGitPreflightError"}}function Be(e){let t=0,s=e.length;while(t<s&&e[t]==="/")t+=1;while(s>t&&e[s-1]==="/")s-=1;let i=e.slice(t,s);return i.toLowerCase().endsWith(".git")?i.slice(0,-4):i}function ze(e){let t=e.trim();if(!t)return null;let s=t.match(/^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i);if(s?.[1]){let i=Be(s[1]);return i.split("/").length===2?`https://github.com/${i}`:null}try{let i=new URL(t);if(i.hostname.toLowerCase()!=="github.com")return null;if(!new Set(["https:","http:","ssh:","git:"]).has(i.protocol))return null;let n=Be(i.pathname);return n.split("/").length===2?`https://github.com/${n}`:null}catch{return null}}async function O(e,t,s){try{return await e()}catch(i){let n=Ee(i);throw new k(t,n?`${s} (${n})`:s,{cause:i})}}function es(e,t){let s=`refs/heads/${t}`;for(let i of e.split(`
|
|
2
|
+
`)){let[n,o]=i.trim().split(/\s+/,2);if(o===s&&/^[0-9a-f]{40,64}$/i.test(n??""))return n??null}return null}function ts(e){let t=e.replace(/[\r\n]+$/,"").replace(/\/+$/,"");if(!t)return;let s=t.split("/");if(t.startsWith("/")||s.some((i)=>!i||i==="."||i===".."))throw new k("git_command_failed","Could not resolve the workspace path relative to the Git repository.");return t}async function Hn(e){let t=Xt(e);if(!await O(t.isInsideWorkTree,"not_git_repository","Cloud handoff requires a Git repository."))throw new k("not_git_repository","Cloud handoff requires a Git working tree.");let s=ts(await O(t.workspacePrefix,"git_command_failed","Could not resolve the workspace path relative to the Git repository.")),i=await O(t.worktreeStatus,"git_command_failed","Could not inspect the Git worktree.");if(i){let c=i.split(`
|
|
3
|
+
`).filter(Boolean),f=c.slice(0,5).join(`
|
|
4
|
+
`),m=c.length>5?`
|
|
5
|
+
...and ${c.length-5} more`:"";throw new k("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
|
|
6
|
+
|
|
7
|
+
${f}${m}`)}let n;try{n=await t.symbolicBranch()}catch(c){let f=ve(c)===1,m=Ee(c),y=f?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new k(f?"detached_head":"git_command_failed",m?`${y} (${m})`:y,{cause:c})}if(!n)throw new k("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[o,r,a]=await Promise.all([O(()=>t.branchRemote(n),"missing_upstream",`Branch ${n} has no upstream. Push it with -u before handing off.`),O(()=>t.branchMergeRef(n),"missing_upstream",`Branch ${n} has no upstream. Push it with -u before handing off.`),O(t.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!o||o==="."||!r.startsWith("refs/heads/"))throw new k("missing_upstream",`Branch ${n} has no remote branch upstream. Push it with -u before handing off.`);let d=r.slice(11),u=o;if(!ze(o))try{u=await t.remoteUrl(o)}catch{throw new k("missing_upstream","Could not resolve the upstream remote.")}let p=ze(u);if(!p)throw new k("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let l;try{l=await t.remoteRefs(o,r)}catch(c){let f=ve(c)===2,m=f?`The upstream branch ${d} 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 k(f?"remote_branch_missing":"git_command_failed",m)}let h=es(l,d);if(!h)throw new k("remote_branch_missing",`The upstream branch ${d} was not found. Push it before handing off.`);if(h.toLowerCase()!==a.toLowerCase())throw new k("unpushed_commits",`Local HEAD does not match the upstream branch ${d}. Push the current commit before handing off.`);return{repoUrl:p,branch:d,headSha:a,...s?{workspaceRelativePath:s}:{}}}function be(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function x(e){if(typeof e!=="string")return;return e.trim()||void 0}function ss(e){return typeof e==="string"&&e.length>0?e:void 0}function is(e){let t=x(e.repoUrl),s=x(e.branch),i=x(e.headSha),n=x(e.modelId);if(!t||!s||!i||!n)throw Error("Cloud handoff fingerprint fields cannot be empty.");let o=x(e.organizationId),r=ss(e.workspaceRelativePath),a=e.mode;return{repoUrl:t,branch:s,headSha:i,modelId:n,...o?{organizationId:o}:{},...r?{workspaceRelativePath:r}:{},...a?{mode:a}:{}}}function Mn(e,t){return e!==void 0&&t!==void 0&&e.repoUrl===t.repoUrl&&e.branch===t.branch&&e.headSha.toLowerCase()===t.headSha.toLowerCase()&&e.modelId===t.modelId&&e.organizationId===t.organizationId&&e.workspaceRelativePath===t.workspaceRelativePath&&e.mode===t.mode}function ns(e){let t=be(e);if(!t||typeof t.repoUrl!=="string"||typeof t.branch!=="string"||typeof t.headSha!=="string"||typeof t.modelId!=="string")return;try{return is({repoUrl:t.repoUrl,branch:t.branch,headSha:t.headSha,modelId:t.modelId,...typeof t.organizationId==="string"?{organizationId:t.organizationId}:{},...typeof t.workspaceRelativePath==="string"?{workspaceRelativePath:t.workspaceRelativePath}:{},...t.mode==="plan"||t.mode==="yolo"||t.mode==="zen"?{mode:t.mode}:{}})}catch{return}}function Un(e){let t=be(be(e)?.handoff);if(!t)return;let s=x(t.toCloudSessionId),i=x(t.handedOffAt),n=t.status;if(!s||!i||n!=="pending"&&n!=="complete")return;let o=x(t.innerSessionId),r=x(t.dashboardUrl),a=ns(t.fingerprint);return{toCloudSessionId:s,handedOffAt:i,status:n,...o?{innerSessionId:o}:{},...r?{dashboardUrl:r}:{},...a?{fingerprint:a}:{}}}function On(e,t){return{...e??{},handoff:t}}function Dn(e){let{handoff:t,cloudHandoffIntent:s,cloudHandoffSeedDispatched:i,...n}=e??{};return n}function Bn(e,t){let s=t.trim();if(!s)throw Error("Cloud session id cannot be empty.");let i=new URL("/agents",e);return i.searchParams.set("sessionId",s),i.toString()}function Ne(e){return e.map((t)=>{let s=t&&typeof t==="object"?t:{};return{role:s.role,content:s.content}})}function Le(e,t){return e.length===t.length&&JSON.stringify(Ne(e))===JSON.stringify(Ne(t))}class yt extends Error{constructor(e,t){super(`Cloud transcript verification failed (local ${e} messages, cloud ${t}).`);this.name="CloudHandoffTranscriptMismatchError"}}var rs=610000,as=3000,j=15000,ds="CLOUD_SESSION_ERROR:",gt="__cline_create_request__:";function cs(e){return(e.trim().split(`
|
|
8
|
+
`)[0]??"").trim().slice(0,72)}class w extends Error{code;detail;connectUrl;status;constructor(e,t,s,i){super(`${ds}${JSON.stringify({code:e,message:t,connectUrl:s})}`);this.code=e,this.detail=t,this.connectUrl=s,this.status=i,this.name="CloudSessionError"}}class vt extends w{constructor(e){super("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list or dashboard before starting another task.");this.name="CloudCreationUnconfirmedError",this.cause=e}}class bt extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function Se(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function ls(e){return`${gt}${e}`.slice(0,255)}function Ge(e){return e?.startsWith(gt)===!0}function St(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function ee(e){let t=ne(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function Fe(e){return new Promise((t,s)=>{if(e.aborted){s(e.reason);return}let i=()=>{clearTimeout(n),s(e.reason)},n=setTimeout(()=>{e.removeEventListener("abort",i),t()},as);e.addEventListener("abort",i,{once:!0})})}function us(e,t){if(e&&typeof e==="object"){let s=e.error;if(typeof s==="string"&&s.trim())return s.trim()}return t}function te(e,t,s,i){let n=us(t,`Cloud session request failed (${e})`);if(e===401)return new w("authentication_required",n);if(e===404)return new w("session_not_found",n);if(e===410)return new w("session_expired",n);if(e===412)return new w("github_not_connected",n,i??`${Se(s)}/dashboard/integrations`);if(e===403&&n.trim().toLowerCase()==="forbidden")return new w("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new w("request_failed",n,void 0,e)}class hs{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e,this.apiBaseUrl=Se(e.apiBaseUrl),this.appBaseUrl=Se(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??rs}async request(e,t={},s,i,n){let o=!1,r;while(!0){let a;try{a=typeof i==="string"?i:await this.options.getAuthToken()}catch(p){if(r)throw te(401,void 0,this.appBaseUrl,s);throw p}if(!a?.trim())throw new w("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new w("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof i==="object"){if(i.subject?ee(a.trim())!==i.subject:a.trim()!==i.token)throw new w("authentication_required","The signed-in account changed during cloud session creation.");i.token=a.trim()}n?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(j),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),u=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof i==="object"&&!o&&i.subject){o=!0,r=a.trim();continue}throw te(d.status,u,this.appBaseUrl,s)}return u?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,s=!1){let i=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${i}`,{},void 0,t)??[]).flatMap((n)=>{if(!n||typeof n!=="object"||typeof n.id!=="string")return[];return[{...n,title:!s&&Ge(n.title)?void 0:n.title,repoContext:n.repoContext&&typeof n.repoContext==="object"?n.repoContext:{},metadata:{...n.metadata&&typeof n.metadata==="object"?n.metadata:{},...!s&&Ge(n.title)?{createRequestTitle:n.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),s=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,i=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let n=await this.request(i)??[];return{connected:!0,connectUrl:s,repositories:n.flatMap((o)=>{let r=Number(o.id),a=String(o.html_url??o.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(o.name??"").trim();return[{id:r,name:d,fullName:String(o.full_name??(d||a)).trim(),url:a,defaultBranch:String(o.default_branch??"").trim()}]})}}catch(n){if(n instanceof w&&n.code==="session_not_found")return{connected:!1,connectUrl:s,repositories:[]};throw n}}async listBranches(e,t,s={}){if(!Number.isSafeInteger(e)||e<=0)throw new w("request_failed","Select a GitHub repository before loading branches.");let i=t?.trim(),n=i?`/api/v1/organizations/${encodeURIComponent(i)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,o=new URLSearchParams,r=s.query?.trim(),a=s.cursor?.trim();if(r)o.set("query",r);if(a)o.set("cursor",a);let d=o.size>0?`${n}?${o}`:n;try{let u=await this.request(d),p=Array.isArray(u)?u:Array.isArray(u?.items)?u.items:[],l=r?.toLowerCase();return{available:!0,branches:p.flatMap((h)=>{let c=String(h.name??"").trim();return c&&(!Array.isArray(u)||!l||c.toLowerCase().includes(l))?[c]:[]}),nextToken:Array.isArray(u)?"":String(u?.nextToken??"").trim()}}catch(u){if(u instanceof w&&u.code==="session_not_found")return{available:!1,branches:[]};throw u}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(j)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new w("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new w("authentication_required","Sign in to Cline before starting a cloud session.");let s={token:t,subject:ee(t)},i=ls(e.requestId?.trim()||os()),n=e.handoff?`${s.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new w("request_failed","A stable request id is required for cloud handoff creation.");let o=async()=>(await this.listWithToken(e.organizationId??void 0,s,!0)).filter((l)=>l.title===i&&l.repoContext.repoUrl===e.repoUrl&&l.metadata.modelId===e.modelId&&(!e.branch?.trim()||l.repoContext.branch===e.branch.trim())),r=async(l)=>{if(l.status==="failed"||l.expiredAt&&Date.parse(l.expiredAt)<=Date.now()){let c=new w(l.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(l.id,s)}catch(f){if(!(f instanceof w&&(f.code==="session_not_found"||f.code==="session_expired")))throw AggregateError([c,f],"The unusable recovered cloud handoff workspace could not be removed.")}if(n)this.unconfirmedHandoffCreates.delete(n),this.completedHandoffCreates.delete(n);throw await e.handoff?.onOuterSessionRemoved?.(l.id),c}await e.handoff?.onOuterSessionCreated(l.id,{created:!1});let h={sessionId:l.id,status:l.status,sandboxUrl:l.sandboxUrl,cleanupAuthToken:s.token};if(n)this.unconfirmedHandoffCreates.delete(n),this.completedHandoffCreates.set(n,h);return h};if(n){let l=await o();if(l.length>1)throw new w("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(l[0])return await r(l[0]);let h=this.completedHandoffCreates.get(n);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,s)}catch(c){if(c instanceof w&&(c.code==="session_not_found"||c.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(n),this.unconfirmedHandoffCreates.delete(n);throw c}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:s.token}}if(this.unconfirmedHandoffCreates.has(n))throw new w("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(n)}try{await e.handoff?.onCreating()}catch(l){if(n)this.unconfirmedHandoffCreates.delete(n);throw l}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),u,p=!1;try{let l=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:i,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,s,()=>{p=!0}),h=l?.sessionId?.trim();if(!h)throw new w("request_failed","The cloud session service returned no session id.");u=h,await this.persistHandoffOuterSession(e,h,s,n);let c={sessionId:h,status:l.status?.trim()||"provisioning",sandboxUrl:l.sandboxUrl?.trim()??"",cleanupAuthToken:s.token};if(n)this.unconfirmedHandoffCreates.delete(n),this.completedHandoffCreates.set(n,c);return c}catch(l){if(u)throw l;let h=!p||l instanceof w&&(l.status!==void 0&&l.status>=400&&l.status<500&&l.status!==408&&l.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(l.code));if(n&&h)throw this.unconfirmedHandoffCreates.delete(n),new bt(l);if(a.signal.aborted||!(l instanceof w)||l instanceof w&&l.code==="request_failed"&&(l.status===void 0||l.status>=500||l.status===408||l.status===409)){let c=[];try{c=await o()}catch(m){if(e.handoff)throw AggregateError([l,m],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(!e.handoff&&!h&&c.length!==1)throw new vt(l);if(c.length>1)throw new w("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let f=c[0];if(f){if(e.handoff)return await r(f);return{sessionId:f.id,status:f.status,sandboxUrl:f.sandboxUrl,cleanupAuthToken:s.token}}}else if(n)this.unconfirmedHandoffCreates.delete(n);throw l}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,s,i){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(n){try{await this.deleteWithAuth(t,s.token)}catch(o){if(!(o instanceof w&&(o.code==="session_not_found"||o.code==="session_expired")))throw AggregateError([n,o],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(i)this.unconfirmedHandoffCreates.delete(i);throw await e.handoff.onOuterSessionRemoved?.(t),n}}async waitUntilReady(e,t,s){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let i=await this.options.getAuthToken(),n=i?{token:i,subject:ee(i)}:void 0;while(!t.aborted){let o;try{o=await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:AbortSignal.any([t,AbortSignal.timeout(j)])},void 0,n)}catch(a){if(t.aborted)throw a;if(a instanceof w&&a.code!=="request_failed")throw a;await Fe(t);continue}let r=o?.status?.trim().toLowerCase();if(s?.({phase:St(o?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new w("session_failed",o?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new w("request_failed","The cloud session service returned an unexpected provisioning status.");await Fe(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(j)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let s;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(i){if(!(i instanceof w)||i.code!=="session_not_found"&&i.code!=="session_expired")throw i;s=i}for(let[i,n]of this.completedHandoffCreates)if(n.sessionId===e)this.completedHandoffCreates.delete(i),this.unconfirmedHandoffCreates.delete(i);if(s)throw s}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new w("authentication_required","Sign in to Cline to load this session's history.");let s=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(j)});if(s.status===404)return null;let i=await s.json().catch(()=>{return});if(!s.ok)throw te(s.status,i,this.appBaseUrl);if(!i||typeof i!=="object"||!("version"in i)||i.version!==1||!("messages"in i)||!Array.isArray(i.messages))throw new w("request_failed","Invalid archived session history");return i.messages}}var Pe={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.2.0",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"]},fs="session_not_found";class Re extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e,this.name="SessionNotFoundError"}}function Ve(e){return e instanceof Re||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}var Rs="CLINE_HUB_DISCOVERY_PATH",xs="CLINE_HUB_BUILD_ID",$s="CLINE_HUB_BUILD_EPOCH_MS",Hs=30000,Ms=15000,Qe=100;function qs(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Us(e){return _s("sha256").update(e).digest("hex").slice(0,12)}function Os(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function Je(e){return new Promise((t)=>setTimeout(t,e))}function Ds(e){return`${e}.lock`}async function js(e){try{let t=JSON.parse(await At($e(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function se(e){await xe(e,{recursive:!0,force:!0}).catch(()=>{return})}function J(){let e=process.env[xs]?.trim();if(e)return e;return"sdk-v1-2575e46ceecd35cbe25f0581cea02b42a151c34df1a966c1737aaaf88a5350c7".trim()||`source-${String(Pe.version)}`}function Bs(){let e=Number(process.env[$s]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792985554353)?1792985554353:void 0}function _t(e,t=J()){let s=Mt(e);if(!s.compatible)return s;let i=e.buildId?.trim();if(!i)return{compatible:!1,reason:"missing_build"};if(i!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function Ye(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function Ze(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let s=t.split(".").map((i)=>Number(i));if(s.length===0||s.some((i)=>!Number.isInteger(i)||i<0))return;return s}function zs(e,t){for(let s=0;s<Math.max(e.length,t.length);s++){let i=e[s]??0,n=t[s]??0;if(i!==n)return i<n?-1:1}return 0}function Ns(e,t){let s=e.buildId?.trim(),i=t.buildId?.trim();if(s&&i&&s===i)return 0;let n=Ye(e.buildEpochMs),o=Ye(t.buildEpochMs);if(n!==void 0&&o!==void 0&&n!==o)return n<o?-1:1;let r=Ze(e.coreVersion),a=Ze(t.coreVersion);if(r&&a){let d=zs(r,a);if(d!==0)return d}if(s&&i&&s!==i)return s<i?-1:1;return 0}function Ls(){return{buildId:J(),buildEpochMs:Bs(),coreVersion:String(Pe.version)}}function Tt(e,t){let s=t?.self??Ls(),i=_t(e,s.buildId??"");if(i.compatible)return!0;if(i.reason!=="build_mismatch"&&i.reason!=="missing_build")return!1;return Ns(s,e)<=0}function Gs(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Us(e)}`,s=process.env[Rs]?.trim()||$e(Z(),"locks","hub","owners",`${qs(t)}.json`);return{ownerId:t,discoveryPath:s}}async function N(e,t={}){try{let s;try{s=await At(e,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}let i;try{i=JSON.parse(s)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!i||typeof i.hubId!=="string"||typeof i.protocolVersion!=="string"||typeof i.authToken!=="string"||typeof i.host!=="string"||typeof i.port!=="number"||typeof i.url!=="string"||typeof i.startedAt!=="string"||typeof i.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:i.hubId,protocolVersion:i.protocolVersion,minClientProtocolVersion:typeof i.minClientProtocolVersion==="string"?i.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof i.maxClientProtocolVersion==="string"?i.maxClientProtocolVersion:void 0,capabilities:Array.isArray(i.capabilities)?i.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof i.coreVersion==="string"?i.coreVersion:void 0,buildId:typeof i.buildId==="string"?i.buildId:void 0,buildEpochMs:typeof i.buildEpochMs==="number"?i.buildEpochMs:void 0,authToken:i.authToken,host:i.host,port:i.port,url:i.url,pid:typeof i.pid==="number"?i.pid:void 0,startedAt:i.startedAt,updatedAt:i.updatedAt}}catch(s){if(t.onError==="throw")throw s;return}}async function Fs(e,t){await Pt(e,async()=>{let s=kt(e);await Ie(s,{recursive:!0});let i=`${e}.${process.pid}.${Ts(6).toString("hex")}.tmp`,n;try{n=await Ke(i,"wx",384),await n.writeFile(`${JSON.stringify(t,null,2)}
|
|
9
|
+
`,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await Es(i,e);let o;try{o=await Ke(s,"r"),await o.sync()}catch{}finally{await o?.close().catch(()=>{return})}}catch(o){throw await n?.close().catch(()=>{return}),await xe(i,{force:!0}).catch(()=>{return}),o}})}async function Y(e){await Pt(e,async()=>{await xe(e,{force:!0}).catch(()=>{return})})}async function Et(e,t,s){let i=Ds(e);await Ie(kt(i),{recursive:!0});let n=Date.now()+Ms;while(!0){try{await Ie(i,{recursive:!1})}catch(o){if((o instanceof Error&&"code"in o?String(o.code):"")!=="EEXIST")throw o;let r=await js(i);if(!r){if(Date.now()>=n){await se(i);continue}await Je(Qe);continue}let a=Date.now()-Date.parse(r.acquiredAt);if(!Os(r.pid)||a>Hs){await se(i);continue}if(Date.now()>=n)throw Error(`Timed out waiting for hub ${t} lock ${i}`);await Je(Qe);continue}try{return await Ps($e(i,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
10
|
+
`,"utf8"),await s()}finally{await se(i)}}}function Pt(e,t){return Et(`${e}.mutation`,"discovery mutation",t)}function Vs(e,t){return Et(e,"startup",t)}async function Rt(e,t){Xe();try{let s=await fetch(t?.authToken?Ks(e):xt(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!s.ok)return;let i=await s.json();if(typeof i.protocolVersion!=="string"||typeof i.host!=="string"||typeof i.port!=="number"||typeof i.url!=="string")return;return{protocolVersion:i.protocolVersion,minClientProtocolVersion:typeof i.minClientProtocolVersion==="string"?i.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof i.maxClientProtocolVersion==="string"?i.maxClientProtocolVersion:void 0,capabilities:Array.isArray(i.capabilities)?i.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof i.coreVersion==="string"?i.coreVersion:void 0,buildId:typeof i.buildId==="string"?i.buildId:void 0,buildEpochMs:typeof i.buildEpochMs==="number"?i.buildEpochMs:void 0,host:i.host,port:i.port,url:i.url,hubId:typeof i.hubId==="string"?i.hubId:void 0,authToken:typeof i.authToken==="string"?i.authToken:void 0,pid:typeof i.pid==="number"?i.pid:void 0,startedAt:typeof i.startedAt==="string"?i.startedAt:void 0,updatedAt:typeof i.updatedAt==="string"?i.updatedAt:void 0}}catch{return}}function Ws(e,t,s="/hub"){return new URL(`ws://${e}:${t}${s}`).toString()}function xt(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function Ks(e){let t=new URL(xt(e));return t.pathname="/status",t.toString()}var Qs="CLINE_HUB_HOST",Js="CLINE_HUB_PORT",Ys="CLINE_HUB_PATHNAME",Xs="127.0.0.1",Zs=Fn,si="/hub";function et(e){return re(e)==="development"?jn:Zs}function ii(e={}){return(e.env??process.env)[Qs]?.trim()||Xs}function ni(e={}){let t=(e.env??process.env)[Js]?.trim();if(!t)return et(e);let s=Number.parseInt(t,10);if(!Number.isInteger(s)||s<1||s>65535)return et(e);return s}function oi(e={}){return(e.env??process.env)[Ys]?.trim()||si}function ri(e={},t={}){return{host:e.host??ii(t),port:e.port??ni(t),pathname:e.pathname??oi(t)}}var di="shared:cline",ci="CLINE_HUB_DISCOVERY_PATH",li="hub-production";function He(e=di){return Gs(`${e}@${J()}`)}function $t(){return{ownerId:li,discoveryPath:process.env[ci]?.trim()||ai(Z(),"locks","hub","production.json")}}var tt=15000,ui=200,st=3000,hi=100,pi=[100,250,500,1000,2000],Ht="--cline-hub-daemon",fi=3,mi=60000,it=new Map;function wi(e,t=Date.now()){let s=it.get(e);if(!s||t-s.windowStartedAt>mi)return it.set(e,{count:1,windowStartedAt:t}),!0;return s.count+=1,s.count<=fi}function yi(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function gi(){try{let e=As(Z(),"logs","hub-daemon.log");return gs(Cs(e),{recursive:!0}),{fd:vs(e,"a"),logPath:e}}catch{return}}function vi(){return re()==="production"?$t():He()}function B(e){return Tt(e)}function bi(e){try{let t=JSON.parse(bs(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function ie(e){try{Ss(`${e}.superseded`)}catch{}}function nt(e,t,s){if(!t||t.url!==s)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function z(e,t){try{return await Rt(e,{authToken:t})}catch{return}}async function ot(e,t){let s=Date.now()+t;while(Date.now()<s){if(!(await z(e))?.url)return!0;await new Promise((i)=>setTimeout(i,hi))}return!1}async function Me(e,t){if(!wi(e.url))return!1;await G(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Qi(e.url,e.authToken).catch(()=>!1);let s=await ot(e.url,st);if(!s&&e.pid&&Si(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}s=await ot(e.url,st)}if(s)await Y(t).catch(()=>{return});return s}function Si(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Ii(e){try{let t=await jt(e.url,e.authToken);return t.activeSessionCount>0||(t.activePluginRequests??0)>0||(t.activeCloudCommands??0)>0}catch{return!1}}async function oe(e,t){if(B(e))return"reusable";let s=await G(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await Ii(e)){if(s)await G(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let i=await Me(e,t);if(!i&&s)await G(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return i?"retired":"failed"}async function Ci(e){if(re()!=="production")return;let t=He();if(t.discoveryPath===e.discoveryPath)return;let s=await N(t.discoveryPath);if(s?.url)await Me(s,t.discoveryPath);else await Y(t.discoveryPath).catch(()=>{return})}function Ai(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return ks(new URL(`./entry.${e}`,import.meta.url))}function _i(e,t){if($n(e))return[Ht];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}var ae;function Ti(e,t){let s,i;if(ae)s=ae.command,i=ae.args??[Ht];else{let n=process.execPath?.trim();if(!n)throw Error("unable to resolve runtime executable for hub daemon");let o=Is(n).toLowerCase().includes("bun");s=n,i=_i(Ai(),o)}return{launcher:s,args:[...i,"--cwd",e,...yi(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...qn(We(process.env),Ei()),CLINE_NO_INTERACTIVE:"1",[ti]:"1"}}}function Ei(){let e=Hi(),t=e?.name?.trim();return t?{client:t,version:e?.version,transport:"local"}:void 0}function Pi(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let t="message"in e?e.message:void 0;return typeof t==="string"&&t.includes("ETXTBSY")}function Ri(e,t={}){if(zt())return;let s=Ti(e,t),i=gi();try{ws(s.launcher,s.args,{detached:!0,stdio:i?["ignore",i.fd,i.fd]:"ignore",env:s.env,cwd:s.cwd,windowsHide:!0}).unref()}finally{if(i)ys(i.fd)}}async function xi(e,t={}){for(let s=0;;s++)try{Ri(e,t);return}catch(i){let n=pi[s];if(!Pi(i)||n===void 0)throw i;await new Promise((o)=>setTimeout(o,n))}}async function $i(e,t,s={}){let i=s.host!==void 0||s.port!==void 0||s.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),n=ri(s),o=Ws(n.host,n.port,n.pathname),r=(c)=>{if(!i)Oe(c.url,c.authToken);return c};await Ci(e).catch(()=>{return});let a=await N(e.discoveryPath),d=a?.url?void 0:bi(e.discoveryPath),u=!1;if(a?.url){let c=a.authToken;if(!c)u=!0,await Me(a,e.discoveryPath);else{let f=await z(a.url,c);if(f?.url&&B(f)&&await M(f.url,{authToken:c}))return ie(e.discoveryPath),r({url:f.url,authToken:c});if(f?.url){if(await oe({...f,authToken:c},e.discoveryPath)==="deferred_busy"&&await M(f.url,{authToken:c}))return r({url:f.url,authToken:c})}else await Y(e.discoveryPath).catch(()=>{return})}}let p=await z(o);if(p?.url){let c=nt(p,a??d,o);if(B(p)){let m=[p.authToken,a?.authToken,d?.authToken].filter((y)=>typeof y==="string"&&y.trim().length>0);for(let y of m){if(!await M(p.url,{authToken:y}))continue;let S={hubId:p.hubId??`repaired-${p.port}`,protocolVersion:p.protocolVersion,minClientProtocolVersion:p.minClientProtocolVersion,maxClientProtocolVersion:p.maxClientProtocolVersion,capabilities:p.capabilities,coreVersion:p.coreVersion,buildId:p.buildId,authToken:y,host:p.host,port:p.port,url:p.url,pid:p.pid??a?.pid??d?.pid,startedAt:p.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await Fs(e.discoveryPath,S)}catch{}return ie(e.discoveryPath),r({url:p.url,authToken:y})}throw Error(`A compatible Cline Hub is already running at ${o}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${u?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let f=await oe(c,e.discoveryPath);if(f==="deferred_busy"){for(let m of[c.authToken,a?.authToken].filter((y)=>typeof y==="string"&&y.trim().length>0))if(await M(p.url,{authToken:m}))return r({url:p.url,authToken:m});if(s.allowPortFallback!==!0&&n.port!==0)throw Error(`An older Cline Hub is running at ${o} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(f==="failed"&&s.allowPortFallback!==!0&&n.port!==0)throw Error(`An incompatible Cline Hub is already running at ${o} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let l=s.allowPortFallback===!0&&n.port!==0?{...n,port:0}:n;await s.beforeSpawn?.(),await xi(t,{...l,manageConnectors:s.manageConnectors});let h=Date.now()+tt;while(Date.now()<h){let c=await N(e.discoveryPath);if(c?.url&&c.authToken){let m=await z(c.url,c.authToken);if(m?.url&&B(m)&&await M(m.url,{authToken:c.authToken}))return ie(e.discoveryPath),r({url:m.url,authToken:c.authToken})}let f=await z(o);if(f?.url&&!B(f)){let m=nt(f,c??d,o),y=await oe(m,e.discoveryPath);if(y==="deferred_busy"&&c?.authToken&&await M(f.url,{authToken:c.authToken}))return r({url:f.url,authToken:c.authToken});if(y==="failed"&&s.allowPortFallback!==!0&&n.port!==0)throw Error(`An incompatible Cline Hub is still running at ${o} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((m)=>setTimeout(m,ui))}throw Error(`Timed out after ${tt}ms waiting for detached hub startup.`)}async function Mi(e,t={}){let s=vi();return await Vs(s.discoveryPath,async()=>$i(s,e,t))}function qi(){return re()==="production"?$t():He()}function Ui(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Oi(e){let t=new URL(e);t.protocol=e.protocol==="wss:"?"https:":"http:";let s=ya(t.toString());if(!s)return;return e.protocol==="wss:"?new Ct.HttpsProxyAgent(s):new It.HttpProxyAgent(s)}function qt(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return qt(e.data);return String(e)}function Di(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function rt(e){let t=e,s=Di(t.reason);return new C("hub_connection_closed",t.code||s?`Hub connection closed (code=${t.code??0}${s?`, reason=${s}`:""})`:Ce,{closeCode:t.code,closeReason:s||void 0})}function de(e,t){if(e instanceof C)return e;if(e instanceof Error)return new C("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new C("hub_connect_failed",e.error.message);let s=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(s)return new C("hub_connect_failed",s);let i=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new C("hub_connect_failed",i?`Failed to connect to hub at ${t.toString()} (${i} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var ce="*",L=8000,ji="cline-hub-auth.",Ut=new Map,Ot=new Set,Bi=3000,Ce="Hub connection closed",zi=250,Ni=5000,at=0.5;class C extends Error{code;details;constructor(e,t,s){super(t);this.code=e,this.details=s,this.name="HubTransportError"}}function Li(e){return e instanceof C}class Ae extends Error{command;code;constructor(e,t,s){super(s);this.command=e,this.code=t,this.name="HubCommandError"}}function qe(e,t={}){let s=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),s)return s;if(t.skipRegistry)return;let i=Ue(e.toString());return i?Ut.get(i):void 0}function Gi(e){try{let t=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}function Ue(e){if(!Gi(e))return;let t=new URL(Dt(e));return t.search="",t.hash="",t.toString()}function dt(e){let t=Ue(e);return!!t&&Ot.has(t)}function Oe(e,t){let s=Ue(e);if(s){if(Ot.add(s),t?.trim())Ut.set(s,t)}return e}class X{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 C("hub_connection_closed",Ce);sawSocketClose=!1;registered=!1;capabilities;constructor(e){if(this.options=e,e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||qe(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let s=++this.connectGeneration,i=this.openSocket(e,t,s),n;this.connectPromise=i.then(async(r)=>{if(n=r,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(Pe.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),s!==this.connectGeneration||this.closedByClient){try{r.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let a of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(a));this.reconnectAttempt=0});let o=this.connectPromise;try{await o}catch(r){if(this.connectPromise===o)this.connectPromise=void 0;if(n&&this.socket===n){this.lastCloseError=de(r,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{n.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw r}}async openSocket(e,t,s){let i=this.options.resolveConnectionHeaders,n;if(i){let u;try{n=await Promise.race([Promise.resolve().then(()=>i()),new Promise((p,l)=>{u=setTimeout(()=>{l(new C("hub_connect_timeout",`Timed out resolving hub connection headers after ${L}ms`))},L)})])}catch(p){let l=p instanceof C?p:new C("hub_connect_failed",p instanceof Error?p.message:String(p));if(s===this.connectGeneration)this.lastCloseError=l;throw l}finally{clearTimeout(u)}}if(s!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(n&&Object.keys(n).some((u)=>u.toLowerCase()==="sec-websocket-protocol")){let u=new C("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(s===this.connectGeneration)this.lastCloseError=u;throw u}let o;try{o=n?Oi(e):void 0}catch(u){let p=de(u,e);if(s===this.connectGeneration)this.lastCloseError=p;throw p}let r=n?new xa(e.toString(),{headers:{...n},agent:o}):new(Ui())(e.toString(),t?[`${ji}${t}`]:void 0);this.socket=r;let a=!1,d=new Promise((u,p)=>{let l=!1,h=setTimeout(()=>{if(l)return;l=!0,a=!0;let c=new C("hub_connect_timeout",`Timed out connecting to hub after ${L}ms`);if(this.socket===r)this.lastCloseError=c,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{r.close()}catch{}p(c)},L);r.addEventListener("open",()=>{if(l)return;l=!0,clearTimeout(h),u()}),r.addEventListener("error",(c)=>{if(l)return;l=!0,clearTimeout(h);let f=de(c,e);if(this.socket===r)this.lastCloseError=f,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;p(f)}),r.addEventListener("close",(c)=>{if(l)return;l=!0,clearTimeout(h);let f=a?this.lastCloseError:rt(c);if(this.socket===r){if(!a)this.lastCloseError=f,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}p(f)})});return r.addEventListener("message",(u)=>{this.handleFrame(JSON.parse(qt(u)))}),r.addEventListener("close",(u)=>{if(this.socket!==r)return;if(!a)this.lastCloseError=rt(u),this.sawSocketClose=!0;this.registered=!1;for(let p of this.pendingReplies.values())p.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await d,r}subscribe(e,t){let s=t?.sessionId?.trim()||void 0,i={listener:e,sessionId:s};return this.listeners.add(i),this.adjustSubscriptionCount(s,1),()=>{if(!this.listeners.delete(i))return;this.adjustSubscriptionCount(s,-1)}}async command(e,t,s,i){let n=0,o=!1,r={...i,onDispatch:(d)=>{o=!0,i?.onDispatch?.(d)}},a=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,s,r)}catch(d){if(!a||o&&i?.retryAfterDispatch===!1||n>=1||!await this.recoverLocalHubTransport(d))throw d;n+=1}}async commandOnce(e,t,s,i,n=!0){if(n)await this.connect();i?.beforeDispatch?.();let o=P("hubreq_");i?.onDispatch?.(o);let r=ei(e,i?.timeoutMs),a=new Promise((u,p)=>{let l=r===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(o))return;p(new Ae(e,"hub_command_timeout",`Hub command ${e} timed out after ${r}ms (hub=${this.currentUrl}, requestId=${o}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},r);this.pendingReplies.set(o,{resolve:(h)=>{if(l)clearTimeout(l);u(h)},reject:(h)=>{if(l)clearTimeout(l);p(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:o,clientId:this.clientId,sessionId:s,timeoutMs:r,payload:t}})}catch(u){throw this.pendingReplies.delete(o),u}let d=await a;if(!d.ok){if(d.error?.code===fs){let u=s??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Re(u,d.error.message)}throw new Ae(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!dt(this.currentUrl)||!Li(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await ct({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let e=Math.min(zi*2**this.reconnectAttempt,Ni),t=Math.round(e*(1-at)+Math.random()*e*at);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!dt(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await ct({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new C("hub_connection_closed",Ce);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new C("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let s=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...s!==void 0?{sinceSequence:s}:{}})}adjustSubscriptionCount(e,t){let s=this.subscriptionKeyForSessionId(e),i=(this.subscriptionCounts.get(s)??0)+t;if(i<=0){if(this.subscriptionCounts.delete(s),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(s,i),t>0&&i===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??ce}subscriptionSessionIdFromKey(e){return e===ce?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let s=this.pendingReplies.get(t);if(!s)return;this.pendingReplies.delete(t),s.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let s=e.envelope.sessionId?.trim();for(let i of[ce,s]){if(!i||!this.subscriptionCounts.has(i))continue;let n=this.lastEventSequenceByKey.get(i)??0;if(t>n)this.lastEventSequenceByKey.set(i,t)}}for(let s of this.listeners){if(s.sessionId&&s.sessionId!==e.envelope.sessionId?.trim())continue;s.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Dt(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function M(e,t){let s=new X({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await s.connect(),!0}catch{return!1}finally{s.close()}}async function ke(e,t){let s=Dt(e),i=await Rt(s,{authToken:t?.authToken});if(!i)return{status:"unreachable",url:s};if(t?.requireCurrentBuild){let n=J(),o=_t(i,n);if(!o.compatible&&!Tt(i))return{status:o.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:s}}else if(!Mt(i).compatible)return{status:"protocol_mismatch",url:s};if(t?.verifyConnection===!0&&!await M(s,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:s};return{status:"compatible",url:s}}function Fi(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],s=0,i=new Set;for(let o of t){if(!o||typeof o!=="object")continue;let r=o.participants;if(!Array.isArray(r)||r.length===0)continue;s+=1;for(let a of r){let d=a&&typeof a==="object"?a.clientId:void 0;if(typeof d==="string"&&d.trim())i.add(d)}}let n=(o)=>{let r=e&&typeof e==="object"?e[o]:void 0;return typeof r==="number"&&Number.isInteger(r)&&r>0?r:0};return{activeSessionCount:s,participantClientCount:i.size,activePluginRequests:n("activePluginRequests"),activeCloudCommands:n("activeCloudCommands")}}async function jt(e,t,s){let i=new X({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:s?.workspaceRoot,cwd:s?.cwd});try{let n=await i.command("session.list",{limit:500},void 0,{timeoutMs:Bi});return Fi(n.payload)}finally{await i.dispose().catch(()=>{return})}}async function Vi(e,t,s){try{let i=await jt(e,t,s);return i.activeSessionCount===0&&i.activePluginRequests===0&&i.activeCloudCommands===0}catch{return!1}}async function Wi(e,t){let s=`${e.discoveryPath}.superseded`,i=await N(s);if(!i?.url||!i.authToken)return;let n=await ke(i.url,{authToken:i.authToken});if(n.status!=="compatible")return;if(await Vi(n.url,i.authToken,t))return;return Oe(n.url,i.authToken)}async function Ki(e={}){if(e.endpoint?.trim()){let n=await ke(e.endpoint);return n.status==="compatible"?n.url:void 0}let t=qi(),s=await N(t.discoveryPath);if(!s?.url)return await Wi(t,e);let i=await ke(s.url,{authToken:s.authToken,requireCurrentBuild:!0});if(i.status==="compatible")return Oe(i.url,s.authToken);if(i.status==="protocol_mismatch")await Y(t.discoveryPath).catch(()=>{return});return}async function ct(e={}){let t=await Ki(e);if(t&&await M(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Mi(e.workspaceRoot??process.cwd())).url}catch(s){e.onStartupError?.(s);return}}async function G(e,t,s,i){Xe();let n=new URL(e),o=t?.trim()||qe(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";if(n.pathname="/drain",n.hash="",s)n.searchParams.set("reason",s);if(i?.off)n.searchParams.set("off","1");return(await fetch(n,{method:"POST",headers:o?{authorization:`Bearer ${o}`}:void 0})).ok}async function Qi(e,t){Xe();let s=new URL(e),i=t?.trim()||qe(s);if(s.protocol==="ws:")s.protocol="http:";else if(s.protocol==="wss:")s.protocol="https:";return s.pathname="/shutdown",s.hash="",(await fetch(s,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}function Ji(e,t){if(!e||typeof e!=="object")return;let s=e,i=typeof s.id==="string"?s.id.trim():"";if(!i)return;let n=typeof s.display_name==="string"?s.display_name.trim():typeof s.displayName==="string"?s.displayName.trim():"",o=typeof s.name==="string"?s.name.trim():"";return{id:i,name:n||o||i,catalogId:t}}function le(e,t){return Array.isArray(e)?e.flatMap((s)=>{let i=Ji(s,t);return i?[i]:[]}):[]}async function Yi(e,t={}){let s=e.trim(),i=s.length;while(i>0&&s[i-1]==="/")i--;let n=s.slice(0,i),o=async(m)=>{let y=await(t.fetchImpl??fetch)(`${n}${m}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!y.ok)throw Error(`HTTP ${y.status}`);return await y.json()},r,a;try{[r,a]=await Promise.all([o("/api/v1/ai/cline/models"),o("/api/v1/ai/cline/recommended-models")])}catch(m){throw Error("Could not load the cloud model catalog.",{cause:m})}let d=r&&typeof r==="object"?r:void 0,u=le(Array.isArray(r)?r:d?.data,"cline"),p=a&&typeof a==="object"?a:void 0,l=p?.data&&typeof p.data==="object"?p.data:p,h=le(l?.clinePass,"cline-pass"),c=le(l?.clineCloud,"cline-cloud"),f=new Set;return[...t.isOrganizationSession?[]:h,...c,...u].filter((m)=>{if(f.has(m.id))return!1;return f.add(m.id),!0})}var Xi=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function Zi(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function en(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function tn(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function sn(e){if(typeof e.content==="string")return{hasAttachment:!1,text:e.content};if(!Array.isArray(e.content))return{hasAttachment:!1,text:"unknown"};let t=!1,s=!1,i=[];for(let n of e.content){if(!n||typeof n!=="object"||Array.isArray(n))continue;let o=n;if(o.type==="text"&&typeof o.text==="string")i.push(o.text);else if(o.type==="tool_result"||o.type==="tool-result")s=!0;else if(o.type==="file"||o.type==="image")t=!0}return{hasAttachment:t&&!s,text:i.join(`
|
|
11
|
+
`)}}function nn(e){let t=me(e);return t.startsWith("[TASK RESUMPTION]")||t==="The user approved switching to act mode. Continue with the approved plan now."}function on(e){if(Zi(e.role)!=="user")return 0;let t=en(e),s=typeof t?.kind==="string"?t.kind:void 0,i=tn(t);if(s==="compaction"||s==="compaction_summary")return i??1;if(i!==void 0)return i;if(s&&Xi.has(s))return 0;let n=sn(e);if(!n.hasAttachment&&!me(n.text))return 0;if(!n.hasAttachment&&nn(n.text))return 0;return 1}function rn(e){return on(e)>0}function ue(e){return Array.isArray(e?.sessions)?e.sessions.filter((t)=>Boolean(t)&&typeof t==="object"&&!Array.isArray(t)):[]}function lt(e){let t=e.updatedAt;return typeof t==="number"?t:Date.parse(String(t??""))||0}function ut(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return String(t?.model??e?.model??"").trim()}function he(e){let t=e.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return!String(t?.parentSessionId??e.parentSessionId??"").trim()}function Bt(e,t="text"){if(!e||typeof e!=="object"||Array.isArray(e))return"";let s=e.content;if(typeof s==="string")return t==="text"?s.trim():"";if(!Array.isArray(s))return"";return s.map((i)=>i&&typeof i==="object"&&!Array.isArray(i)?t==="thinking"&&i.type==="redacted_thinking"?"[redacted]":String(i[t]??""):"").join("").trim()}function F(e){let t=e.trim(),s=t.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(s?s[1]:t).trim()}function K(e,t,s){let i=F(s);return e.filter((n)=>Boolean(n)&&typeof n==="object"&&!Array.isArray(n)&&String(n.role??"").toLowerCase()==="user"&&(i!==""||rn(n))&&F(Bt(n))===i).length+t.filter((n)=>F(n.prompt)===i).length}function Nt(e){return e.flatMap((t)=>{if(t.event!=="session.pending_prompt_submitted")return[];let s=t.payload?.prompt&&typeof t.payload.prompt==="object"&&!Array.isArray(t.payload.prompt)?t.payload.prompt:void 0,i=String(s?.id??"").trim();if(!i)return[];return[{id:i,prompt:String(s?.prompt??""),steer:s?.delivery==="steer",attachmentCount:typeof s?.attachmentCount==="number"?s.attachmentCount:0,userImages:Array.isArray(s?.userImages)?s.userImages.filter((n)=>typeof n==="string"):void 0}]})}var an=new Set(["run.completed","run.aborted","run.failed"]),dn=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function ht(e,t){return e.filter((s)=>Boolean(s)&&typeof s==="object"&&!Array.isArray(s)&&String(s.role??"").toLowerCase()==="assistant").map((s)=>Bt(s,t)).filter(Boolean)}function pt(e,t,s="text"){let i=new Map;for(let n of ht(t,s))i.set(n,(i.get(n)??0)+1);return ht(e,s).filter((n)=>{let o=i.get(n)??0;if(o===0)return!0;if(o===1)i.delete(n);else i.set(n,o-1);return!1})}function Q(e,t,s=new Set){if(!e||typeof e!=="object")return s;if(Array.isArray(e)){for(let o of e)Q(o,t,s);return s}let i=e,n=t==="tool_use"?i.id:i.tool_use_id;if(i.type===t&&typeof n==="string")s.add(n);for(let o of Object.values(i))Q(o,t,s);return s}function ft(e,t="assistant"){let s="",i="";for(let n of e)if(n.event===`${t}.delta`)i+=t==="reasoning"&&n.payload?.redacted&&!n.payload?.text?"[redacted]":typeof n.payload?.text==="string"?n.payload.text:"";else if(n.event===`${t}.finished`){let o=n.payload?.[t==="assistant"?"text":"reasoning"],r=typeof o==="string"&&o?o:i;if(r)s=r;i=""}return(s||i).trim()}function cn(e,t,s={}){let i=s.queueSnapshotApplied!==!1,n=pt(t,s.baselineMessages??[]),o=pt(t,s.baselineMessages??[],"thinking"),r=Q(t,"tool_use"),a=Q(t,"tool_result"),d=new Set(e.slice(0,s.messagesSnapshotEventCutoff??e.length)),u=new Set,p=new Map;for(let m of e.slice(0,s.messagesSnapshotEventCutoff??e.length)){let y=Nt([m])[0];if(!y)continue;let S=F(y.prompt),_=p.get(S)??Math.max(0,K(t,[],S)-K(s.baselineMessages??[],[],S));if(p.set(S,Math.max(0,_-1)),_>0)u.add(m)}let l=[...i?e.slice(s.queueSnapshotEventCutoff??e.length):e].reverse().find((m)=>m.event==="session.pending_prompts"),h=[],c=[],f=(m)=>{if(c.length===0)return;let y=c.filter((A)=>d.has(A)),S=(A)=>{if(!m)return-1;let I=[...y].reverse().findIndex((Vt)=>Vt.event===`${A}.finished`),D=I<0?-1:y.length-1-I;return D>=0||c.at(-1)?.event==="run.aborted"?D:y.length-1},_=S("assistant"),q=S("reasoning"),U=ft(y.slice(0,_+1)),g=U?n.findIndex((A)=>A.endsWith(U)):-1,T=g>=0;if(T)n.splice(g,1);let E=ft(y.slice(0,q+1),"reasoning"),H=E?o.findIndex((A)=>A.endsWith(E)):-1;if(H>=0)o.splice(H,1);for(let[A,I]of c.entries()){if(u.has(I)){h.push({...I,payload:{...I.payload,transcriptReflected:!0}});continue}if(d.has(I)&&dn.has(I.event)&&(I.event.startsWith("reasoning.")?H>=0&&A<=q:T&&A<=_))continue;if(I.event==="session.pending_prompts"&&I!==l)continue;if(d.has(I)&&I.event.startsWith("tool.")){let D=String(I.payload?.toolCallId??"").trim();if(a.has(D)||I.event==="tool.started"&&r.has(D))continue}h.push(I)}c=[]};for(let m of e)if(c.push(m),an.has(m.event))f(!0);return f(!1),h}function V(e){let t=structuredClone(e),s=(i)=>{if(!i||typeof i!=="object"||Object.isFrozen(i))return;for(let n of Object.values(i))s(n);Object.freeze(i)};return s(t),t}function De(e){let t=e?.trim();return t?me(t).slice(0,120):void 0}function Lt(e){if(typeof e==="string")return e;if(Array.isArray(e)){let t=[];for(let s of e){if(typeof s==="string"){if(s.trim())t.push(s);continue}if(!s||typeof s!=="object")continue;let i=s,n=typeof i.type==="string"?i.type:"",o=n==="text"?String(i.text??""):n==="thinking"?String(i.thinking??""):n==="tool_use"?`[tool] ${String(i.name??"tool_call")}`:n==="tool_result"?`[tool_result]
|
|
12
|
+
${Lt(i.content)}`:n==="image"?"[image]":n==="redacted_thinking"?"[redacted_thinking]":typeof i.text==="string"?i.text:"";if(o.trim())t.push(o)}return t.join(`
|
|
13
|
+
`)}if(e&&typeof e==="object"){let t=e;if(typeof t.text==="string")return t.text}return""}function ln(e){let t=De(e??void 0);if(!t)return;return t.split(`
|
|
14
|
+
`)[0]?.trim().slice(0,70)||void 0}function un(e){for(let t of["user","assistant"])for(let s of e){if(!s||typeof s!=="object")continue;let i=s;if(i.role!==t)continue;let n=De(Lt(i.content));if(!n)continue;return n.split(`
|
|
15
|
+
`)[0]?.trim().slice(0,70)||void 0}return}function hn(e){let t=e.metadata&&typeof e.metadata==="object"?De(e.metadata.title):void 0;if(t)return t.slice(0,70);let s=ln(e.prompt);if(s)return s;let i=e.messages?un(e.messages):void 0;if(i)return i;return`Session ${e.sessionId.slice(-6)}`}function pn(e,t,s,i){let n=t.payload??{},o=()=>{let a=s.get(i);if(a===void 0||!e.messages[a]||e.messages[a]?.role!=="assistant")a=e.messages.length,e.messages.push({role:"assistant",content:[]}),s.set(i,a);let d=e.messages[a];if(!Array.isArray(d.content))d.content=[];return d.content},r=(a,d,u)=>{let p=o(),l=p.at(-1);if(l?.type===a)l[d]=`${l[d]??""}${u}`;else p.push({type:a,[d]:u})};switch(t.event){case"assistant.delta":if(typeof n.text==="string")r("text","text",n.text);return;case"reasoning.delta":if(typeof n.text==="string"&&n.text)r("thinking","thinking",n.text);else if(n.redacted===!0)o().push({type:"redacted_thinking",data:""});return;case"assistant.finished":s.delete(i);return;case"assistant.media":if(n.media)o().push({type:"media",media:structuredClone(n.media)});return;case"tool.started":{let a=String(n.toolCallId??"");if(a&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((u)=>u.type==="tool_use"&&u.id===a)))o().push({type:"tool_use",id:a,name:String(n.toolName??"tool"),input:structuredClone(n.input??{})});return}case"tool.finished":{let a=String(n.toolCallId??"");if(a&&!e.messages.some((d)=>Array.isArray(d.content)&&d.content.some((u)=>u.type==="tool_result"&&u.tool_use_id===a)))e.messages.push({role:"user",content:[{type:"tool_result",tool_use_id:a,content:typeof n.output==="string"?n.output:JSON.stringify(n.output??""),is_error:Boolean(n.error)}]}),s.delete(i);return}case"usage.updated":e.usage=structuredClone(n.totals??n.delta??{});return;case"session.pending_prompts":{let a=Array.isArray(n.prompts)?n.prompts:[];e.promptsInQueue=a.map((d)=>({id:String(d.id??""),prompt:String(d.prompt??""),steer:d.delivery==="steer",attachmentCount:typeof d.attachmentCount==="number"?d.attachmentCount:0,userImages:Array.isArray(d.userImages)?d.userImages.filter((u)=>typeof u==="string"):void 0})).filter((d)=>d.id&&(d.prompt||d.attachmentCount));return}case"session.pending_prompt_submitted":{let a=n.prompt,d=String(a?.id??"");if(!d||e.lastQueuedPromptStartId===d)return;if(e.lastQueuedPromptStartId=d,e.promptsInQueue=e.promptsInQueue.filter((u)=>u.id!==d),n.transcriptReflected!==!0)e.messages.push({role:"user",content:[{type:"text",text:String(a?.prompt??"")}]});e.busy=!0,e.status="running",e.endedAt=void 0,s.delete(i);return}case"run.started":case"session.attached":case"session.updated":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;let a=n.session,d=typeof a?.status==="string"?a.status:t.event==="run.started"?"running":e.status,u=d==="pending"?"running":d;if(t.event==="session.updated"&&u==="running"&&e.endedAt!==void 0&&!e.busy)return;let p=e.busy;if(e.status=u,e.busy=u==="running",t.event==="run.started"){if(!p)s.delete(i);e.endedAt=void 0}return}case"run.completed":case"run.failed":case"run.aborted":{if(typeof t.sequence==="number"&&e.lastHubStatusSequence!==void 0&&t.sequence<e.lastHubStatusSequence)return;if(typeof t.sequence==="number")e.lastHubStatusSequence=t.sequence;e.status=typeof n.reason==="string"?n.reason:t.event==="run.failed"?"error":t.event==="run.aborted"?"aborted":"completed",e.busy=!1,e.endedAt=Date.now(),s.delete(i);return}}}function pe(e){return e instanceof Error&&e.name==="HubTransportError"&&["hub_connect_timeout","hub_connect_failed","hub_connection_closed","hub_connection_not_open"].includes(String(e.code))}function fe(e,t){return e instanceof Error&&e.name==="HubCommandError"&&e.code==="hub_command_timeout"&&(!t||e.command===t)}var b="/workspace",fn=30000,mn=2000,wn=2000,Gt="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 yn(e){let t=`cline/${(e.metadata.taskId?.trim()||e.id).slice(-8).toLowerCase()}`,s=e.sandboxType==="resumable"||e.metadata.sandboxType==="resumable";return`${Gt}
|
|
16
|
+
|
|
17
|
+
Do all work for this task on the branch \`${t}\`: create it from the current checkout before your first change (or check it out if it already exists), and never commit directly to the default branch. `+(s?"Commit and push only when the user asks. ":`SAVE YOUR WORK: This sandbox is temporary. Push your progress to origin so it remains available outside the sandbox. The branch \`${t}\` is a backup of your work-in-progress, not a finished deliverable, so commit to it freely even when the work is incomplete. Commit regularly as you complete meaningful steps, using clear, descriptive messages. The first time you commit, push the branch with \`git push -u origin ${t}\`, and push again after each later commit. `)+"Do not force-push or amend commits that are already pushed unless the user explicitly asks."}function we(e){if(!e)return b;if(W.isAbsolute(e)||e.includes("\\")||e.split("/").some((s)=>!s||s==="."||s===".."))throw new w("request_failed","The handoff workspace path must stay inside the repository.");let t=W.join(b,e);if(!t.startsWith(`${b}/`))throw new w("request_failed","The handoff workspace path must stay inside the repository.");return t}function je(e){let t=e.metadata.cwd;return typeof t==="string"&&W.normalize(t)===t&&(t===b||t.startsWith(`${b}/`))?t:b}function mt(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0,s=t?.handoff&&typeof t.handoff==="object"?t.handoff:void 0;return String(s?.sourceSessionId??"").trim()}class _e extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud conversation creation was not dispatched.",{cause:e});this.name="CloudHandoffSeedRejectedError"}}class Te extends w{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 Ft 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 R(e){let t=e.expiredAt?Date.parse(e.expiredAt):Number.NaN;return Number.isFinite(t)&&t<=Date.now()}function gn(e){return e.trim().startsWith("ses-")}function vn(e,t){let s=new URL(`/api/v1/session/${encodeURIComponent(t)}`,e);return s.protocol=s.protocol==="https:"?"wss:":"ws:",s.toString()}function ye(e){return{config:{executionTarget:"cloud",provider:"cline",providerId:"cline",model:e.metadata.modelId??"",modelId:e.metadata.modelId??"",repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",cwd:je(e),workspaceRoot:b},messages:[],promptsInQueue:[],busy:!1,startedAt:Date.parse(e.createdAt)||Date.now(),endedAt:R(e)&&e.expiredAt?Date.parse(e.expiredAt):void 0,status:e.status,attachedViaHub:!0}}function ge(e,t,s){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:t,provider:"cline",model:e.metadata.modelId??"",repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",cwd:je(e),workspaceRoot:b,...s?.trim()?{prompt:s.trim()}:{},metadata:{origin:"cloud",repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function wt(e){return{sessionId:e.id,origin:"cloud",executionTarget:"cloud",status:e.status,provider:"cline",model:e.metadata.modelId??"",cwd:je(e),workspaceRoot:b,repoUrl:e.repoContext.repoUrl??"",branch:e.repoContext.branch??"",startedAt:e.createdAt,...e.lastActivityAt?{lastActivityAt:e.lastActivityAt}:{},endedAt:R(e)?e.expiredAt??void 0:e.status==="failed"?e.lastActivityAt??e.createdAt:void 0,updatedAt:e.updatedAt,...e.title?.trim()?{title:e.title.trim()}:{},metadata:{...e.title?.trim()?{title:e.title.trim()}:{},origin:"cloud",...e.metadata.provisioningPhase?{provisioningPhase:e.metadata.provisioningPhase}:{},repoUrl:e.repoContext.repoUrl??"",git:{url:e.repoContext.repoUrl??"",branch:e.repoContext.branch??""}}}}function bn(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function Sn(e,t){let s=[...e??[]],i=new Set(s.map((n)=>n.id));for(let n of t)if(!i.has(n.id))s.push(n);return s}class In{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;provisioningControllers=new Map;sendAbortTokens=new Map;titleWrites=new Map;deletingSessions=new Set;createHubClient;constructor(e){this.options=e,this.pendingInitialTasks=e.pendingInitialTasks??new Map,this.createHubClient=e.createHubClient??((t)=>new X(t))}restoreCreationOptions(e,t){if(this.restoredOptions.set(e,structuredClone(t)),this.pendingInitialTasks.has(e))this.pendingInitialTasks.set(e,{...this.pendingInitialTasks.get(e),...structuredClone(t)});let s=this.sessions.get(e);if(s)Object.assign(s.config,structuredClone(t))}seedSessionState(e,t){if(!this.sessions.has(e))this.sessions.set(e,structuredClone(t))}stateFromRecord(e){let t=ye(e);return Object.assign(t.config,this.pendingInitialTasks.get(e.id),this.restoredOptions.get(e.id)),t}getSnapshot(e){let t=this.knownSessions.get(e),s=this.sessions.get(e)??(t?this.stateFromRecord(t):void 0);if(!s)return;let i=this.connections.get(e);return V({...s,sessionId:e,record:t,approvals:Array.from(this.approvals.values()).filter((n)=>n.item.sessionId===e).map((n)=>n.item),connectionState:this.detachedSessions.has(e)||this.disposed?"detached":i?.reconnectResolution||i?.rehydrationPromise?"reconnecting":i?i.connected?"connected":i.reconnecting?"reconnecting":"connecting":this.connectionPromises.has(e)?"connecting":"detached",transcriptKnown:i?.transcriptKnown??Boolean(t&&R(t))})}subscribe(e,t){let s=(i)=>{if(!t||i.sessionId===t)e(i)};return this.listeners.add(s),()=>{this.listeners.delete(s)}}publish(e){let t=e.type==="snapshot"?Object.freeze(e):V(e);for(let s of this.listeners)try{s(t)}catch(i){this.options.logger?.error?.("Cloud session subscriber failed",{error:i})}}publishSnapshot(e,t=!1,s){this.cancelScheduledSnapshot(e);let i=this.getSnapshot(e);if(i)this.publish({type:"snapshot",sessionId:e,snapshot:i,replace:t,cause:s});else this.publish({type:"removed",sessionId:e})}snapshotTimers=new Map;cancelScheduledSnapshot(e){clearTimeout(this.snapshotTimers.get(e)),this.snapshotTimers.delete(e)}scheduleSnapshot(e){if(this.disposed||this.detachedSessions.has(e)||this.snapshotTimers.has(e))return;let t=setTimeout(()=>this.publishSnapshot(e),100);t.unref?.(),this.snapshotTimers.set(e,t)}notify(e,t){let s=String(t.sessionId??"");if(e==="cloud_session_sync_failed")this.publish({type:"sync_failed",sessionId:s,message:String(t.message??"Cloud synchronization failed")});else this.publishSnapshot(s,e==="cloud_session_rehydrated",e==="chat_session_status"?"status":e==="chat_session_ended"?"ended":e==="tool_approval_state"?"approvals":void 0)}applyLiveEvent(e,t){let s=this.sessions.get(e);if(s)pn(s,t,this.streamingMessages,e)}async respondApproval(e,t,s){this.assertSessionActive(e);let i=this.approvals.get(`${e}:${t}`);if(!i){if(!this.connections.has(e))throw Error("This cloud session connection is closed; reopen the session to respond.");throw new w("request_failed","This approval was already resolved or is no longer available.")}await i.resolve(s)}async detach(e){this.detachedSessions.add(e),this.sessionGenerations.set(e,(this.sessionGenerations.get(e)??0)+1),this.connectionPromises.delete(e),this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud viewer detached")),await this.disposeConnection(e),this.publishSnapshot(e)}isCloudSession(e){return gn(e)||this.knownSessions.has(e)||this.connections.has(e)||this.sessions.get(e)?.config.executionTarget==="cloud"}getCachedDiscoveryRecord(e){let t=this.knownSessions.get(e);return t?wt(t):void 0}async getCrossScopeDiscoveryRecord(e){let t=this.getCachedDiscoveryRecord(e);if(!t)return;try{let s=(await this.options.api.status(e)).status?.trim();return s?{...t,status:s}:t}catch(s){if(s instanceof w&&(s.code==="session_not_found"||s.code==="session_expired")){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e);return}return t}}async list(){return await this.listInOrganization(await this.resolveActiveOrganizationId())}async listInOrganization(e){if(this.disposed)throw Error("Cloud session controller was disposed");let t=(r)=>this.sessions.get(r)?.title??this.knownSessions.get(r)?.title,s=new Map([...this.knownSessions.keys(),...this.sessions.keys()].map((r)=>[r,t(r)])),i=(r)=>{let a=t(r.id);if(this.titleWrites.has(r.id)||a!==s.get(r.id))r.title=a??r.title},n=(await this.options.api.list(e)).map((r)=>this.preserveConnectedRuntimeModel(r));if(this.disposed)throw Error("Cloud session controller was disposed");this.lastListedOrganizationId=e,this.lastListedSessions=n;for(let r of n)i(r),this.knownSessions.set(r.id,r),this.unlistedSessions.delete(r.id);await Promise.all(Array.from(this.unlistedSessions.entries()).filter(([,r])=>r.organizationId===e).map(([r])=>this.getCrossScopeDiscoveryRecord(r)));let o=await Promise.all(n.map(async(r)=>{if(r.status!=="provisioning")return r;let a=await this.options.api.status(r.id).catch(()=>{return}),d=a?.status?.trim();if(!d)return r;return{...r,status:d,metadata:{...r.metadata,...St(a?.phase)?{provisioningPhase:a?.phase}:{},...a?.statusReason?.trim()?{statusReason:a.statusReason.trim()}:{}}}}));if(this.disposed)throw Error("Cloud session controller was disposed");for(let r of o){i(r),this.knownSessions.set(r.id,r);let a=this.sessions.get(r.id);if(a)a.title=r.title;if(a?.status==="provisioning"&&r.status!=="provisioning")a.status=r.status;let d=this.connections.get(r.id);if(d)d.remote=r;let u=R(r);if(u||r.status==="failed"||r.status==="suspended"){if(a)a.busy=!1,a.status=u?"expired":r.status,a.endedAt=u?Date.parse(r.expiredAt??"")||Date.now():Math.max(a.endedAt??0,Date.parse(r.lastActivityAt??r.createdAt)||0)||void 0;if(d)this.disposeConnection(r.id).catch(()=>{return})}}this.lastListedOrganizationId=e,this.lastListedSessions=o;for(let r of o)if(this.sessions.has(r.id))this.publishSnapshot(r.id);return V(o)}async handoffTargetExists(e){try{return await this.options.api.status(e),!0}catch(t){if(t instanceof w&&(t.code==="session_not_found"||t.code==="session_expired"))return!1;throw t}}preserveConnectedRuntimeModel(e){let t=this.connections.get(e.id)?.remote.metadata,s=t?.cwd??this.knownSessions.get(e.id)?.metadata.cwd;return{...e,metadata:{...e.metadata,...t?.modelId?{modelId:t.modelId}:{},...s?{cwd:s}:{}}}}async refreshOrganization(){await this.resolveActiveOrganizationId({fresh:!0})}async resolveActiveOrganizationId(e){return await this.options.getActiveOrganizationId?.(e)}async listRepositories(){return await this.options.api.listRepositories(await this.resolveActiveOrganizationId())}async listModels(){if(this.disposed)throw Error("Cloud session manager was disposed");let e=await this.resolveActiveOrganizationId({fresh:!0}),t=await Yi(this.options.apiBaseUrl,{isOrganizationSession:Boolean(e)});if(this.disposed)throw Error("Cloud session manager was disposed");return t}async prepareHandoffRepository(e){let t=await this.resolveActiveOrganizationId(),s=await this.options.api.listRepositories(t);if(!s.connected)throw new w("github_not_connected","Connect GitHub before handing this session off to cloud.",s.connectUrl);let i=(n)=>n.trim().replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();if(!s.repositories.some((n)=>i(n.url)===i(e)))throw new w("github_not_connected",`The GitHub integration cannot access ${e}. Grant repository access before handing off.`,s.connectUrl);return t?{organizationId:t}:{}}async listBranches(e,t={}){return await this.options.api.listBranches(e,await this.resolveActiveOrganizationId(),t)}async listForDiscovery(e={}){let t,s=(async()=>{let a=await this.resolveActiveOrganizationId();t={organizationId:a};let d=this.discoveryRefresh?.organizationId===a?this.discoveryRefresh?.promise:void 0;if(!d){let u=this.listInOrganization(a).finally(()=>{if(this.discoveryRefresh?.promise===u)this.discoveryRefresh=void 0});this.discoveryRefresh={organizationId:a,promise:u},d=u}return{organizationId:a,records:await d}})(),i=()=>t?{organizationId:t.organizationId,records:this.lastListedOrganizationId===t.organizationId?this.lastListedSessions:[]}:void 0,n;if(e.timeoutMs===void 0)n=await s;else{let a;try{n=await Promise.race([s.catch((d)=>{if(!(d instanceof w&&d.code==="authentication_required"))this.options.logger?.error?.("Cloud session discovery failed",{error:d});return i()}),new Promise((d)=>{a=setTimeout(()=>d(i()),Math.max(0,e.timeoutMs??0))})])}finally{if(a!==void 0)clearTimeout(a)}}if(!n)return[];let{organizationId:o,records:r}=n;return[...new Map([...Array.from(this.unlistedSessions.values()).filter((a)=>a.organizationId===o).map((a)=>a.record),...r].map((a)=>[a.id,a])).values()].map((a)=>{let d=wt(a),u=this.sessions.get(a.id);if(!u)return d;let p=u.title?.trim()||a.title?.trim();return{...d,status:u.status,prompt:u.prompt,endedAt:u.endedAt!==void 0?new Date(u.endedAt).toISOString():d.endedAt,metadata:{...d.metadata??{},title:hn({sessionId:a.id,metadata:p?{title:p}:void 0,prompt:u.prompt,messages:u.messages})}}})}async create(e){let t=e.requestId?.trim();if(!t)return await this.createOnce(e);let s=this.createRequests.get(t);if(s)return await s;let i=this.createOnce(e).finally(()=>{if(this.createRequests.get(t)===i)this.createRequests.delete(t)});return this.createRequests.set(t,i),await i}trackProvisioningController(e,t){let s=this.provisioningControllers.get(e);if(!s)s=new Set,this.provisioningControllers.set(e,s);return s.add(t),()=>{if(s.delete(t),s.size===0)this.provisioningControllers.delete(e)}}abortProvisioningControllers(e,t){let s=this.provisioningControllers.get(e);if(!s?.size)return!1;for(let i of s)i.abort(t);return!0}async waitUntilReady(e){this.detachedSessions.delete(e),this.assertSessionActive(e);let t=new AbortController,s=this.trackProvisioningController(e,t);try{await this.options.api.waitUntilReady(e,AbortSignal.any([t.signal,AbortSignal.timeout(610000)])),t.signal.throwIfAborted(),this.assertSessionActive(e),await this.refreshKnownSession(e)}finally{s()}}async seedHandoff(e,t){we(t.workspaceRelativePath),this.detachedSessions.delete(e);let s=await this.ensureConnection(e,{createInner:!0,handoffSeed:t});if(!s.innerSessionId)throw Error("Cloud Hub did not return an inner session id");return{innerSessionId:s.innerSessionId}}async verifyHandoffTranscript(e,t,s={}){let i=await this.ensureConnection(e),n=i.innerSessionId;if(!n)throw Error("Cloud Hub did not return an inner session id");let o=await i.client.command("session.messages",{sessionId:n},n);this.assertSessionActive(e,i);let r=o.payload?.messages;if(!Array.isArray(r))throw Error("Cloud runtime returned no transcript after seeding.");if(t.length>0&&r.length===0)throw new Ft;if(!(s.allowAppendedMessages?r.length>=t.length&&Le(t,r.slice(0,t.length)):Le(t,r)))throw new yt(t.length,r.length);i.transcriptKnown=!0;let a=this.sessions.get(e);if(a)a.messages=structuredClone(r),this.authoritativeMessages.set(e,structuredClone(r)),this.streamingMessages.delete(e),this.publishSnapshot(e,!0)}async createOnce(e){if(this.disposed)throw Error("Cloud session manager was disposed");let t=we(e.workspaceRelativePath),s=e.organizationId===void 0?await this.resolveActiveOrganizationId({fresh:!0}):e.organizationId??void 0,i=e.handoff,n=!i,o=await this.options.api.create({...e,organizationId:s,...i&&{handoff:{...i,onOuterSessionCreated:async(f,m)=>{n=m?.created===!0,await i.onOuterSessionCreated(f,m)}}}});if(!o?.sessionId?.trim())throw new w("request_failed","The cloud session service returned an unexpected response; please try again.");if(this.disposed){if(n&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(o.sessionId,o.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw Error("Cline account changed while the cloud session was starting")}let r={id:o.sessionId,sandboxType:e.sandboxType,status:o.status,sandboxUrl:o.sandboxUrl,repoContext:{repoUrl:e.repoUrl,...e.branch?.trim()?{branch:e.branch.trim()}:{}},metadata:{modelId:e.modelId,cwd:t},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};this.knownSessions.set(r.id,r),this.unlistedSessions.set(r.id,{record:r,organizationId:s});let{autoApproveTools:a,thinking:d,reasoningEffort:u,mode:p,workspaceRelativePath:l}=e;this.pendingInitialTasks.set(r.id,{autoApproveTools:a,thinking:d,reasoningEffort:u,mode:p??"act",workspaceRelativePath:l});let h=this.stateFromRecord(r);h.prompt=e.initialPrompt?.trim()||void 0,h.config.mode=e.mode??"act",this.sessions.set(r.id,h);let c;try{if(e.handoff){let f=await e.handoff.resolveMessages();this.assertSessionActive(r.id),c=(await this.seedHandoff(r.id,{sourceSessionId:e.handoff.sourceSessionId,messages:f,mode:e.mode,workspaceRelativePath:e.workspaceRelativePath,config:{autoApproveTools:e.autoApproveTools,thinking:e.thinking,reasoningEffort:e.reasoningEffort},onSeeding:e.handoff.onSeeding})).innerSessionId}}catch(f){if(this.disposed&&n&&this.options.lateCreateDisposition==="delete")await this.deleteProvisionedSessionAfterDispose(r.id,o.cleanupAuthToken,e.handoff?.onOuterSessionRemoved);throw f}return this.assertSessionActive(r.id),this.notify("chat_session_status",{sessionId:r.id,status:h.status}),{sessionId:r.id,origin:"cloud",executionTarget:"cloud",status:r.status,provider:"cline",model:e.modelId,repoUrl:e.repoUrl,branch:e.branch??"",cwd:t,workspaceRoot:b,...c?{innerSessionId:c}:{},...h.prompt?{prompt:h.prompt}:{}}}async deleteProvisionedSessionAfterDispose(e,t,s){this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),await this.options.api.delete(e,t).then(()=>s?.(e)).catch((i)=>{this.options.logger?.log("Failed to clean up a cloud session created during an account change",{sessionId:e,error:i})})}async attach(e,t){let s=this.sessionGenerations.get(e)??0;if(this.detachedSessions.delete(e),t)this.restoreCreationOptions(e,t);let i=await this.ensureKnownSession(e);if(this.assertSessionActive(e),s!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during attachment");if(!this.sessions.has(e))this.sessions.set(e,this.stateFromRecord(i));if(i.status==="provisioning"||i.status==="failed")return ge(i,i.status,this.sessions.get(e)?.prompt);if(R(i))return await this.disposeConnection(e),await this.attachExpired(i);let n;try{n=await this.ensureConnection(e)}catch(a){let d=await this.refreshKnownSession(e);if(d&&R(d))return await this.disposeConnection(e),await this.attachExpired(d);throw a}await this.ensureAttached(n);let o=n.remote,r=this.sessions.get(e);return ge(o,r?.status??o.status,r?.prompt)}async send(e,t,s,i,n,o){let r=this.sendAbortTokens.get(e),a=this.knownSessions.get(e);if(a&&R(a))throw new w("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");let d=await this.ensureConnection(e,{createInner:!0}),u=()=>this.disposed||d.disposed||this.deletingSessions.has(e)||this.sendAbortTokens.get(e)!==r,p=()=>{if(u())throw Error("Cloud session prompt cancelled")};if(p(),await d.reconnectResolution,p(),await this.ensureAttached(d),await d.reconnectResolution,p(),!d.transcriptKnown)await this.rehydrateAfterTransportDrop(e,d);p(),await this.updateModel(d,i),await d.reconnectResolution,p();let l=d.innerSessionId;if(!l)throw Error("Cloud Hub session was not initialized");let h=this.sessions.get(e),c=s??(h?.busy?"queue":void 0),f=K(h?.messages??[],h?.promptsInQueue??[],t),m=c!=="queue"&&c!=="steer",y=h&&c!=="queue"?{role:"user",content:[{type:"text",text:t}]}:void 0;if(h&&y)h.messages=[...h.messages,y];let S=()=>{if(h&&y)h.messages=h.messages.filter((g)=>g!==y),this.publishSnapshot(e)};if(h&&m){let g=h.status!=="running";if(h.busy=!0,h.status="running",g)this.publishSnapshot(e,!1,"status")}let _=new Set,q=!1,U=()=>{if(q||u())return;q=!0,this.publish({type:"prompt_accepted",sessionId:e,prompt:t,delivery:c})};try{let g=await d.client.command("session.send_input",{prompt:t,delivery:c,...n?.length?{attachments:{userImages:n}}:{}},l,{timeoutMs:c==="queue"?fn:null,onDispatch:(E)=>{_.add(E),d.pendingInputs??=new Map,d.pendingInputs.set(E,{clientId:d.client.getClientId(),ownsBusyState:m,accept:U})},beforeDispatch:()=>{if(p(),d.innerSessionId!==l)throw Error("The cloud session reconnected before the prompt could be sent. Please try again.");if(o?.beforeDispatch?.(),h&&m)h.prompt||=t;let E=this.knownSessions.get(e);if(E&&!E.title?.trim()&&!this.titleWrites.has(e)){let H=cs(t);if(H){if(E.title=H,h)h.title=H;let A=this.options.api.updateTitle?.(e,H).then(()=>{}).catch(()=>{}).finally(()=>{if(this.titleWrites.get(e)===A)this.titleWrites.delete(e)});if(A)this.titleWrites.set(e,A)}}}});U();let T=c==="queue"||c!=="steer"&&g.payload?.result===void 0;if(T)S();return{sessionId:e,ok:!0,...T?{queued:!0}:{},result:g.payload?.result}}catch(g){if(u())throw S(),g;if(pe(g)||fe(g,"session.send_input")){let T;try{T=await this.rehydrateAfterTransportDrop(e,d)}catch(E){if(p(),S(),h&&m)h.busy=!1,h.status="error";if(c==="queue")throw new Te;throw E}if(p(),c==="queue")throw new Te;if(c==="steer")throw new w("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");if(K(T.messages,Sn(T.prompts,T.submittedPrompts),t)<=f)throw new w("request_failed","Cline could not confirm whether this message was accepted. Check the cloud session before resending it.");return{sessionId:e,ok:!0,...c==="queue"?{queued:!0}:{},recoveredAfterDisconnect:!0,status:T.status}}if(S(),h&&m)h.busy=!1,h.status="error";throw this.publishSnapshot(e),g}finally{for(let g of _)d.pendingInputs?.delete(g)}}async updateModel(e,t){let s=t?.trim();if(!s||e.remote.metadata.modelId===s)return;let i=e.innerSessionId;if(!i)throw Error("Cloud Hub session was not initialized");await e.client.command("session.update_connection",{sessionId:i,updates:{modelId:s}},i,{beforeDispatch:()=>{if(this.assertSessionActive(e.remote.id,e),e.innerSessionId!==i)throw Error("The cloud session reconnected before the model could be changed. Please try again.")}}),this.assertSessionActive(e.remote.id,e),this.applyModel(e,s)}applyModel(e,t){e.remote.metadata.modelId=t;let s=this.sessions.get(e.remote.id);if(s)s.config.model=t,s.config.modelId=t}async rehydrateAfterTransportDrop(e,t){if(this.assertSessionActive(e,t),t.rehydrationPromise)return t.rehydrationRerunRequested=!0,await t.rehydrationPromise;let s=(async()=>{let i;do t.rehydrationRerunRequested=!1,i=await this.performTransportRehydration(e,t),this.assertSessionActive(e,t);while(t.rehydrationRerunRequested&&!this.disposed);return i})().finally(()=>{if(t.rehydrationPromise===s)t.rehydrationPromise=void 0,this.publishSnapshot(e)});return t.rehydrationPromise=s,await s}async performTransportRehydration(e,t){this.assertSessionActive(e,t);let s=t.innerSessionId;if(!s)throw Error("Cloud Hub session was not initialized");t.bufferingEvents=!0,t.bufferedEvents=[],t.bufferedEventsDropped=0;try{await this.ensureAttached(t),this.assertSessionActive(e,t);let i=await t.client.command("session.get",{includeSnapshot:!0},s);this.assertSessionActive(e,t);let n=i.payload?.session&&typeof i.payload.session==="object"&&!Array.isArray(i.payload.session)?i.payload.session:void 0;this.applySessionModel(t,n);let o=this.sessions.get(e),r=this.authoritativeMessages.get(e)??[],a=String(n?.status??o?.status??"running").trim(),d=a==="pending"?"running":a;if(d==="running"&&!t.transcriptKnown&&!t.pendingInputs?.size)t.externalRun??={progressHydrated:!0};let u=()=>t.client.command("session.messages",{sessionId:s},s),p=await u().catch((g)=>{if(!fe(g,"session.messages"))throw g;return this.assertSessionActive(e,t),u()});if(this.assertSessionActive(e,t),!Array.isArray(p.payload?.messages))throw Error("Cloud Hub returned an invalid transcript snapshot");let l=p.payload.messages,h=t.bufferedEventsDropped+t.bufferedEvents.length,c=await t.client.command("session.pending_prompts",{sessionId:s},s).catch(()=>{return});this.assertSessionActive(e,t);let f=t.bufferedEventsDropped+t.bufferedEvents.length;if(o){let g=o.status!==d;if(this.authoritativeMessages.set(e,structuredClone(l)),o.messages=structuredClone(l),this.streamingMessages.delete(e),o.status=d,o.busy=d==="running",g)if(d==="completed"||d==="failed"||d==="aborted")o.endedAt=Date.now(),this.notify("chat_session_ended",{sessionId:e,reason:d==="failed"?"error":d});else this.notify("chat_session_status",{sessionId:e,status:d})}let m=c!==void 0&&c.ok!==!1&&Array.isArray(c.payload?.prompts),y=m?this.applyQueueSnapshot(e,c):void 0;t.transcriptKnown=!0;let S=l;this.assertSessionActive(e,t),this.notify("cloud_session_rehydrated",{sessionId:e,status:d,transcriptKnown:!0,messages:S}),this.assertSessionActive(e,t);let _=t.bufferedEvents,q=Nt(_),U=cn(_,l,{queueSnapshotApplied:m,queueSnapshotEventCutoff:Math.max(0,f-t.bufferedEventsDropped),messagesSnapshotEventCutoff:Math.max(0,h-t.bufferedEventsDropped),baselineMessages:r});t.bufferedEvents=[],t.bufferingEvents=!1,t.syncFailureNotified=!1;for(let g of U)this.forwardEvent(e,t,g);return{status:d,messages:l,prompts:y,submittedPrompts:q}}catch(i){let n=t.bufferedEvents;t.bufferedEvents=[],t.bufferingEvents=!1,this.assertSessionActive(e,t);for(let o of n)this.forwardEvent(e,t,o);if(!t.syncFailureNotified)t.syncFailureNotified=!0,this.notify("cloud_session_sync_failed",{sessionId:e,message:i instanceof Error?i.message:String(i)});throw i}}async abort(e){if(this.sendAbortTokens.set(e,Symbol()),this.abortProvisioningControllers(e,Error("Cloud session prompt cancelled")))return{sessionId:e,ok:!0};let t=await this.ensureConnection(e),s=()=>{if(this.disposed||t.disposed)throw Error("Cloud session connection was disposed")};if(s(),await t.client.connect(),await t.reconnectResolution,s(),await this.resolveInnerSession(e,t),t.innerSessionId){await this.ensureAttached(t),await t.reconnectResolution,s();let n=t.innerSessionId;if(!n)throw Error("Cloud Hub session was not initialized");await t.client.command("run.abort",{sessionId:n},n,{beforeDispatch:()=>{if(s(),t.innerSessionId!==n)throw Error("The cloud session reconnected before Stop could be sent. Please try Stop again.")}})}s();let i=this.sessions.get(e);if(i)i.busy=!1,i.status="aborted";return this.publishSnapshot(e),{sessionId:e,ok:!0}}async pendingPrompts(e){if(this.knownSessions.get(e)?.status==="provisioning")return{sessionId:e,promptsInQueue:[]};if(!(await this.ensureConnection(e)).innerSessionId)return{sessionId:e,promptsInQueue:[]};let t=await this.queueCommand(e,"session.pending_prompts",{});return{sessionId:e,promptsInQueue:this.applyQueueSnapshot(e,t)}}async updatePendingPrompt(e,t,s){let i=await this.queueCommand(e,"session.update_pending_prompt",{promptId:t,...s});return{sessionId:e,updated:i.payload?.updated===!0,promptsInQueue:this.applyQueueSnapshot(e,i)}}async removePendingPrompt(e,t){let s=await this.queueCommand(e,"session.remove_pending_prompt",{promptId:t});return{sessionId:e,removed:s.payload?.removed===!0,promptsInQueue:this.applyQueueSnapshot(e,s)}}async queueCommand(e,t,s){let i=await this.ensureConnection(e),n=i.innerSessionId;if(!n)throw Error("Cloud Hub session was not initialized");await i.client.connect(),await i.reconnectResolution,await this.ensureAttached(i),await i.reconnectResolution;let o=await i.client.command(t,{sessionId:n,...s},n,{beforeDispatch:()=>{if(this.assertSessionActive(e,i),i.innerSessionId!==n)throw Error("The cloud session reconnected before the queue request could be sent. Refresh the queue and try again.")}});return this.assertSessionActive(e,i),o}applyQueueSnapshot(e,t){if(!Array.isArray(t.payload?.prompts))throw Error("Cloud Hub returned an invalid pending-prompts snapshot");let s=t.payload.prompts.map((n)=>({id:typeof n.id==="string"?n.id:"",prompt:typeof n.prompt==="string"?n.prompt:"",steer:n.delivery==="steer",attachmentCount:typeof n.attachmentCount==="number"?n.attachmentCount:0,userImages:Array.isArray(n.userImages)?n.userImages.filter((o)=>typeof o==="string"):void 0})).filter((n)=>n.id),i=this.sessions.get(e);if(i)i.promptsInQueue=s;return this.publishSnapshot(e,!1,"queue"),s}async readMessages(e){let t=this.knownSessions.get(e);if(t?.status==="provisioning"||t?.status==="failed")return[];if(t&&R(t))return await this.loadArchivedMessages(t)??[];try{let s=await this.ensureConnection(e);if(!s.innerSessionId)return[];return(await this.rehydrateAfterTransportDrop(e,s)).messages}catch(s){let i=await this.refreshKnownSession(e)??t;if(i){let n=await this.loadArchivedMessages(i).catch(()=>null);if(n!==null)return n}throw s}}async updateTitle(e,t){let s=this.titleWrites.get(e),i=(async()=>{await s?.catch(()=>{}),this.assertSessionActive(e),await this.options.api.updateTitle(e,t);let n=this.knownSessions.get(e);if(n)n.title=t;let o=this.sessions.get(e);if(o)o.title=t;this.publishSnapshot(e)})();this.titleWrites.set(e,i);try{await i}finally{if(this.titleWrites.get(e)===i)this.titleWrites.delete(e)}}async delete(e){this.deletingSessions.add(e),this.abortProvisioningControllers(e);try{let t=this.connectionPromises.get(e);if(t)await t.catch(()=>{return});await this.disposeConnection(e);try{await this.options.api.delete(e)}catch(s){let i=s instanceof w?s.code:"";if(i!=="session_not_found"&&i!=="session_expired")throw s}this.knownSessions.delete(e),this.unlistedSessions.delete(e),this.pendingInitialTasks.delete(e),this.sessions.delete(e),this.authoritativeMessages.delete(e),this.restoredOptions.delete(e),this.publish({type:"removed",sessionId:e}),this.sendAbortTokens.delete(e);for(let[s,i]of this.approvals)if(i.item.sessionId===e)this.approvals.delete(s)}finally{this.deletingSessions.delete(e)}}async dispose(){this.disposed=!0;for(let t of this.snapshotTimers.keys())this.cancelScheduledSnapshot(t);this.sendAbortTokens.clear();for(let t of this.provisioningControllers.values())for(let s of t)s.abort();this.provisioningControllers.clear();let e=new Set([...this.connections.keys(),...this.knownSessions.keys(),...this.sessions.keys()]);for(let[t,s]of this.approvals)if(e.has(s.item.sessionId))this.approvals.delete(t);for(let t of e)this.sessions.delete(t),this.knownSessions.delete(t),this.publish({type:"removed",sessionId:t});if(this.knownSessions.clear(),this.unlistedSessions.clear(),!this.options.pendingInitialTasks)this.pendingInitialTasks.clear();this.listeners.clear(),await Promise.allSettled(Array.from(this.connections.keys()).map((t)=>this.disposeConnection(t)))}async attachExpired(e){let t=this.sessions.get(e.id)??ye(e);return t.busy=!1,t.status="expired",this.sessions.set(e.id,t),await this.loadArchivedMessages(e).catch(()=>{return}),ge(e,"expired")}async loadArchivedMessages(e){let t=this.sessionGenerations.get(e.id),s=await this.options.api.history(e.id);if(this.assertSessionActive(e.id),this.sessionGenerations.get(e.id)!==t)throw Error("Cloud session attachment changed while loading history");if(s===null)return null;let i=this.sessions.get(e.id)??ye(e);return i.messages=structuredClone(s),this.sessions.set(e.id,i),this.authoritativeMessages.set(e.id,structuredClone(i.messages)),this.publishSnapshot(e.id,!0),s}async refreshKnownSession(e){let t=await this.resolveActiveOrganizationId(),s=await this.options.api.list(t).catch(()=>{return});if(this.disposed)throw Error("Cloud session manager was disposed");if(!s)return this.knownSessions.get(e);for(let i of s)this.knownSessions.set(i.id,i);return s.find((i)=>i.id===e)}async ensureKnownSession(e){let t=this.knownSessions.get(e);if(t)return t;let s=(await this.list()).find((i)=>i.id===e);if(!s)throw new w("session_not_found",`Cloud session ${e} was not found.`);return this.knownSessions.get(e)??structuredClone(s)}assertSessionActive(e,t){if(this.disposed||t?.disposed||this.detachedSessions.has(e)||t?.generation!==void 0&&t.generation!==(this.sessionGenerations.get(e)??0))throw Error("Cloud session connection was disposed");if(this.deletingSessions.has(e))throw new w("session_not_found","This cloud session is being deleted.")}async ensureConnection(e,t={}){let s=this.sessionGenerations.get(e)??0,i=()=>{if(this.assertSessionActive(e),s!==(this.sessionGenerations.get(e)??0))throw Error("Cloud viewer detached during connection")};i();let n=this.connectionPromises.get(e),o=n?await n:this.connections.get(e);if(o?.remote.status==="suspended")return await this.disposeConnection(e),i(),await this.ensureConnection(e,t);if(o){if(this.assertSessionActive(e,o),await o.reconnectResolution,this.assertSessionActive(e,o),!o.innerSessionId)await o.client.connect(),await o.reconnectResolution,this.assertSessionActive(e,o),await this.resolveInnerSession(e,o,Boolean(t.handoffSeed)),this.assertSessionActive(e,o);if(t.handoffSeed&&o.innerSessionId)await this.assertHandoffConnectionReusable(o,t.handoffSeed);if(t.createInner&&!o.innerSessionId)await this.createInnerSession(o,t.handoffSeed);return this.assertSessionActive(e,o),o}let r=(async()=>{let a=await this.ensureKnownSession(e);if(i(),!this.pendingInitialTasks.has(e)&&(a.sandboxType==="resumable"||a.metadata.sandboxType==="resumable"||a.status==="suspended")){let l=await this.options.api.status(e).catch(async(c)=>{if(!(c instanceof w?c.code==="request_failed"&&(c.status===void 0||c.status===408||c.status===429||c.status>=500):c instanceof TypeError||c instanceof Error&&c.name==="TimeoutError"))throw c;return i(),await this.refreshKnownSession(e).catch(()=>{return})});if(i(),l?.status)a.status=l.status;let h=this.sessions.get(e);if(h?.status==="suspended"&&["provisioning","ready","active"].includes(a.status))h.status=a.status,h.busy=!1,h.endedAt=void 0}if(a.status==="suspended"){let l=new AbortController,h=this.trackProvisioningController(e,l);try{try{a=await this.options.api.resume(e,l.signal)}catch(f){if(!(f instanceof w)||f.status!==409)throw f;i(),l.signal.throwIfAborted();let m=await this.options.api.status(e,{signal:l.signal});if(m.status!=="provisioning"&&m.status!=="ready"&&m.status!=="active")throw f;a={...a,status:m.status}}i(),l.signal.throwIfAborted(),this.knownSessions.set(e,a);let c=this.sessions.get(e);if(c)c.status=a.status,c.busy=!1,c.endedAt=void 0;this.publishSnapshot(e,!1,"status")}finally{h()}}if(a.status==="provisioning"){let l=new AbortController,h=this.trackProvisioningController(e,l);try{if(await this.options.api.waitUntilReady(e,l.signal,({phase:f})=>{a.metadata.provisioningPhase=f,this.notify("chat_session_status",{sessionId:e,status:"provisioning",phase:f})}),this.disposed)throw Error("Cloud session manager was disposed");if(a=await this.refreshKnownSession(e)??a,l.signal.throwIfAborted(),a.status==="provisioning")a.status="ready";let c=this.sessions.get(e);if(c?.status==="provisioning")c.status="idle",c.busy=!1,c.endedAt=void 0}catch(c){if(c instanceof w&&c.code==="session_failed"){if(a.status="failed",a.metadata.statusReason=c.detail,a.metadata.provisioningPhase="failed",!this.disposed)this.knownSessions.set(e,a);let f=this.sessions.get(e);if(f)f.status="error";this.notify("chat_session_status",{sessionId:e,status:"error"})}throw c}finally{h()}}if(i(),a.status==="failed")throw new w("session_failed",a.metadata.statusReason||"The cloud sandbox could not be prepared.");if(R(a))throw new w("session_expired","This cloud session has expired; its sandbox is gone. Start a new cloud session to continue.");this.sessions.set(e,this.sessions.get(e)??this.stateFromRecord(a));let d,u=0,p=this.createHubClient({url:vn(this.options.apiBaseUrl,e),clientId:`${this.options.clientIdentity?.prefix??"cloud"}-${e}-${ps()}`,clientType:this.options.clientIdentity?.type??"cloud-client",displayName:this.options.clientIdentity?.displayName??"Cline cloud session",workspaceRoot:b,cwd:b,resolveConnectionHeaders:async()=>{i();let l=u>0;if(u+=1,d)d.connected=!1,d.reconnecting=l,this.publishSnapshot(e);if(l){let c=d;if(c&&!c.disposed){c.transcriptKnown=!1,c.innerSessionId=void 0;let f=(async()=>{if(await this.resolveInnerSession(e,c),c.innerSessionId)await this.rehydrateAfterTransportDrop(e,c)})().catch(()=>this.disposeConnectionIfSessionGone(e,c)).finally(()=>{if(c.reconnectResolution===f)c.reconnectResolution=void 0,c.connected=c.transcriptKnown,this.publishSnapshot(e)});c.reconnectResolution=f}}let h=await this.options.getAuthToken();if(!h?.trim())throw new w("authentication_required","Sign in to Cline to reconnect this cloud session.");return i(),{Authorization:`Bearer ${h.trim()}`}}});d={generation:s,remote:a,client:p,bufferedEvents:[],bufferedEventsDropped:0,transcriptKnown:!1,seenEventIds:new Set,unsubscribe:()=>{}},d.unsubscribe=p.subscribe(()=>{},{sessionId:a.metadata.taskId?.trim()||e}),this.connections.set(e,d);try{if(await p.connect(),d.connected=!0,this.publishSnapshot(e),this.assertSessionActive(e,d),await this.resolveInnerSession(e,d,Boolean(t.handoffSeed)),this.assertSessionActive(e,d),t.handoffSeed&&d.innerSessionId)await this.assertHandoffConnectionReusable(d,t.handoffSeed);if(t.createInner&&!d.innerSessionId)await this.createInnerSession(d,t.handoffSeed);return this.assertSessionActive(e,d),d}catch(l){if(pe(l)&&!this.disposed&&!d.disposed&&!this.deletingSessions.has(e))throw l;if(this.connections.get(e)===d)this.connections.delete(e);if(d.disposed=!0,d.unsubscribe(),!this.disposed&&s===(this.sessionGenerations.get(e)??0))this.clearPendingApprovals(e);throw await p.dispose().catch(()=>{return}),l}})().finally(()=>{if(this.connectionPromises.get(e)===r)this.connectionPromises.delete(e)});return this.connectionPromises.set(e,r),await r}async resolveInnerSession(e,t,s=!1){if(this.assertSessionActive(e,t),t.innerSessionId)return;let i=t.remote.metadata.taskId?.trim(),n;if(i)try{let a=await t.client.command("session.get",{sessionId:i},i);this.assertSessionActive(e,t),n=a.payload?.session&&typeof a.payload.session==="object"&&!Array.isArray(a.payload.session)?a.payload.session:void 0}catch(a){if(!Ve(a))throw a}else{let a=await t.client.command("session.list",{limit:100});this.assertSessionActive(e,t),n=ue(a.payload).filter(he).sort((d,u)=>lt(u)-lt(d))[0]}let o=String(n?.sessionId??"").trim();if(!o||!n){if(!s&&!this.pendingInitialTasks.has(e))throw Error("This cloud session's task is unavailable. Start a new cloud session to continue.");return}if(t.remote.sandboxType==="resumable"||t.remote.metadata.sandboxType==="resumable")await this.restoreSavedInnerSession(t,o,n),this.assertSessionActive(e,t);this.pendingInitialTasks.delete(e),t.innerSessionId=o,this.subscribeToInnerSession(e,t);let r=ut(n);if(r)this.applyModel(t,r);await this.ensureAttached(t)}async restoreSavedInnerSession(e,t,s){let i=()=>e.client.command("session.update_connection",{sessionId:t,updates:{}},t);try{await i();return}catch(f){if(!(Ve(f)||f instanceof Error&&f.code==="command_failed"&&f.message===`session not found: ${t}`))throw f}this.assertSessionActive(e.remote.id,e);let n=await e.client.command("session.messages",{},t);this.assertSessionActive(e.remote.id,e);let o=n.payload?.messages;if(!Array.isArray(o)||o.length===0)throw Error("The saved conversation is empty or unavailable.");let r=s.metadata??{},a=s.runtimeOptions??{},d=this.sessions.get(e.remote.id)?.config,u=Object.hasOwn(r,"thinking")?r.thinking:d?.thinking,p=Object.hasOwn(r,"reasoningEffort")?r.reasoningEffort:d?.reasoningEffort,l=typeof r.autoApproveTools==="boolean"?r.autoApproveTools:d?.autoApproveTools,h=s.cwd??s.workspaceRoot??b,c=s.workspaceRoot??b;try{let f=await e.client.command("session.create",{workspaceRoot:c,cwd:h,initialMessages:o,metadata:{...r,interactive:!0},sessionConfig:{sessionId:t,providerId:r.provider??"cline",modelId:r.model??r.modelId??e.remote.metadata.modelId,workspaceRoot:c,cwd:h,systemPrompt:a.systemPrompt??r.systemPrompt??"",mode:a.mode??r.mode??"act",...typeof u==="boolean"?{thinking:u}:{},...typeof p==="string"?{reasoningEffort:p}:{},...r.checkpointEnabled===!0?{checkpoint:{enabled:!0}}:{}},runtimeOptions:a,...typeof l==="boolean"?{toolPolicies:{"*":{autoApprove:l}}}:{}});if(this.assertSessionActive(e.remote.id,e),(f.payload?.session?.sessionId??f.payload?.sessionId)!==t)throw Error("Cloud Hub did not restore the requested session.")}catch(f){if(f?.code!=="session_already_exists")throw f;this.assertSessionActive(e.remote.id,e),await i()}}async assertHandoffConnectionReusable(e,t){let s=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let i=ue(s.payload).filter(he),[n]=i;if(i.length!==1||String(n?.sessionId??"").trim()!==e.innerSessionId||mt(n)!==t.sourceSessionId)throw new w("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.")}async createInnerSession(e,t){if(this.assertSessionActive(e.remote.id,e),e.innerSessionCreation){if(await e.innerSessionCreation,t)await this.assertHandoffConnectionReusable(e,t);return}let s=(async()=>{if(t&&await this.adoptExistingHandoffSession(e,t)){this.unconfirmedInnerCreates.delete(e.remote.id);return}if(t?.recoverOnly||this.unconfirmedInnerCreates.has(e.remote.id))throw new w("request_failed","Cloud conversation creation is still unconfirmed. Wait for it to appear before trying again.");await this.createInnerSessionOnce(e,t)})().finally(()=>{e.innerSessionCreation=void 0});return e.innerSessionCreation=s,await s}async adoptExistingHandoffSession(e,t){let s=await e.client.command("session.list",{limit:100});this.assertSessionActive(e.remote.id,e);let i=ue(s.payload).filter(he);if(i.length===0)return!1;let[n]=i,o=String(n?.sessionId??"").trim();if(i.length!==1||!o||mt(n)!==t.sourceSessionId)throw new w("request_failed","This cloud workspace already contains another conversation. Open it in Cline Cloud or delete it before retrying the handoff.");return e.innerSessionId=o,this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,n),await this.ensureAttached(e),!0}async createInnerSessionOnce(e,t){let s=e.remote.metadata.modelId?.trim();if(!s)throw Error("Cloud session is missing its model id");let i=this.sessions.get(e.remote.id),n=this.pendingInitialTasks.get(e.remote.id)??this.restoredOptions.get(e.remote.id),o=we(t?.workspaceRelativePath??n?.workspaceRelativePath),r=t?.mode??n?.mode??"act";try{await t?.onSeeding?.(),this.assertSessionActive(e.remote.id,e)}catch(m){if(t)throw new _e(m);throw m}let a=yn(e.remote),d=t?.config?.thinking??i?.config.thinking,u=t?.config?.reasoningEffort??i?.config.reasoningEffort,p=!1,l=e.client.command("session.create",{workspaceRoot:b,cwd:o,...t?{initialMessages:t.messages}:{},sessionConfig:{...e.remote.metadata.taskId?.trim()?{sessionId:e.remote.metadata.taskId.trim()}:{},providerId:"cline",modelId:s,workspaceRoot:b,cwd:o,systemPrompt:t?`${Gt}
|
|
18
|
+
|
|
19
|
+
This session was handed off from a local workspace to a fresh Linux clone of ${e.remote.repoContext.repoUrl??"the repository"}@${e.remote.repoContext.branch??"the selected branch"} at ${b}. Earlier transcript references to the local OS, absolute paths, environment, and tool availability are stale.`+(o===b?"":`
|
|
20
|
+
|
|
21
|
+
Continue from the original repository subdirectory at ${o}.`):a,mode:r,enableTools:!0,...typeof d==="boolean"?{thinking:d}:{},...typeof u==="string"?{reasoningEffort:u}:{}},metadata:{source:this.options.clientIdentity?.source??"sdk",provider:"cline",model:s,interactive:!0,thinking:d??null,reasoningEffort:d===!1?null:u??null,...t?{handoff:{from:"local",sourceSessionId:t.sourceSessionId,outerSessionId:e.remote.id}}:{}},runtimeOptions:{mode:r},modelSelection:{provider:"cline",model:s},toolPolicies:{"*":{autoApprove:(t?.config?.autoApproveTools??i?.config.autoApproveTools)!==!1}}},void 0,{beforeDispatch:()=>this.assertSessionActive(e.remote.id,e),onDispatch:()=>{p=!0}}),h;try{h=await l}catch(m){if(t&&!p)throw new _e(m);if(t&&(fe(m,"session.create")||pe(m)))this.unconfirmedInnerCreates.add(e.remote.id);throw m}this.assertSessionActive(e.remote.id,e);let c=h.payload?.session&&typeof h.payload.session==="object"?h.payload.session:void 0,f=String(c?.sessionId??h.payload?.sessionId??"").trim();if(!f){if(t)this.unconfirmedInnerCreates.add(e.remote.id);throw Error("Cloud Hub did not return an inner session id")}if(this.unconfirmedInnerCreates.delete(e.remote.id),this.pendingInitialTasks.delete(e.remote.id),e.innerSessionId=f,e.remote.metadata.cwd=o,i)i.config.cwd=o,i.config.mode=r;this.subscribeToInnerSession(e.remote.id,e),this.applySessionModel(e,c),e.transcriptKnown=!t}handleEvent(e,t,s){if(this.disposed||t.disposed)return;if(t.innerSessionId&&s.sessionId&&s.sessionId!==t.innerSessionId)return;let i=s.eventId?.trim();if(i&&!(s.event==="approval.requested"&&s.sequence===void 0)){if(t.seenEventIds.has(i))return;t.seenEventIds.add(i);while(t.seenEventIds.size>wn){let n=t.seenEventIds.values().next().value;if(n)t.seenEventIds.delete(n)}}if(t.bufferingEvents){if(t.bufferedEvents.push(s),t.bufferedEvents.length>mn)t.bufferedEvents.shift(),t.bufferedEventsDropped+=1,this.options.logger?.log("Cloud sync event buffer reached its limit",{sessionId:e,severity:"warn"});return}this.forwardEvent(e,t,s)}forwardEvent(e,t,s){if(this.disposed||t.disposed)return;if(s.event==="session.attached"||s.event==="session.updated"||s.event==="session.created")this.applySessionModel(t,s.payload?.session);if(s.event==="approval.requested"){this.handleApprovalRequested(e,t,s);return}if(s.event==="approval.resolved"){let r=String(s.payload?.approvalId??"").trim();if(r)this.removeApproval(e,r);return}if(s.event==="run.started"){let r=this.sessions.get(e)?.busy,a=s.payload?.requestId,d=typeof a==="string"?t.pendingInputs?.get(a):void 0;if(d&&s.payload?.clientId===d.clientId){if(d.accept(),d.ownsBusyState)t.externalRun=void 0}else if(typeof s.payload?.clientId==="string")t.externalRun??={progressHydrated:Boolean(r)}}let i=t.externalRun,n=s.event==="run.completed"||s.event==="run.failed"||s.event==="run.aborted",o=i&&!i.progressHydrated&&(s.event==="assistant.delta"||s.event==="reasoning.delta"||s.event==="tool.started");if(i&&(o||n)){if(i.progressHydrated=!0,n)t.externalRun=void 0;let r=Boolean(t.rehydrationPromise);if(this.rehydrateAfterTransportDrop(e,t).catch((a)=>{if(this.disposed||t.disposed)return;this.notify("cloud_session_sync_failed",{sessionId:e,message:a instanceof Error?a.message:"Cloud transcript refresh failed"})}),!r){t.bufferedEvents.push(s);return}}if(this.applyLiveEvent(e,s),this.publish({type:"hub_event",sessionId:e,event:{...s,sessionId:e}}),s.event==="assistant.delta"||s.event==="reasoning.delta"||s.event==="tool.updated")this.scheduleSnapshot(e);else this.publishSnapshot(e)}handleApprovalRequested(e,t,s){this.storePendingApproval(e,t,s.payload),this.sendApprovalSnapshot(e)}storePendingApproval(e,t,s){let i=String(s?.approvalId??"").trim();if(!i)return;let n=`${e}:${i}`,o={approvalId:i,requestId:n,sessionId:e,createdAt:new Date(typeof s?.createdAt==="number"?s.createdAt:Date.now()).toISOString(),toolCallId:String(s?.toolCallId??""),toolName:String(s?.toolName??"tool"),input:bn(s?.inputJson),iteration:typeof s?.iteration==="number"?s.iteration:void 0,agentId:typeof s?.agentId==="string"?s.agentId:void 0,conversationId:typeof s?.conversationId==="string"?s.conversationId:void 0};this.approvals.set(n,{item:o,resolve:async(r)=>{if(this.disposed||t.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");if(await this.ensureAttached(t),this.disposed||t.disposed)throw Error("This cloud session connection is closed; reopen the session to respond.");await t.client.command("approval.respond",{approvalId:i,approved:r.approved,reason:r.reason},t.innerSessionId)}})}removeApproval(e,t){this.approvals.delete(`${e}:${t}`),this.sendApprovalSnapshot(e)}clearPendingApprovals(e){for(let[t,s]of this.approvals)if(s.item.sessionId===e)this.approvals.delete(t);this.sendApprovalSnapshot(e)}sendApprovalSnapshot(e){this.notify("tool_approval_state",{sessionId:e,items:Array.from(this.approvals.values()).filter((t)=>t.item.sessionId===e).map((t)=>t.item)})}async ensureAttached(e){if(this.assertSessionActive(e.remote.id,e),!e.innerSessionId)return;let t=await e.client.command("session.attach",{sessionId:e.innerSessionId},e.innerSessionId);this.assertSessionActive(e.remote.id,e),this.applySessionModel(e,t.payload?.session)}subscribeToInnerSession(e,t){let s=t.innerSessionId;if(!s)return;t.unsubscribe(),this.clearPendingApprovals(e),t.unsubscribe=t.client.subscribe((i)=>this.handleEvent(e,t,i),{sessionId:s})}applySessionModel(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return;let s=ut(t);if(s)this.applyModel(e,s);let i=t,n=typeof i.cwd==="string"&&W.normalize(i.cwd)===i.cwd&&(i.cwd===b||i.cwd.startsWith(`${b}/`))?i.cwd:void 0;if(n){e.remote.metadata.cwd=n;let a=this.sessions.get(e.remote.id);if(a)a.config.cwd=n}let o=this.sessions.get(e.remote.id),r=i.runtimeOptions?.mode;if(o&&(r==="act"||r==="plan"||r==="yolo"||r==="zen"))o.config.mode=r}async disposeConnection(e){this.cancelScheduledSnapshot(e);let t=this.connections.get(e);if(this.connections.delete(e),!t)return;t.disposed=!0,t.pendingInputs?.clear(),t.unsubscribe(),this.clearPendingApprovals(e),await t.client.dispose()}async disposeConnectionIfSessionGone(e,t){if(t.disposed||this.disposed)return;let s;try{s=await this.resolveActiveOrganizationId()}catch{return}let i=await this.options.api.list(s).catch(()=>{return});if(!i||t.disposed)return;let n=i.find((r)=>r.id===e),o=n?this.preserveConnectedRuntimeModel(n):void 0;if(!o){await this.disposeConnection(e).catch(()=>{return});return}if(this.knownSessions.set(e,o),t.remote=o,o.status==="failed"||o.status==="suspended"){let r=this.sessions.get(e);if(r)r.busy=!1,r.status=o.status,r.endedAt=Date.parse(o.updatedAt)||Date.now();await this.disposeConnection(e).catch(()=>{return});return}if(R(o))await this.attachExpired(o).catch(()=>{return}),await this.disposeConnection(e).catch(()=>{return})}}class Cn{getConnection;snapshots=new Map;records=new Map;listeners=new Set;unsubscribe;connection;disposed=!1;serviceId;scopeGeneration=-1;revision=-1;sessionRevisions=new Map;constructor(e){this.getConnection=e}async ready(){if(this.disposed)throw Error("Cloud viewer is disposed");if(!this.connection){let e=this.getConnection().then(async(t)=>{if(this.disposed)throw Error("Cloud viewer is disposed");this.unsubscribe=t.subscribe((s)=>{if(s.event==="cloud.event")this.recover(s.payload)});try{let s=await t.command("cloud.watch");return this.checkReply(s),this.recover(s.payload),t}catch(s){throw this.unsubscribe?.(),this.unsubscribe=void 0,s}});this.connection=e,e.catch(()=>{if(this.connection===e)this.connection=void 0})}return this.connection}async connect(){await this.ready()}recover(e){if(this.disposed||!this.acceptVersion(e))return;let t=Number(e?.revision);if(Array.isArray(e?.snapshots)){let s=e.snapshots,i=new Set(s.map((n)=>n.sessionId));for(let n of this.snapshots.keys())if((!e.sessionId||e.sessionId===n)&&!i.has(n))this.receive({type:"removed",sessionId:n},t);for(let n of s)this.receive({type:"snapshot",sessionId:n.sessionId,snapshot:n,replace:!0},t)}else this.receive(e?.event,t)}acceptVersion(e){if(typeof e?.serviceId!=="string"||typeof e.revision!=="number")return!1;if(e.serviceId===this.serviceId&&Number(e.scopeGeneration)<this.scopeGeneration)return!1;if(e.serviceId!==this.serviceId||e.scopeGeneration!==this.scopeGeneration){for(let t of this.snapshots.keys())this.receive({type:"removed",sessionId:t});this.records.clear(),this.sessionRevisions.clear(),this.serviceId=e.serviceId,this.scopeGeneration=Number(e.scopeGeneration),this.revision=-1}return this.revision=Math.max(this.revision,e.revision),!0}checkReply(e){if(!e.ok)throw Error(e.error?.message??"Cloud hub request failed")}receive(e,t=this.revision){if(this.disposed||!e)return;if(t<(this.sessionRevisions.get(e.sessionId)??-1))return;if(this.sessionRevisions.set(e.sessionId,t),e.type==="snapshot")this.snapshots.set(e.sessionId,structuredClone(e.snapshot));if(e.type==="removed")this.snapshots.delete(e.sessionId),this.records.delete(e.sessionId);let s=V(e);for(let i of this.listeners)i(s)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async call(e,t){let s=this.serviceId?{serviceId:this.serviceId,scopeGeneration:this.scopeGeneration}:void 0,i=await this.ready();if(this.disposed)throw Error("Cloud viewer is disposed");let n=s??{serviceId:this.serviceId,scopeGeneration:this.scopeGeneration},o=()=>n.serviceId===this.serviceId&&n.scopeGeneration===this.scopeGeneration,r=!1,a=await i.command("cloud.command",{operation:e,args:t,scope:n},void 0,{timeoutMs:["create","send","attach"].includes(e)?null:void 0,beforeDispatch:()=>{if(this.disposed)throw Error("Cloud viewer is disposed");if(!o())throw Error("Cloud account changed before request");if(r)throw Error("Cloud request outcome is unknown; reconnect before retrying")},onDispatch:()=>{r=!0}});if(this.checkReply(a),!o()||a.payload?.serviceId!==n.serviceId||a.payload?.scopeGeneration!==n.scopeGeneration||!this.acceptVersion(a.payload))throw Error("Cloud account changed during request");if(this.disposed)throw Error("Cloud viewer is disposed");return a.payload?.result}create(...e){return this.call("create",e)}attach(...e){return this.call("attach",e)}send(...e){return this.call("send",e)}refreshOrganization(){return this.call("refreshOrganization",[])}abort(...e){return this.call("abort",e)}pendingPrompts(...e){return this.call("pendingPrompts",e)}updatePendingPrompt(...e){return this.call("updatePendingPrompt",e)}removePendingPrompt(...e){return this.call("removePendingPrompt",e)}readMessages(...e){return this.call("readMessages",e)}updateTitle(...e){return this.call("updateTitle",e)}delete(...e){return this.call("delete",e)}listModels(...e){return this.call("listModels",e)}listRepositories(...e){return this.call("listRepositories",e)}listBranches(...e){return this.call("listBranches",e)}respondApproval(...e){return this.call("respondApproval",e)}restoreCreationOptions(...e){return this.call("restoreCreationOptions",e)}getCrossScopeDiscoveryRecord(...e){return this.call("getCrossScopeDiscoveryRecord",e)}async list(){return await this.call("list",[])}async listForDiscovery(...e){let t=await this.call("listForDiscovery",e);for(let s of t)this.records.set(String(s.sessionId),structuredClone(s));return t}getCachedDiscoveryRecord(e){let t=this.records.get(e);return t?structuredClone(t):void 0}getSnapshot(e){let t=this.snapshots.get(e);return t?structuredClone(t):void 0}isCloudSession(e){return e.trim().startsWith("ses-")||this.records.has(e)||this.snapshots.has(e)}async dispose(){this.disposed=!0,this.unsubscribe?.(),this.unsubscribe=void 0;for(let e of this.snapshots.keys())for(let t of this.listeners)t({type:"removed",sessionId:e});this.snapshots.clear(),this.records.clear(),this.listeners.clear()}}var lo=["create","attach","send","abort","pendingPrompts","updatePendingPrompt","removePendingPrompt","readMessages","updateTitle","delete","list","listForDiscovery","getCrossScopeDiscoveryRecord","listModels","listRepositories","listBranches","respondApproval","restoreCreationOptions","refreshOrganization"];export{lo as CLOUD_HUB_OPERATIONS,Gt as CLOUD_SESSION_SYSTEM_PROMPT,vt as CloudCreationUnconfirmedError,bt as CloudHandoffCreationRejectedError,k as CloudHandoffGitPreflightError,_e as CloudHandoffSeedRejectedError,Ft as CloudHandoffSeedUnsupportedError,yt as CloudHandoffTranscriptMismatchError,Te as CloudQueueUnconfirmedError,hs as CloudSessionApi,In as CloudSessionController,w as CloudSessionError,Cn as HubCloudSessionClient,Bn as buildCloudHandoffDashboardUrl,yn as buildCloudSessionSystemPrompt,Dn as clearCloudHandoffMetadata,Mn as cloudHandoffFingerprintsEqual,Le as cloudHandoffTranscriptsEqual,wt as cloudSessionToDiscoveryRecord,K as countPromptOccurrences,is as createCloudHandoffFingerprint,cs as deriveCloudSessionTitle,gn as isCloudOuterSessionId,he as isRootSessionRow,Yi as loadCloudModels,On as mergeCloudHandoffMetadata,ze as normalizeGitHubRemoteUrl,De as normalizeSessionTitle,St as parseCloudProvisioningPhase,Hn as preflightCloudHandoffGit,Un as readCloudHandoffMetadata,ue as readSessionRows,cn as reconcileBufferedCloudEvents,hn as resolveSessionListTitle,ut as sessionRowModelId,Lt as stringifyMessageContent,Nt as submittedPromptsFromEvents,lt as updatedAt};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pl}from"./index-d96n0s70.js";import{ct}from"./index-28c7m0fv.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-dx8bd4wq.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-m1gpa2eg.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-5j92dtg5.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-nqjnz7m4.js");return t(c(e))});return{operations:{language:(t)=>r(t)}}}async function V(e){let r=await ct(e),t=pl({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{Kl,zr,Rn,Jl}from"./index-yrnwqsdt.js";import{Vl}from"./index-6akf3a5d.js";import{createRequire as d}from"module";var i=d(import.meta.url),u=class extends Vl{ClientClass;constructor(e){super();this.ClientClass=e}createClient(e,r,a){let t=this.mergeModelParams(r,a);return{client:new this.ClientClass(Kl(e,r.modelVersion),e.destination),mergedParams:Rn(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)=>Jl(t.embedding))}extractResponseMetadata(e){return zr(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{Kl,Hl,Ql}from"./index-yrnwqsdt.js";import{Gs}from"./index-sw74pcm3.js";import{createRequire as p}from"module";var g=p(import.meta.url),m=[...Gs.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 Gs{ClientClass;constructor(t){super();this.ClientClass=t}buildRequest(t,s,o,e){let a=[],n=Ql(o.tools);a.push(...n.warnings);let{responseFormat:r,warning:l}=Hl(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=Kl(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{Rc}from"./index-71ym4q6s.js";import{O}from"./index-eh83hr16.js";import{i,c}from"./index-mcnngj50.js";var d=i(function(r){Object.defineProperty(r,"__esModule",{value:!0});r.getMachineId=void 0;var n=c("fs"),u=Rc(),t=O();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{Oc}from"./index-h7gn5v3f.js";import{O}from"./index-eh83hr16.js";import{i,c}from"./index-mcnngj50.js";var d=i(function(r){Object.defineProperty(r,"__esModule",{value:!0});r.getMachineId=void 0;var n=c("fs"),u=Oc(),t=O();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{Rc}from"./index-71ym4q6s.js";import{O}from"./index-eh83hr16.js";import{i}from"./index-mcnngj50.js";var o=i(function(r){Object.defineProperty(r,"__esModule",{value:!0});r.getMachineId=void 0;var d=Rc(),u=O();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{Oc}from"./index-h7gn5v3f.js";import{O}from"./index-eh83hr16.js";import{i}from"./index-mcnngj50.js";var o=i(function(r){Object.defineProperty(r,"__esModule",{value:!0});r.getMachineId=void 0;var d=Oc(),u=O();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{O}from"./index-eh83hr16.js";import{i,c}from"./index-mcnngj50.js";var u=i(function(t){Object.defineProperty(t,"__esModule",{value:!0});t.getMachineId=void 0;var s=c("fs"),d=O();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{O}from"./index-eh83hr16.js";import{i,c}from"./index-mcnngj50.js";var u=i(function(t){Object.defineProperty(t,"__esModule",{value:!0});t.getMachineId=void 0;var s=c("fs"),d=O();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();
|
package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-nckraycx.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{O}from"./index-eh83hr16.js";import{i}from"./index-mcnngj50.js";var r=i(function(e){Object.defineProperty(e,"__esModule",{value:!0});e.getMachineId=void 0;var d=O();async function n(){d.diag.debug("could not read machine-id: unsupported platform");return}e.getMachineId=n});export default r();
|
package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-w91yq3tm.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{O}from"./index-eh83hr16.js";import{i}from"./index-mcnngj50.js";var r=i(function(e){Object.defineProperty(e,"__esModule",{value:!0});e.getMachineId=void 0;var d=O();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{Rc}from"./index-71ym4q6s.js";import{O}from"./index-eh83hr16.js";import{i,c}from"./index-mcnngj50.js";var p=i(function(n){Object.defineProperty(n,"__esModule",{value:!0});n.getMachineId=void 0;var s=c("process"),o=Rc(),d=O();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{Oc}from"./index-h7gn5v3f.js";import{O}from"./index-eh83hr16.js";import{i,c}from"./index-mcnngj50.js";var p=i(function(n){Object.defineProperty(n,"__esModule",{value:!0});n.getMachineId=void 0;var s=c("process"),o=Oc(),d=O();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{ct}from"./index-28c7m0fv.js";import{gl}from"./index-j8r18nfg.js";import"./index-bzy863k0.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 ct(r),a=gl({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};
|