@cline/core 0.0.94-nightly.1792204233 → 0.0.95

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.
@@ -5,7 +5,7 @@ import{execFile as rn}from"node:child_process";import{basename as Do,resolve as
5
5
  ...and ${u.length-5} more`:"";throw new _("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
6
6
 
7
7
  ${g}${y}`)}let i;try{i=await t.symbolicBranch()}catch(u){let g=Q(u)===1,y=K(u),w=g?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new _(g?"detached_head":"git_command_failed",y?`${w} (${y})`:w,{cause:u})}if(!i)throw new _("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[r,a,d]=await Promise.all([O(()=>t.branchRemote(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),O(()=>t.branchMergeRef(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),O(t.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!r||r==="."||!a.startsWith("refs/heads/"))throw new _("missing_upstream",`Branch ${i} has no remote branch upstream. Push it with -u before handing off.`);let l=a.slice(11),f=r;if(!et(r))try{f=await t.remoteUrl(r)}catch{throw new _("missing_upstream","Could not resolve the upstream remote.")}let c=et(f);if(!c)throw new _("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let h;try{h=await t.remoteRefs(r,a)}catch(u){let g=Q(u)===2,y=g?`The upstream branch ${l} was not found. Push it before handing off.`:"Could not verify the remote branch. Check your network and GitHub authentication, then try again.";throw new _(g?"remote_branch_missing":"git_command_failed",y)}let p=ln(h,l);if(!p)throw new _("remote_branch_missing",`The upstream branch ${l} was not found. Push it before handing off.`);if(p.toLowerCase()!==d.toLowerCase())throw new _("unpushed_commits",`Local HEAD does not match the upstream branch ${l}. Push the current commit before handing off.`);return{repoUrl:c,branch:l,headSha:d,...s?{workspaceRelativePath:s}:{}}}function pe(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function x(e){if(typeof e!=="string")return;return e.trim()||void 0}function fn(e){return typeof e==="string"&&e.length>0?e:void 0}function hn(e){let t=x(e.repoUrl),n=x(e.branch),s=x(e.headSha),o=x(e.modelId);if(!t||!n||!s||!o)throw Error("Cloud handoff fingerprint fields cannot be empty.");let i=x(e.organizationId),r=fn(e.workspaceRelativePath),a=e.mode;return{repoUrl:t,branch:n,headSha:s,modelId:o,...i?{organizationId:i}:{},...r?{workspaceRelativePath:r}:{},...a?{mode:a}:{}}}function Jo(e,t){return e!==void 0&&t!==void 0&&e.repoUrl===t.repoUrl&&e.branch===t.branch&&e.headSha.toLowerCase()===t.headSha.toLowerCase()&&e.modelId===t.modelId&&e.organizationId===t.organizationId&&e.workspaceRelativePath===t.workspaceRelativePath&&e.mode===t.mode}function mn(e){let t=pe(e);if(!t||typeof t.repoUrl!=="string"||typeof t.branch!=="string"||typeof t.headSha!=="string"||typeof t.modelId!=="string")return;try{return hn({repoUrl:t.repoUrl,branch:t.branch,headSha:t.headSha,modelId:t.modelId,...typeof t.organizationId==="string"?{organizationId:t.organizationId}:{},...typeof t.workspaceRelativePath==="string"?{workspaceRelativePath:t.workspaceRelativePath}:{},...t.mode==="plan"||t.mode==="yolo"||t.mode==="zen"?{mode:t.mode}:{}})}catch{return}}function Go(e){let t=pe(pe(e)?.handoff);if(!t)return;let n=x(t.toCloudSessionId),s=x(t.handedOffAt),o=t.status;if(!n||!s||o!=="pending"&&o!=="complete")return;let i=x(t.innerSessionId),r=x(t.dashboardUrl),a=mn(t.fingerprint);return{toCloudSessionId:n,handedOffAt:s,status:o,...i?{innerSessionId:i}:{},...r?{dashboardUrl:r}:{},...a?{fingerprint:a}:{}}}function Vo(e,t){return{...e??{},handoff:t}}function Ko(e){let{handoff:t,cloudHandoffIntent:n,cloudHandoffSeedDispatched:s,...o}=e??{};return o}function Qo(e,t){let n=t.trim();if(!n)throw Error("Cloud session id cannot be empty.");let s=new URL("/agents",e);return s.searchParams.set("sessionId",n),s.toString()}function tt(e){return e.map((t)=>{let n=t&&typeof t==="object"?t:{};return{role:n.role,content:n.content}})}function fe(e,t){return e.length===t.length&&JSON.stringify(tt(e))===JSON.stringify(tt(t))}class he extends Error{constructor(e,t){super(`Cloud transcript verification failed (local ${e} messages, cloud ${t}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as gn}from"node:crypto";import{decodeJwtPayload as yn}from"@cline/shared";var bn=610000,wn=3000,B=15000,vn="CLOUD_SESSION_ERROR:",ot="__cline_create_request__:";function it(e){return(e.trim().split(`
8
- `)[0]??"").trim().slice(0,72)}class m extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${vn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class rt extends m{constructor(e){super("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list or dashboard before starting another task.");this.name="CloudCreationUnconfirmedError",this.cause=e}}class at extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function ye(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function Cn(e){return`${ot}${e}`.slice(0,255)}function nt(e){return e?.startsWith(ot)===!0}function be(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function me(e){let t=yn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function st(e){return new Promise((t,n)=>{if(e.aborted){n(e.reason);return}let s=()=>{clearTimeout(o),n(e.reason)},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},wn);e.addEventListener("abort",s,{once:!0})})}function Sn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function ge(e,t,n,s){let o=Sn(t,`Cloud session request failed (${e})`);if(e===401)return new m("authentication_required",o);if(e===404)return new m("session_not_found",o);if(e===410)return new m("session_expired",o);if(e===412)return new m("github_not_connected",o,s??`${ye(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new m("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new m("request_failed",o,void 0,e)}class kn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=ye(e.apiBaseUrl),this.appBaseUrl=ye(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??bn}async request(e,t={},n,s,o){let i=!1,r;while(!0){let a;try{a=typeof s==="string"?s:await this.options.getAuthToken()}catch(f){if(r)throw ge(401,void 0,this.appBaseUrl,n);throw f}if(!a?.trim())throw new m("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new m("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?me(a.trim())!==s.subject:a.trim()!==s.token)throw new m("authentication_required","The signed-in account changed during cloud session creation.");s.token=a.trim()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),l=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,r=a.trim();continue}throw ge(d.status,l,this.appBaseUrl,n)}return l?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&nt(i.title)?void 0:i.title,repoContext:i.repoContext&&typeof i.repoContext==="object"?i.repoContext:{},metadata:{...i.metadata&&typeof i.metadata==="object"?i.metadata:{},...!n&&nt(i.title)?{createRequestTitle:i.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let o=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:o.flatMap((i)=>{let r=Number(i.id),a=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(i.name??"").trim();return[{id:r,name:d,fullName:String(i.full_name??(d||a)).trim(),url:a,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof m&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new m("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,r=n.query?.trim(),a=n.cursor?.trim();if(r)i.set("query",r);if(a)i.set("cursor",a);let d=i.size>0?`${o}?${i}`:o;try{let l=await this.request(d),f=Array.isArray(l)?l:Array.isArray(l?.items)?l.items:[],c=r?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let p=String(h.name??"").trim();return p&&(!Array.isArray(l)||!c||p.toLowerCase().includes(c))?[p]:[]}),nextToken:Array.isArray(l)?"":String(l?.nextToken??"").trim()}}catch(l){if(l instanceof m&&l.code==="session_not_found")return{available:!1,branches:[]};throw l}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new m("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new m("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:me(t)},s=Cn(e.requestId?.trim()||gn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new m("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),r=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let p=new m(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(u){if(!(u instanceof m&&(u.code==="session_not_found"||u.code==="session_expired")))throw AggregateError([p,u],"The unusable recovered cloud handoff workspace could not be removed.")}if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.delete(o);throw await e.handoff?.onOuterSessionRemoved?.(c.id),p}await e.handoff?.onOuterSessionCreated(c.id,{created:!1});let h={sessionId:c.id,status:c.status,sandboxUrl:c.sandboxUrl,cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,h);return h};if(o){let c=await i();if(c.length>1)throw new m("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await r(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(p){if(p instanceof m&&(p.code==="session_not_found"||p.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(o),this.unconfirmedHandoffCreates.delete(o);throw p}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:n.token}}if(this.unconfirmedHandoffCreates.has(o))throw new m("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),l,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new m("request_failed","The cloud session service returned no session id.");l=h,await this.persistHandoffOuterSession(e,h,n,o);let p={sessionId:h,status:c.status?.trim()||"provisioning",sandboxUrl:c.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,p);return p}catch(c){if(l)throw c;let h=!f||c instanceof m&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new at(c);if(a.signal.aborted||!(c instanceof m)||c instanceof m&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let u=[];try{u=await i()}catch(y){if(e.handoff)throw AggregateError([c,y],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(!e.handoff&&!h&&u.length!==1)throw new rt(c);if(u.length>1)throw new m("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let g=u[0];if(g){if(e.handoff)return await r(g);return{sessionId:g.id,status:g.status,sandboxUrl:g.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof m&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject:me(s)}:void 0;while(!t.aborted){let i;try{i=await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:AbortSignal.any([t,AbortSignal.timeout(B)])},void 0,o)}catch(a){if(t.aborted)throw a;if(a instanceof m&&a.code!=="request_failed")throw a;await st(t);continue}let r=i?.status?.trim().toLowerCase();if(n?.({phase:be(i?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new m("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new m("request_failed","The cloud session service returned an unexpected provisioning status.");await st(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof m)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new m("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw ge(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new m("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as _o}from"node:crypto";import{posix as ue}from"node:path";import{createSessionId as js,ensureLoopbackProxyBypass as Nt,isHubProtocolCompatible as Fs,resolveClineBuildEnv as zs,resolveHubCommandTimeoutMs as Js}from"@cline/shared";import{HttpProxyAgent as Gs}from"http-proxy-agent";import{HttpsProxyAgent as Vs}from"https-proxy-agent";import{getProxyForUrl as Ks}from"proxy-from-env";import Qs from"ws";var q={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.94-nightly.1792204233",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","proxy-from-env":"^2.1.0","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/proxy-from-env":"^1.0.4","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var dt="session_not_found";class Y extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function we(e){return e instanceof Y||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as rs}from"node:child_process";import{closeSync as as,mkdirSync as ds,openSync as cs,readFileSync as us,unlinkSync as ls}from"node:fs";import{basename as ps,dirname as fs,join as hs}from"node:path";import{fileURLToPath as ms}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as gs,getClineClientIdentity as ys,isBunEmbeddedModulePath as bs,isHubDaemonProcess as ws,resolveClineBuildEnv as It,withHubLauncherIdentity as vs,withResolvedClineBuildEnv as Cs}from"@cline/shared";import{createHash as _n,randomBytes as Pn}from"node:crypto";import{mkdir as Ce,open as ct,readFile as ht,rename as An,rm as Se,writeFile as Tn}from"node:fs/promises";import{dirname as mt,join as ke}from"node:path";import{ensureLoopbackProxyBypass as xn,isHubProtocolCompatible as En}from"@cline/shared";import{resolveClineDataDir as N,resolveClineDir as hi}from"@cline/shared/storage";var Hn="CLINE_HUB_DISCOVERY_PATH",In="CLINE_HUB_BUILD_ID",Mn="CLINE_HUB_BUILD_EPOCH_MS",On=30000,Un=15000,ut=100;function Ln(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Dn(e){return _n("sha256").update(e).digest("hex").slice(0,12)}function Bn(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function lt(e){return new Promise((t)=>setTimeout(t,e))}function qn(e){return`${e}.lock`}async function Nn(e){try{let t=JSON.parse(await ht(ke(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function ve(e){await Se(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[In]?.trim();if(e)return e;return"sdk-v1-f5a1fc2ba8d43f15033fc87e8829924161d986b0704ba71d3b1f2052a2bf3e40".trim()||`source-${String(q.version)}`}function $n(){let e=Number(process.env[Mn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792204255621)?1792204255621:void 0}function X(e,t=U()){let n=En(e);if(!n.compatible)return n;let s=e.buildId?.trim();if(!s)return{compatible:!1,reason:"missing_build"};if(s!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function pt(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ft(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((s)=>Number(s));if(n.length===0||n.some((s)=>!Number.isInteger(s)||s<0))return;return n}function Wn(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let s=e[n]??0,o=t[n]??0;if(s!==o)return s<o?-1:1}return 0}function gt(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=pt(e.buildEpochMs),i=pt(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let r=ft(e.coreVersion),a=ft(t.coreVersion);if(r&&a){let d=Wn(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function yt(){return{buildId:U(),buildEpochMs:$n(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??yt(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return gt(n,e)<=0}function bt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Dn(e)}`,n=process.env[Hn]?.trim()||ke(N(),"locks","hub","owners",`${Ln(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e,t={}){try{let n;try{n=await ht(e,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let s;try{s=JSON.parse(n)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!s||typeof s.hubId!=="string"||typeof s.protocolVersion!=="string"||typeof s.authToken!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string"||typeof s.startedAt!=="string"||typeof s.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:s.hubId,protocolVersion:s.protocolVersion,minClientProtocolVersion:typeof s.minClientProtocolVersion==="string"?s.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof s.maxClientProtocolVersion==="string"?s.maxClientProtocolVersion:void 0,capabilities:Array.isArray(s.capabilities)?s.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof s.coreVersion==="string"?s.coreVersion:void 0,buildId:typeof s.buildId==="string"?s.buildId:void 0,buildEpochMs:typeof s.buildEpochMs==="number"?s.buildEpochMs:void 0,authToken:s.authToken,host:s.host,port:s.port,url:s.url,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:s.startedAt,updatedAt:s.updatedAt}}catch(n){if(t.onError==="throw")throw n;return}}async function wt(e,t){await Ct(e,async()=>{let n=mt(e);await Ce(n,{recursive:!0});let s=`${e}.${process.pid}.${Pn(6).toString("hex")}.tmp`,o;try{o=await ct(s,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
8
+ `)[0]??"").trim().slice(0,72)}class m extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${vn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class rt extends m{constructor(e){super("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list or dashboard before starting another task.");this.name="CloudCreationUnconfirmedError",this.cause=e}}class at extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function ye(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function Cn(e){return`${ot}${e}`.slice(0,255)}function nt(e){return e?.startsWith(ot)===!0}function be(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function me(e){let t=yn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function st(e){return new Promise((t,n)=>{if(e.aborted){n(e.reason);return}let s=()=>{clearTimeout(o),n(e.reason)},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},wn);e.addEventListener("abort",s,{once:!0})})}function Sn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function ge(e,t,n,s){let o=Sn(t,`Cloud session request failed (${e})`);if(e===401)return new m("authentication_required",o);if(e===404)return new m("session_not_found",o);if(e===410)return new m("session_expired",o);if(e===412)return new m("github_not_connected",o,s??`${ye(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new m("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new m("request_failed",o,void 0,e)}class kn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=ye(e.apiBaseUrl),this.appBaseUrl=ye(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??bn}async request(e,t={},n,s,o){let i=!1,r;while(!0){let a;try{a=typeof s==="string"?s:await this.options.getAuthToken()}catch(f){if(r)throw ge(401,void 0,this.appBaseUrl,n);throw f}if(!a?.trim())throw new m("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new m("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?me(a.trim())!==s.subject:a.trim()!==s.token)throw new m("authentication_required","The signed-in account changed during cloud session creation.");s.token=a.trim()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),l=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,r=a.trim();continue}throw ge(d.status,l,this.appBaseUrl,n)}return l?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&nt(i.title)?void 0:i.title,repoContext:i.repoContext&&typeof i.repoContext==="object"?i.repoContext:{},metadata:{...i.metadata&&typeof i.metadata==="object"?i.metadata:{},...!n&&nt(i.title)?{createRequestTitle:i.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let o=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:o.flatMap((i)=>{let r=Number(i.id),a=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(i.name??"").trim();return[{id:r,name:d,fullName:String(i.full_name??(d||a)).trim(),url:a,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof m&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new m("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,r=n.query?.trim(),a=n.cursor?.trim();if(r)i.set("query",r);if(a)i.set("cursor",a);let d=i.size>0?`${o}?${i}`:o;try{let l=await this.request(d),f=Array.isArray(l)?l:Array.isArray(l?.items)?l.items:[],c=r?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let p=String(h.name??"").trim();return p&&(!Array.isArray(l)||!c||p.toLowerCase().includes(c))?[p]:[]}),nextToken:Array.isArray(l)?"":String(l?.nextToken??"").trim()}}catch(l){if(l instanceof m&&l.code==="session_not_found")return{available:!1,branches:[]};throw l}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new m("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new m("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:me(t)},s=Cn(e.requestId?.trim()||gn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new m("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),r=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let p=new m(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(u){if(!(u instanceof m&&(u.code==="session_not_found"||u.code==="session_expired")))throw AggregateError([p,u],"The unusable recovered cloud handoff workspace could not be removed.")}if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.delete(o);throw await e.handoff?.onOuterSessionRemoved?.(c.id),p}await e.handoff?.onOuterSessionCreated(c.id,{created:!1});let h={sessionId:c.id,status:c.status,sandboxUrl:c.sandboxUrl,cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,h);return h};if(o){let c=await i();if(c.length>1)throw new m("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await r(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(p){if(p instanceof m&&(p.code==="session_not_found"||p.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(o),this.unconfirmedHandoffCreates.delete(o);throw p}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:n.token}}if(this.unconfirmedHandoffCreates.has(o))throw new m("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),l,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new m("request_failed","The cloud session service returned no session id.");l=h,await this.persistHandoffOuterSession(e,h,n,o);let p={sessionId:h,status:c.status?.trim()||"provisioning",sandboxUrl:c.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,p);return p}catch(c){if(l)throw c;let h=!f||c instanceof m&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new at(c);if(a.signal.aborted||!(c instanceof m)||c instanceof m&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let u=[];try{u=await i()}catch(y){if(e.handoff)throw AggregateError([c,y],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(!e.handoff&&!h&&u.length!==1)throw new rt(c);if(u.length>1)throw new m("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let g=u[0];if(g){if(e.handoff)return await r(g);return{sessionId:g.id,status:g.status,sandboxUrl:g.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof m&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject:me(s)}:void 0;while(!t.aborted){let i;try{i=await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:AbortSignal.any([t,AbortSignal.timeout(B)])},void 0,o)}catch(a){if(t.aborted)throw a;if(a instanceof m&&a.code!=="request_failed")throw a;await st(t);continue}let r=i?.status?.trim().toLowerCase();if(n?.({phase:be(i?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new m("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new m("request_failed","The cloud session service returned an unexpected provisioning status.");await st(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof m)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new m("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw ge(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new m("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as _o}from"node:crypto";import{posix as ue}from"node:path";import{createSessionId as js,ensureLoopbackProxyBypass as Nt,isHubProtocolCompatible as Fs,resolveClineBuildEnv as zs,resolveHubCommandTimeoutMs as Js}from"@cline/shared";import{HttpProxyAgent as Gs}from"http-proxy-agent";import{HttpsProxyAgent as Vs}from"https-proxy-agent";import{getProxyForUrl as Ks}from"proxy-from-env";import Qs from"ws";var q={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.95",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","proxy-from-env":"^2.1.0","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/proxy-from-env":"^1.0.4","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var dt="session_not_found";class Y extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function we(e){return e instanceof Y||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as rs}from"node:child_process";import{closeSync as as,mkdirSync as ds,openSync as cs,readFileSync as us,unlinkSync as ls}from"node:fs";import{basename as ps,dirname as fs,join as hs}from"node:path";import{fileURLToPath as ms}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as gs,getClineClientIdentity as ys,isBunEmbeddedModulePath as bs,isHubDaemonProcess as ws,resolveClineBuildEnv as It,withHubLauncherIdentity as vs,withResolvedClineBuildEnv as Cs}from"@cline/shared";import{createHash as _n,randomBytes as Pn}from"node:crypto";import{mkdir as Ce,open as ct,readFile as ht,rename as An,rm as Se,writeFile as Tn}from"node:fs/promises";import{dirname as mt,join as ke}from"node:path";import{ensureLoopbackProxyBypass as xn,isHubProtocolCompatible as En}from"@cline/shared";import{resolveClineDataDir as N,resolveClineDir as hi}from"@cline/shared/storage";var Hn="CLINE_HUB_DISCOVERY_PATH",In="CLINE_HUB_BUILD_ID",Mn="CLINE_HUB_BUILD_EPOCH_MS",On=30000,Un=15000,ut=100;function Ln(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Dn(e){return _n("sha256").update(e).digest("hex").slice(0,12)}function Bn(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function lt(e){return new Promise((t)=>setTimeout(t,e))}function qn(e){return`${e}.lock`}async function Nn(e){try{let t=JSON.parse(await ht(ke(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function ve(e){await Se(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[In]?.trim();if(e)return e;return"sdk-v1-d7fc6ac75da1ec6a985419452ab0576ef1178c82233d7370cd14e6261884bd99".trim()||`source-${String(q.version)}`}function $n(){let e=Number(process.env[Mn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792205906587)?1792205906587:void 0}function X(e,t=U()){let n=En(e);if(!n.compatible)return n;let s=e.buildId?.trim();if(!s)return{compatible:!1,reason:"missing_build"};if(s!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function pt(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ft(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((s)=>Number(s));if(n.length===0||n.some((s)=>!Number.isInteger(s)||s<0))return;return n}function Wn(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let s=e[n]??0,o=t[n]??0;if(s!==o)return s<o?-1:1}return 0}function gt(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=pt(e.buildEpochMs),i=pt(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let r=ft(e.coreVersion),a=ft(t.coreVersion);if(r&&a){let d=Wn(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function yt(){return{buildId:U(),buildEpochMs:$n(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??yt(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return gt(n,e)<=0}function bt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Dn(e)}`,n=process.env[Hn]?.trim()||ke(N(),"locks","hub","owners",`${Ln(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e,t={}){try{let n;try{n=await ht(e,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let s;try{s=JSON.parse(n)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!s||typeof s.hubId!=="string"||typeof s.protocolVersion!=="string"||typeof s.authToken!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string"||typeof s.startedAt!=="string"||typeof s.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:s.hubId,protocolVersion:s.protocolVersion,minClientProtocolVersion:typeof s.minClientProtocolVersion==="string"?s.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof s.maxClientProtocolVersion==="string"?s.maxClientProtocolVersion:void 0,capabilities:Array.isArray(s.capabilities)?s.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof s.coreVersion==="string"?s.coreVersion:void 0,buildId:typeof s.buildId==="string"?s.buildId:void 0,buildEpochMs:typeof s.buildEpochMs==="number"?s.buildEpochMs:void 0,authToken:s.authToken,host:s.host,port:s.port,url:s.url,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:s.startedAt,updatedAt:s.updatedAt}}catch(n){if(t.onError==="throw")throw n;return}}async function wt(e,t){await Ct(e,async()=>{let n=mt(e);await Ce(n,{recursive:!0});let s=`${e}.${process.pid}.${Pn(6).toString("hex")}.tmp`,o;try{o=await ct(s,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
9
9
  `,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await An(s,e);let i;try{i=await ct(n,"r"),await i.sync()}catch{}finally{await i?.close().catch(()=>{return})}}catch(i){throw await o?.close().catch(()=>{return}),await Se(s,{force:!0}).catch(()=>{return}),i}})}async function L(e){await Ct(e,async()=>{await Se(e,{force:!0}).catch(()=>{return})})}async function vt(e,t,n){let s=qn(e);await Ce(mt(s),{recursive:!0});let o=Date.now()+Un;while(!0){try{await Ce(s,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await Nn(s);if(!a){if(Date.now()>=o){await ve(s);continue}await lt(ut);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!Bn(a.pid)||d>On){await ve(s);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${s}`);await lt(ut);continue}try{return await Tn(ke(s,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
10
10
  `,"utf8"),await n()}finally{await ve(s)}}}function Ct(e,t){return vt(`${e}.mutation`,"discovery mutation",t)}function St(e,t){return vt(e,"startup",t)}async function ee(e,t){xn();try{let n=await fetch(t?.authToken?jn(e):Rt(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let s=await n.json();if(typeof s.protocolVersion!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string")return;return{protocolVersion:s.protocolVersion,minClientProtocolVersion:typeof s.minClientProtocolVersion==="string"?s.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof s.maxClientProtocolVersion==="string"?s.maxClientProtocolVersion:void 0,capabilities:Array.isArray(s.capabilities)?s.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof s.coreVersion==="string"?s.coreVersion:void 0,buildId:typeof s.buildId==="string"?s.buildId:void 0,buildEpochMs:typeof s.buildEpochMs==="number"?s.buildEpochMs:void 0,host:s.host,port:s.port,url:s.url,hubId:typeof s.hubId==="string"?s.hubId:void 0,authToken:typeof s.authToken==="string"?s.authToken:void 0,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:typeof s.startedAt==="string"?s.startedAt:void 0,updatedAt:typeof s.updatedAt==="string"?s.updatedAt:void 0}}catch{return}}function kt(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Rt(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function jn(e){let t=new URL(Rt(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as Fn,CLINE_HUB_PORT as zn,resolveClineBuildEnv as Jn}from"@cline/shared";var Gn="CLINE_HUB_HOST",Vn="CLINE_HUB_PORT",Kn="CLINE_HUB_PATHNAME",Qn="127.0.0.1",Yn=zn,Xn="/hub";function _t(e){return Jn(e)==="development"?Fn:Yn}function Zn(e={}){return(e.env??process.env)[Gn]?.trim()||Qn}function es(e={}){let n=(e.env??process.env)[Vn]?.trim();if(!n)return _t(e);let s=Number.parseInt(n,10);if(!Number.isInteger(s)||s<1||s>65535)return _t(e);return s}function ts(e={}){return(e.env??process.env)[Kn]?.trim()||Xn}function Pt(e={},t={}){return{host:e.host??Zn(t),port:e.port??es(t),pathname:e.pathname??ts(t)}}import{join as ns}from"node:path";var ss="shared:cline",os="CLINE_HUB_DISCOVERY_PATH",is="hub-production";function W(e=ss){return bt(`${e}@${U()}`)}function te(){return{ownerId:is,discoveryPath:process.env[os]?.trim()||ns(N(),"locks","hub","production.json")}}var At=15000,Ss=200,Tt=3000,ks=100,Rs=[100,250,500,1000,2000],Mt="--cline-hub-daemon",_s=3,Ps=60000,xt=new Map;function As(e,t=Date.now()){let n=xt.get(e);if(!n||t-n.windowStartedAt>Ps)return xt.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=_s}function Ts(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function xs(){try{let e=hs(N(),"logs","hub-daemon.log");return ds(fs(e),{recursive:!0}),{fd:cs(e,"a"),logPath:e}}catch{return}}function Es(){return It()==="production"?te():W()}function j(e){return Z(e)}function Hs(e){try{let t=JSON.parse(us(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function Re(e){try{ls(`${e}.superseded`)}catch{}}function Et(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function F(e,t){try{return await ee(e,{authToken:t})}catch{return}}async function Ht(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await F(e))?.url)return!0;await new Promise((o)=>setTimeout(o,ks))}return!1}async function Ae(e,t){if(!As(e.url))return!1;await z(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Ut(e.url,e.authToken).catch(()=>!1);let n=await Ht(e.url,Tt);if(!n&&e.pid&&Is(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Ht(e.url,Tt)}if(n)await L(t).catch(()=>{return});return n}function Is(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Ms(e){try{return(await Te(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function _e(e,t){if(j(e))return"reusable";let n=await z(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await Ms(e)){if(n)await z(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let s=await Ae(e,t);if(!s&&n)await z(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return s?"retired":"failed"}async function Os(e){if(It()!=="production")return;let t=W();if(t.discoveryPath===e.discoveryPath)return;let n=await I(t.discoveryPath);if(n?.url)await Ae(n,t.discoveryPath);else await L(t.discoveryPath).catch(()=>{return})}function Us(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return ms(new URL(`./entry.${e}`,import.meta.url))}function Ls(e,t){if(bs(e))return[Mt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}var Pe;function Ds(e,t){let n,s;if(Pe)n=Pe.command,s=Pe.args??[Mt];else{let o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let i=ps(o).toLowerCase().includes("bun");n=o,s=Ls(Us(),i)}return{launcher:n,args:[...s,"--cwd",e,...Ts(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...vs(Cs(process.env),Bs()),CLINE_NO_INTERACTIVE:"1",[gs]:"1"}}}function Bs(){let e=ys(),t=e?.name?.trim();return t?{client:t,version:e?.version,transport:"local"}:void 0}function qs(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function Ns(e,t={}){if(ws())return;let n=Ds(e,t),s=xs();try{rs(n.launcher,n.args,{detached:!0,stdio:s?["ignore",s.fd,s.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(s)as(s.fd)}}async function $s(e,t={}){for(let n=0;;n++)try{Ns(e,t);return}catch(s){let o=Rs[n];if(!qs(s)||o===void 0)throw s;await new Promise((i)=>setTimeout(i,o))}}async function Ws(e,t,n={}){let s=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Pt(n),i=kt(o.host,o.port,o.pathname),r=(u)=>{if(!s)ne(u.url,u.authToken);return u};await Os(e).catch(()=>{return});let a=await I(e.discoveryPath),d=a?.url?void 0:Hs(e.discoveryPath),l=!1;if(a?.url){let u=a.authToken;if(!u)l=!0,await Ae(a,e.discoveryPath);else{let g=await F(a.url,u);if(g?.url&&j(g)&&await E(g.url,{authToken:u}))return Re(e.discoveryPath),r({url:g.url,authToken:u});if(g?.url){if(await _e({...g,authToken:u},e.discoveryPath)==="deferred_busy"&&await E(g.url,{authToken:u}))return r({url:g.url,authToken:u})}else await L(e.discoveryPath).catch(()=>{return})}}let f=await F(i);if(f?.url){let u=Et(f,a??d,i);if(j(f)){let y=[f.authToken,a?.authToken,d?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0);for(let v of y){if(!await E(f.url,{authToken:v}))continue;let P={hubId:f.hubId??`repaired-${f.port}`,protocolVersion:f.protocolVersion,minClientProtocolVersion:f.minClientProtocolVersion,maxClientProtocolVersion:f.maxClientProtocolVersion,capabilities:f.capabilities,coreVersion:f.coreVersion,buildId:f.buildId,authToken:v,host:f.host,port:f.port,url:f.url,pid:f.pid??a?.pid??d?.pid,startedAt:f.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await wt(e.discoveryPath,P)}catch{}return Re(e.discoveryPath),r({url:f.url,authToken:v})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${l?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let g=await _e(u,e.discoveryPath);if(g==="deferred_busy"){for(let y of[u.authToken,a?.authToken].filter((w)=>typeof w==="string"&&w.trim().length>0))if(await E(f.url,{authToken:y}))return r({url:f.url,authToken:y});if(n.allowPortFallback!==!0&&o.port!==0)throw Error(`An older Cline Hub is running at ${i} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(g==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let h=n.allowPortFallback===!0&&o.port!==0?{...o,port:0}:o;await n.beforeSpawn?.(),await $s(t,{...h,manageConnectors:n.manageConnectors});let p=Date.now()+At;while(Date.now()<p){let u=await I(e.discoveryPath);if(u?.url&&u.authToken){let y=await F(u.url,u.authToken);if(y?.url&&j(y)&&await E(y.url,{authToken:u.authToken}))return Re(e.discoveryPath),r({url:y.url,authToken:u.authToken})}let g=await F(i);if(g?.url&&!j(g)){let y=Et(g,u??d,i),w=await _e(y,e.discoveryPath);if(w==="deferred_busy"&&u?.authToken&&await E(g.url,{authToken:u.authToken}))return r({url:g.url,authToken:u.authToken});if(w==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((y)=>setTimeout(y,Ss))}throw Error(`Timed out after ${At}ms waiting for detached hub startup.`)}async function Ot(e,t={}){let n=Es();return await St(n.discoveryPath,async()=>Ws(n,e,t))}function Ys(){return zs()==="production"?te():W()}function Xs(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Zs(e){let t=new URL(e);t.protocol=e.protocol==="wss:"?"https:":"http:";let n=Ks(t.toString());if(!n)return;return e.protocol==="wss:"?new Vs(n):new Gs(n)}function $t(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return $t(e.data);return String(e)}function eo(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function Lt(e){let t=e,n=eo(t.reason);return new k("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:He,{closeCode:t.code,closeReason:n||void 0})}function xe(e,t){if(e instanceof k)return e;if(e instanceof Error)return new k("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new k("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new k("hub_connect_failed",n);let s=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new k("hub_connect_failed",s?`Failed to connect to hub at ${t.toString()} (${s} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var Ee="*",se=8000,to="cline-hub-auth.",Wt=new Map,jt=new Set,no=3000;var He="Hub connection closed",so=250,oo=5000,Dt=0.5;class k extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function io(e){return e instanceof k}class Ie extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function Oe(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let s=Ue(e.toString());return s?Wt.get(s):void 0}function ro(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function Ue(e){if(!ro(e))return;let t=new URL(Ft(e));return t.search="",t.hash="",t.toString()}function Bt(e){let t=Ue(e);return!!t&&jt.has(t)}function ne(e,t){let n=Ue(e);if(n){if(jt.add(n),t?.trim())Wt.set(n,t)}return e}class J{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new k("hub_connection_closed",He);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||Oe(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,s=this.openSocket(e,t,n),o;this.connectPromise=s.then(async(r)=>{if(o=r,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(q.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{r.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let a of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(a));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(r){if(this.connectPromise===i)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=xe(r,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw r}}async openSocket(e,t,n){let s=this.options.resolveConnectionHeaders,o;if(s){let l;try{o=await Promise.race([Promise.resolve().then(()=>s()),new Promise((f,c)=>{l=setTimeout(()=>{c(new k("hub_connect_timeout",`Timed out resolving hub connection headers after ${se}ms`))},se)})])}catch(f){let c=f instanceof k?f:new k("hub_connect_failed",f instanceof Error?f.message:String(f));if(n===this.connectGeneration)this.lastCloseError=c;throw c}finally{clearTimeout(l)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((l)=>l.toLowerCase()==="sec-websocket-protocol")){let l=new k("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=l;throw l}let i;try{i=o?Zs(e):void 0}catch(l){let f=xe(l,e);if(n===this.connectGeneration)this.lastCloseError=f;throw f}let r=o?new Qs(e.toString(),{headers:{...o},agent:i}):new(Xs())(e.toString(),t?[`${to}${t}`]:void 0);this.socket=r;let a=!1,d=new Promise((l,f)=>{let c=!1,h=setTimeout(()=>{if(c)return;c=!0,a=!0;let p=new k("hub_connect_timeout",`Timed out connecting to hub after ${se}ms`);if(this.socket===r)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{r.close()}catch{}f(p)},se);r.addEventListener("open",()=>{if(c)return;c=!0,clearTimeout(h),l()}),r.addEventListener("error",(p)=>{if(c)return;c=!0,clearTimeout(h);let u=xe(p,e);if(this.socket===r)this.lastCloseError=u,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;f(u)}),r.addEventListener("close",(p)=>{if(c)return;c=!0,clearTimeout(h);let u=a?this.lastCloseError:Lt(p);if(this.socket===r){if(!a)this.lastCloseError=u,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}f(u)})});return r.addEventListener("message",(l)=>{this.handleFrame(JSON.parse($t(l)))}),r.addEventListener("close",(l)=>{if(this.socket!==r)return;if(!a)this.lastCloseError=Lt(l),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await d,r}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,s={listener:e,sessionId:n};return this.listeners.add(s),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(s))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,s){let o=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,s)}catch(r){if(!i||o>=1||!await this.recoverLocalHubTransport(r))throw r;o+=1}}async commandOnce(e,t,n,s,o=!0){if(o)await this.connect();s?.beforeDispatch?.();let i=js("hubreq_");s?.onDispatch?.(i);let r=Js(e,s?.timeoutMs),a=new Promise((l,f)=>{let c=r===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;f(new Ie(e,"hub_command_timeout",`Hub command ${e} timed out after ${r}ms (hub=${this.currentUrl}, requestId=${i}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},r);this.pendingReplies.set(i,{resolve:(h)=>{if(c)clearTimeout(c);l(h)},reject:(h)=>{if(c)clearTimeout(c);f(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:r,payload:t}})}catch(l){throw this.pendingReplies.delete(i),l}let d=await a;if(!d.ok){if(d.error?.code===dt){let l=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Y(l,d.error.message)}throw new Ie(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Bt(this.currentUrl)||!io(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await qt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let e=Math.min(so*2**this.reconnectAttempt,oo),t=Math.round(e*(1-Dt)+Math.random()*e*Dt);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Bt(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await qt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new k("hub_connection_closed",He);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new k("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),s=(this.subscriptionCounts.get(n)??0)+t;if(s<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,s),t>0&&s===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??Ee}subscriptionSessionIdFromKey(e){return e===Ee?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let s of[Ee,n]){if(!s||!this.subscriptionCounts.has(s))continue;let o=this.lastEventSequenceByKey.get(s)??0;if(t>o)this.lastEventSequenceByKey.set(s,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Ft(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function E(e,t){let n=new J({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function Me(e,t){let n=Ft(e),s=await ee(n,{authToken:t?.authToken});if(!s)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=U(),i=X(s,o);if(!i.compatible&&!Z(s))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!Fs(s).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await E(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function ao(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,s=new Set;for(let o of t){if(!o||typeof o!=="object")continue;let i=o.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let r of i){let a=r&&typeof r==="object"?r.clientId:void 0;if(typeof a==="string"&&a.trim())s.add(a)}}return{activeSessionCount:n,participantClientCount:s.size}}async function Te(e,t,n){let s=new J({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await s.command("session.list",{limit:500},void 0,{timeoutMs:no});return ao(o.payload)}finally{await s.dispose().catch(()=>{return})}}async function co(e,t,n){try{return(await Te(e,t,n)).activeSessionCount===0}catch{return!1}}async function uo(e,t){let n=`${e.discoveryPath}.superseded`,s=await I(n);if(!s?.url||!s.authToken)return;let o=await Me(s.url,{authToken:s.authToken});if(o.status!=="compatible")return;if(await co(o.url,s.authToken,t))return;return ne(o.url,s.authToken)}async function lo(e={}){if(e.endpoint?.trim()){let o=await Me(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=Ys(),n=await I(t.discoveryPath);if(!n?.url)return await uo(t,e);let s=await Me(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(s.status==="compatible")return ne(s.url,n.authToken);if(s.status==="protocol_mismatch")await L(t.discoveryPath).catch(()=>{return});return}async function qt(e={}){let t=await lo(e);if(t&&await E(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Ot(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function z(e,t,n,s){Nt();let o=new URL(e),i=t?.trim()||Oe(o);if(o.protocol==="ws:")o.protocol="http:";else if(o.protocol==="wss:")o.protocol="https:";if(o.pathname="/drain",o.hash="",n)o.searchParams.set("reason",n);if(s?.off)o.searchParams.set("off","1");return(await fetch(o,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function Ut(e,t){Nt();let n=new URL(e),s=t?.trim()||Oe(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:s?{authorization:`Bearer ${s}`}:void 0})).ok}function po(e,t){if(!e||typeof e!=="object")return;let n=e,s=typeof n.id==="string"?n.id.trim():"";if(!s)return;let o=typeof n.display_name==="string"?n.display_name.trim():typeof n.displayName==="string"?n.displayName.trim():"",i=typeof n.name==="string"?n.name.trim():"";return{id:s,name:o||i||s,catalogId:t}}function Le(e,t){return Array.isArray(e)?e.flatMap((n)=>{let s=po(n,t);return s?[s]:[]}):[]}async function zt(e,t={}){let n=e.trim(),s=n.length;while(s>0&&n[s-1]==="/")s--;let o=n.slice(0,s),i=async(g)=>{let y=await(t.fetchImpl??fetch)(`${o}${g}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!y.ok)throw Error(`HTTP ${y.status}`);return await y.json()},r,a;try{[r,a]=await Promise.all([i("/api/v1/ai/cline/models"),i("/api/v1/ai/cline/recommended-models")])}catch(g){throw Error("Could not load the cloud model catalog.",{cause:g})}let d=r&&typeof r==="object"?r:void 0,l=Le(Array.isArray(r)?r:d?.data,"cline"),f=a&&typeof a==="object"?a:void 0,c=f?.data&&typeof f.data==="object"?f.data:f,h=Le(c?.clinePass,"cline-pass"),p=Le(c?.clineCloud,"cline-cloud"),u=new Set;return[...t.isOrganizationSession?[]:h,...p,...l].filter((g)=>{if(u.has(g.id))return!1;return u.add(g.id),!0})}import{formatDisplayUserInput as Jt}from"@cline/shared";var fo=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function ho(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function mo(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function go(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function yo(e){if(typeof e.content==="string")return{hasAttachment:!1,text:e.content};if(!Array.isArray(e.content))return{hasAttachment:!1,text:"unknown"};let t=!1,n=!1,s=[];for(let o of e.content){if(!o||typeof o!=="object"||Array.isArray(o))continue;let i=o;if(i.type==="text"&&typeof i.text==="string")s.push(i.text);else if(i.type==="tool_result"||i.type==="tool-result")n=!0;else if(i.type==="file"||i.type==="image")t=!0}return{hasAttachment:t&&!n,text:s.join(`
11
11
  `)}}function bo(e){let t=Jt(e);return t.startsWith("[TASK RESUMPTION]")||t==="The user approved switching to act mode. Continue with the approved plan now."}function wo(e){if(ho(e.role)!=="user")return 0;let t=mo(e),n=typeof t?.kind==="string"?t.kind:void 0,s=go(t);if(n==="compaction"||n==="compaction_summary")return s??1;if(s!==void 0)return s;if(n&&fo.has(n))return 0;let o=yo(e);if(!o.hasAttachment&&!Jt(o.text))return 0;if(!o.hasAttachment&&bo(o.text))return 0;return 1}function Gt(e){return wo(e)>0}function re(e){return Array.isArray(e?.sessions)?e.sessions.filter((t)=>Boolean(t)&&typeof t==="object"&&!Array.isArray(t)):[]}function De(e){let t=e.updatedAt;return typeof t==="number"?t:Date.parse(String(t??""))||0}function Be(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return String(t?.model??e?.model??"").trim()}function ae(e){let t=e.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return!String(t?.parentSessionId??e.parentSessionId??"").trim()}function Yt(e,t="text"){if(!e||typeof e!=="object"||Array.isArray(e))return"";let n=e.content;if(typeof n==="string")return t==="text"?n.trim():"";if(!Array.isArray(n))return"";return n.map((s)=>s&&typeof s==="object"&&!Array.isArray(s)?t==="thinking"&&s.type==="redacted_thinking"?"[redacted]":String(s[t]??""):"").join("").trim()}function oe(e){let t=e.trim(),n=t.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(n?n[1]:t).trim()}function G(e,t,n){let s=oe(n);return e.filter((o)=>Boolean(o)&&typeof o==="object"&&!Array.isArray(o)&&String(o.role??"").toLowerCase()==="user"&&(s!==""||Gt(o))&&oe(Yt(o))===s).length+t.filter((o)=>oe(o.prompt)===s).length}function qe(e){return e.flatMap((t)=>{if(t.event!=="session.pending_prompt_submitted")return[];let n=t.payload?.prompt&&typeof t.payload.prompt==="object"&&!Array.isArray(t.payload.prompt)?t.payload.prompt:void 0,s=String(n?.id??"").trim();if(!s)return[];return[{id:s,prompt:String(n?.prompt??""),steer:n?.delivery==="steer",attachmentCount:typeof n?.attachmentCount==="number"?n.attachmentCount:0,userImages:Array.isArray(n?.userImages)?n.userImages.filter((o)=>typeof o==="string"):void 0}]})}var vo=new Set(["run.completed","run.aborted","run.failed"]),Co=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function Vt(e,t){return e.filter((n)=>Boolean(n)&&typeof n==="object"&&!Array.isArray(n)&&String(n.role??"").toLowerCase()==="assistant").map((n)=>Yt(n,t)).filter(Boolean)}function Kt(e,t,n="text"){let s=new Map;for(let o of Vt(t,n))s.set(o,(s.get(o)??0)+1);return Vt(e,n).filter((o)=>{let i=s.get(o)??0;if(i===0)return!0;if(i===1)s.delete(o);else s.set(o,i-1);return!1})}function ie(e,t,n=new Set){if(!e||typeof e!=="object")return n;if(Array.isArray(e)){for(let i of e)ie(i,t,n);return n}let s=e,o=t==="tool_use"?s.id:s.tool_use_id;if(s.type===t&&typeof o==="string")n.add(o);for(let i of Object.values(s))ie(i,t,n);return n}function Qt(e,t="assistant"){let n="",s="";for(let o of e)if(o.event===`${t}.delta`)s+=t==="reasoning"&&o.payload?.redacted&&!o.payload?.text?"[redacted]":typeof o.payload?.text==="string"?o.payload.text:"";else if(o.event===`${t}.finished`){let i=o.payload?.[t==="assistant"?"text":"reasoning"],r=typeof i==="string"&&i?i:s;if(r)n=r;s=""}return(n||s).trim()}function Xt(e,t,n={}){let s=n.queueSnapshotApplied!==!1,o=Kt(t,n.baselineMessages??[]),i=Kt(t,n.baselineMessages??[],"thinking"),r=ie(t,"tool_use"),a=ie(t,"tool_result"),d=new Set(e.slice(0,n.messagesSnapshotEventCutoff??e.length)),l=new Set,f=new Map;for(let y of e.slice(0,n.messagesSnapshotEventCutoff??e.length)){let w=qe([y])[0];if(!w)continue;let v=oe(w.prompt),P=f.get(v)??Math.max(0,G(t,[],v)-G(n.baselineMessages??[],[],v));if(f.set(v,Math.max(0,P-1)),P>0)l.add(y)}let h=[...s?e.slice(n.queueSnapshotEventCutoff??e.length):e].reverse().find((y)=>y.event==="session.pending_prompts"),p=[],u=[],g=(y)=>{if(u.length===0)return;let w=u.filter((A)=>d.has(A)),v=(A)=>{if(!y)return-1;let S=[...w].reverse().findIndex((on)=>on.event===`${A}.finished`),D=S<0?-1:w.length-1-S;return D>=0||u.at(-1)?.event==="run.aborted"?D:w.length-1},P=v("assistant"),H=v("reasoning"),b=Qt(w.slice(0,P+1)),R=b?o.findIndex((A)=>A.endsWith(b)):-1,M=R>=0;if(M)o.splice(R,1);let V=Qt(w.slice(0,H+1),"reasoning"),le=V?i.findIndex((A)=>A.endsWith(V)):-1;if(le>=0)i.splice(le,1);for(let[A,S]of u.entries()){if(l.has(S)){p.push({...S,payload:{...S.payload,transcriptReflected:!0}});continue}if(d.has(S)&&Co.has(S.event)&&(S.event.startsWith("reasoning.")?le>=0&&A<=H:M&&A<=P))continue;if(S.event==="session.pending_prompts"&&S!==h)continue;if(d.has(S)&&S.event.startsWith("tool.")){let D=String(S.payload?.toolCallId??"").trim();if(a.has(D)||S.event==="tool.started"&&r.has(D))continue}p.push(S)}u=[]};for(let y of e)if(u.push(y),vo.has(y.event))g(!0);return g(!1),p}import{formatDisplayUserInput as So}from"@cline/shared";function de(e){let t=structuredClone(e),n=(s)=>{if(!s||typeof s!=="object"||Object.isFrozen(s))return;for(let o of Object.values(s))n(o);Object.freeze(s)};return n(t),t}function ce(e){let t=e?.trim();return t?So(t).slice(0,120):void 0}function Ne(e){if(typeof e==="string")return e;if(Array.isArray(e)){let t=[];for(let n of e){if(typeof n==="string"){if(n.trim())t.push(n);continue}if(!n||typeof n!=="object")continue;let s=n,o=typeof s.type==="string"?s.type:"",i=o==="text"?String(s.text??""):o==="thinking"?String(s.thinking??""):o==="tool_use"?`[tool] ${String(s.name??"tool_call")}`:o==="tool_result"?`[tool_result]
@@ -254,7 +254,7 @@ Searched ${f} files.`;let S=[`Found ${g.length} result${g.length===1?"":"s"} for
254
254
 
255
255
  ...[assistant text truncated: omitted ${e} chars due to repeated tool-call markup]...
256
256
 
257
- `;function KS(e=process.env){return{maxToolResultChars:zS(e[Ru.maxToolResultChars]),maxTotalTextBytes:zS(e[Ru.maxTotalTextBytes]),minOutdatedRewriteBytes:DL(e[Ru.minOutdatedRewriteBytes])}}class xu{recoveryNotices=new WeakSet;getToolResultRecovery;recoveryNoticeBytes=0;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor(e={}){this.getToolResultRecovery=e.getToolResultRecovery,this.maxToolResultChars=Go(e.maxToolResultChars,_u),this.maxFileContentChars=Go(e.maxFileContentChars,AL),this.maxTotalTextBytes=Go(e.maxTotalTextBytes,EL),this.mediaBudget=e.mediaBudget??{},this.maxAssistantTextChars=Go(e.maxAssistantTextChars,RL),this.maxAssistantToolMarkupChars=Go(e.maxAssistantToolMarkupChars,PL),this.minOutdatedRewriteBytes=UL(e.minOutdatedRewriteBytes,_L)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi(e){this.recoveryNoticeBytes=0,this.reindex(e),this.commitOutdatedRewrites(e);let n=this.addMissingToolResults(e).map((o)=>{if(!Array.isArray(o.content)){if(o.role==="user"&&typeof o.content==="string"){let a=HS(o.content);if(a!==o.content)return{...o,content:a}}if(o.role==="assistant"&&typeof o.content==="string"){let a=this.truncateAssistantText(o.content);if(a!==o.content)return{...o,content:a}}return o}let s=!1,i=o.content.map((a)=>{let d=this.transformBlock(a,o.role);if(d!==a)s=!0;return d});return s?{...o,content:i}:o}),r=this.applyMediaBudget(n);return this.truncateToTotalTextBudget(r)}transformBlock(e,t){if(t==="user"&&e.type==="text"&&typeof e.text==="string"){let s=HS(e.text);if(s!==e.text)return{...e,text:s};return e}if(t==="assistant"&&e.type==="text"&&typeof e.text==="string"){let s=this.truncateAssistantText(e.text);return s===e.text?e:{...e,text:s}}if(e.type==="file"){let s=Vo(e.content,this.maxFileContentChars,WS);return s===e.content?e:{...e,content:s}}if(e.type!=="tool_result")return e;let n=this.resolveToolName(e),r=this.getToolResultRecovery?.({...e,name:n??e.name});if(r){let{text:s,images:i}=Ia(e.content);if(typeof s==="string"&&s.length>this.maxToolResultChars){let a=[{type:"text",text:this.truncateMiddle(s)},...i];if(r.uri){let d={type:"text",text:`Full result is temporarily saved to ${r.uri}. Only read_files can access this cache URI. Use read_files with specific line ranges if omitted content is needed.`},c=pe(d.text);if(this.recoveryNoticeBytes+c<=this.maxTotalTextBytes/2)this.recoveryNoticeBytes+=c,this.recoveryNotices.add(d),a.push(d)}return{...e,content:a}}}let o=e.content;if(this.isReadTool(n)&&e.is_error!==!0){let s=this.committedOutdatedRewrites.get(e.tool_use_id);if(s&&s.size>0){let a=this.getReadLocators(e).filter((d)=>s.has(this.toReadLocatorKey(d))&&this.isOutdatedReadLocator(d,e.tool_use_id));if(a.length>0)o=this.replaceOutdatedReadContent(o,a)}}return o=this.truncateToolResultContent(o),o===e.content?e:{...e,content:o}}reindex(e){let t=this.indexedMessageCount===0||e.length>=this.indexedMessageCount&&e[this.indexedMessageCount-1]===this.indexedTailRef;if(e.length<this.indexedMessageCount||!t)this.resetIndexes();for(let n=this.indexedMessageCount;n<e.length;n++){let r=e[n];if(!Array.isArray(r.content))continue;for(let o=0;o<r.content.length;o++){let s=r.content[o];if(s.type==="file")this.latestFullContentOwnerByPathCache.set(s.path,`file:${n}:${o}`);else if(s.type==="tool_use"){let i=s.name.toLowerCase();if(this.toolNameByIdCache.set(s.id,i),this.isReadTool(i)){let a=this.extractLocatorsFromReadToolInput(s.input);if(a.length>0)this.readLocatorsByToolUseIdCache.set(s.id,a)}}else if(s.type==="tool_result"){let i=this.resolveToolName(s);if(!this.isReadTool(i)||s.is_error===!0)continue;let a=this.getReadLocators(s);for(let d of a)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(d),s.tool_use_id),this.isFullFileRead(d))this.latestFullContentOwnerByPathCache.set(d.path,s.tool_use_id)}}}this.indexedMessageCount=e.length,this.indexedTailRef=e.length>0?e[e.length-1]:void 0}commitOutdatedRewrites(e){let t=new Map,n=new Set,r=0;for(let o of e){if(!Array.isArray(o.content))continue;for(let s of o.content){if(s.type!=="tool_result"||s.is_error===!0)continue;let i=this.resolveToolName(s);if(!this.isReadTool(i))continue;n.add(s.tool_use_id);let a=this.committedOutdatedRewrites.get(s.tool_use_id),d=new Set,c=new Set;for(let u of this.getReadLocators(s)){let p=this.toReadLocatorKey(u);if(!this.isOutdatedReadLocator(u,s.tool_use_id))continue;if(c.add(p),!a?.has(p))d.add(p)}if(a){for(let u of a)if(!c.has(u))a.delete(u);if(a.size===0)this.committedOutdatedRewrites.delete(s.tool_use_id)}if(d.size===0)continue;let l=t.get(s.tool_use_id);if(!l)l=new Set,t.set(s.tool_use_id,l);for(let u of d)l.add(u);r+=this.estimateOutdatedReclaimBytes(s.content,d)}}for(let o of this.committedOutdatedRewrites.keys())if(!n.has(o))this.committedOutdatedRewrites.delete(o);if(t.size===0||r<this.minOutdatedRewriteBytes)return;for(let[o,s]of t){let i=this.committedOutdatedRewrites.get(o);if(!i)i=new Set,this.committedOutdatedRewrites.set(o,i);for(let a of s)i.add(a)}}estimateOutdatedReclaimBytes(e,t){let n=this.extractReadLocatorsFromToolResultContent(e),r=n.length>0&&n.every((d)=>t.has(this.toReadLocatorKey(d))),o=(d)=>{let c;try{c=JSON.parse(d)}catch{return r||n.length===0?pe(this.truncateMiddle(d)):0}let l=Array.isArray(c)?c:[c],u=0;for(let p of l){let m=this.extractLocatorFromResultEntry(p);if(m&&t.has(this.toReadLocatorKey(m)))u+=this.providerBoundEntryBytes(p)}return u};if(typeof e==="string")return o(e);let s=new Set(t),i=0;for(let d of e)if(d.type==="text")i+=this.countOutdatedImageEntries(d.text,s);let a=0;for(let d of e)if(d.type==="text")a+=o(d.text);else if(d.type==="image"){if(i>0)i-=1,a+=pe(d.data)}else if(gn(d)){let c=this.extractLocatorFromResultEntry(d);if(c&&t.has(this.toReadLocatorKey(c)))a+=this.providerBoundEntryBytes(d)}else if(d.type==="file"){if(t.has(this.toReadLocatorKey({path:d.path,startLine:null,endLine:null})))a+=pe(this.truncateMiddle(d.content))}return a}providerBoundEntryBytes(e){let t=this.truncateNestedStrings(e);return pe(JSON.stringify(t))}addMissingToolResults(e){let t=this.collectToolResultIds(e),n=[],r=new Map,o=!1,s=()=>{if(r.size===0)return;i(this.createMissingToolResultMessage(r)),r.clear(),o=!0},i=(a)=>{let d=n.at(-1);if(this.shouldMergeUserAfterToolResults(d,a)){n[n.length-1]={...d,content:[...d.content,...this.contentBlocksForUserMerge(a.content)]},o=!0;return}n.push(a)};for(let a of e){if(this.isToolResultOnlyMessage(a)){if(i(this.appendMissingToolResults(a,r)),r.size>0)r.clear(),o=!0;continue}if(Array.isArray(a.content)){let d=a.content.filter((l)=>l.type==="tool_result"),c=a.content.filter((l)=>l.type!=="tool_result");if(d.length>0){let l=this.appendMissingToolResults({...a,role:"user",content:d},r);if(i(l),r.size>0)r.clear();o=!0}if(c.length>0||d.length===0){if(d.length===0)s();let l=d.length>0?{...a,content:c}:a;if(i(l),l.role==="assistant")this.trackMissingToolCalls(l,t,r)}continue}s(),i(a)}return s(),o?n:e}appendMissingToolResults(e,t){if(t.size===0||!Array.isArray(e.content))return e;return{...e,role:"user",content:[...e.content,...this.createMissingToolResultBlocks(t)]}}shouldMergeUserAfterToolResults(e,t){return e?.role==="user"&&t.role==="user"&&this.isToolResultOnlyMessage(e)&&this.contentBlocksForUserMerge(t.content).length>0}contentBlocksForUserMerge(e){return typeof e==="string"?e.length>0?[{type:"text",text:e}]:[]:e}collectToolResultIds(e){let t=new Set;for(let n of e){if(!Array.isArray(n.content))continue;for(let r of n.content)if(r.type==="tool_result")t.add(r.tool_use_id)}return t}isToolResultOnlyMessage(e){return e.role==="user"&&Array.isArray(e.content)&&e.content.length>0&&e.content.every((t)=>t.type==="tool_result")}trackMissingToolCalls(e,t,n){if(!Array.isArray(e.content))return;for(let r of e.content){if(r.type!=="tool_use"||t.has(r.id))continue;n.set(r.id,r.name)}}createMissingToolResultMessage(e){return{role:"user",content:this.createMissingToolResultBlocks(e)}}createMissingToolResultBlocks(e){return Array.from(e,([t,n])=>({type:"tool_result",tool_use_id:t,name:n,content:[{type:"text",text:this.formatMissingToolResultText(n)}],is_error:!0}))}formatMissingToolResultText(e){return e?`${$S} Tool: ${e}.`:$S}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators(e){let t=e,n=this.readResultLocatorCache.get(t);if(n===void 0)n=this.extractReadLocatorsFromToolResultContent(e.content),this.readResultLocatorCache.set(t,n);if(n.length>0)return n;return this.readLocatorsByToolUseIdCache.get(e.tool_use_id)??[]}extractLocatorsFromReadToolInput(e){if(!e||typeof e!=="object")return[];let t=e,n=[],r=this.extractLocatorFromReadRequest(t);if(r)n.push(r);if(Array.isArray(t.files))for(let o of t.files){let s=this.extractLocatorFromReadRequest(o);if(s)n.push(s)}if(Array.isArray(t.file_paths)){for(let o of t.file_paths)if(typeof o==="string"&&o.length>0)n.push({path:o,startLine:null,endLine:null})}return this.dedupeReadLocators(n)}extractReadLocatorsFromToolResultContent(e){if(typeof e==="string")return this.tryParseReadLocators(e);let t=[];for(let n of e){if(n.type==="text"){t.push(...this.tryParseReadLocators(n.text));continue}if(gn(n)){let r=this.extractLocatorFromResultEntry(n);if(r)t.push(r)}}return this.dedupeReadLocators(t)}tryParseReadLocators(e){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(e))}catch{return[]}}extractLocatorsFromParsedReadResult(e){if(Array.isArray(e)){let n=[];for(let r of e){let o=this.extractLocatorFromResultEntry(r);if(o)n.push(o)}return this.dedupeReadLocators(n)}let t=this.extractLocatorFromResultEntry(e);return t?[t]:[]}extractLocatorFromReadRequest(e){if(!e||typeof e!=="object")return;let t=e,n=this.extractPath(t);if(!n)return;return{path:n,startLine:this.extractLineNumber(t.start_line),endLine:this.extractLineNumber(t.end_line)}}extractLocatorFromResultEntry(e){if(!e||typeof e!=="object")return;let t=e,n=this.extractPath(t);if(n)return{path:n,startLine:this.extractLineNumber(t.start_line),endLine:this.extractLineNumber(t.end_line)};if(typeof t.query==="string"&&t.query.length>0)return this.parseReadQuery(t.query);return}extractPath(e){let t=[e.path,e.file_path,e.filePath];for(let n of t)if(typeof n==="string"&&n.length>0)return n;return}extractLineNumber(e){return typeof e==="number"&&Number.isInteger(e)?e:null}parseReadQuery(e){let t=/^(.*):(\d+)-(EOF|\d+)$/.exec(e);if(!t)return{path:e,startLine:null,endLine:null};return{path:t[1],startLine:Number(t[2]),endLine:t[3]==="EOF"?null:Number(t[3])}}dedupeReadLocators(e){let t=new Map;for(let n of e)t.set(this.toReadLocatorKey(n),n);return Array.from(t.values())}toReadLocatorKey(e){if(this.isFullFileRead(e))return e.path;return`${e.path}:${e.startLine??1}-${e.endLine??"EOF"}`}isFullFileRead(e){return e.startLine==null&&e.endLine==null}isOutdatedReadLocator(e,t){let n=this.latestFullContentOwnerByPathCache.get(e.path);if(n&&n!==t)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(e))!==t}replaceOutdatedReadContent(e,t){let n=new Set(t.map((s)=>this.toReadLocatorKey(s))),r=new Set(t.map((s)=>s.path));if(typeof e==="string")return this.replaceOutdatedInString(e,n)??qn;let o=0;for(let s of e)if(s.type==="text")o+=this.countOutdatedImageEntries(s.text,n);return e.map((s)=>{if(s.type==="file"){if(!r.has(s.path))return s;return{...s,content:qn}}if(s.type==="image"){if(o===0)return s;return o-=1,{type:"text",text:qn}}if(gn(s))return this.replaceOutdatedReadEntry(s,n);if(s.type!=="text")return s;let i=this.replaceOutdatedInString(s.text,n);if(i===null)return{...s,text:qn};return i===s.text?s:{...s,text:i}})}countOutdatedImageEntries(e,t){let n;try{n=JSON.parse(e)}catch{return 0}let r=Array.isArray(n)?n:[n],o=0;for(let s of r){if(!s||typeof s!=="object")continue;let i=s,a=this.extractLocatorFromResultEntry(i);if(!a)continue;if(!t.has(this.toReadLocatorKey(a)))continue;if(i.result==="Successfully read image"||i.content==="Successfully read image")o+=1}return o}replaceOutdatedInString(e,t){let n;try{n=JSON.parse(e)}catch{return null}let r=Array.isArray(n)?n.map((o)=>this.replaceOutdatedReadEntry(o,t)):this.replaceOutdatedReadEntry(n,t);return JSON.stringify(r)}replaceOutdatedReadEntry(e,t){if(!e||typeof e!=="object")return e;let n=this.extractLocatorFromResultEntry(e);if(!n||!t.has(this.toReadLocatorKey(n)))return e;let r={...e};if(typeof r.result==="string")r.result=qn;else if(typeof r.content==="string")r.content=qn;else r.result=qn;return r}isReadTool(e){return!!e&&ML.has(e)}resolveToolName(e){let t=this.toolNameByIdCache.get(e.tool_use_id);if(t!==void 0)return t;return typeof e.name==="string"&&e.name.length>0?e.name.toLowerCase():void 0}truncateToolResultContent(e){if(typeof e==="string")return this.truncateMiddle(e);return e.map((t)=>{if(this.recoveryNotices.has(t))return t;if(t.type==="file"){let n=this.truncateMiddle(t.content);return n===t.content?t:{...t,content:n}}if(t.type==="text"){let n=this.truncateMiddle(t.text);return n===t.text?t:{...t,text:n}}if(gn(t))return this.truncateNestedStrings(t);return t})}truncateNestedStrings(e){if(typeof e==="string")return this.truncateMiddle(e);if(Array.isArray(e)){let t=!1,n=e.map((r)=>{let o=this.truncateNestedStrings(r);if(o!==r)t=!0;return o});return t?n:e}if(e!==null&&typeof e==="object"){if(Mu(e))return e;let t=!1,n={};for(let[r,o]of Object.entries(e)){let s=this.truncateNestedStrings(o);if(s!==o)t=!0;n[r]=s}return t?n:e}return e}truncateMiddle(e){return Vo(e,this.maxToolResultChars,WS)}truncateAssistantText(e){if(this.hasRepeatedToolCallMarkup(e))return Vo(e,this.maxAssistantToolMarkupChars,LL);return Vo(e,this.maxAssistantTextChars,OL)}hasRepeatedToolCallMarkup(e){if(e.length<=this.maxAssistantToolMarkupChars)return!1;let t=0;for(let n of e.matchAll(NL))if(t+=1,t>=xL)return!0;return!1}truncateToTotalTextBudget(e){let t=this.countMessageTextBytes(e);if(t<=this.maxTotalTextBytes)return e;let n=e.map((s)=>{if(!Array.isArray(s.content))return{...s};return{...s,content:s.content.map((i)=>{let a=HL(i);if(i.type==="tool_result"&&a.type==="tool_result"&&Array.isArray(i.content)&&Array.isArray(a.content))i.content.forEach((d,c)=>{if(this.recoveryNotices.has(d))this.recoveryNotices.add(a.content[c])});return a})}}),r=this.collectTruncationCandidates(n),o=Math.floor(this.maxTotalTextBytes/(2*Math.max(1,r.length)));for(let s of r){if(t<=this.maxTotalTextBytes)break;let i=s.byteLength,a=Math.min(s.minBytes,o);if(i<=a)continue;let d=t-this.maxTotalTextBytes,c=Math.max(a,i-d),l=FL(s.get(),c,s.makeMarker);s.set(l),t-=i-pe(l)}return n}countMessageTextBytes(e){let t=0;for(let n of e){if(typeof n.content==="string"){t+=pe(n.content);continue}for(let r of n.content)if(r.type==="text")t+=pe(r.text);else if(r.type==="thinking")t+=pe(r.thinking);else if(r.type==="file")t+=pe(r.content);else if(r.type==="tool_use")t+=La(r.input);else if(r.type==="tool_result"){if(typeof r.content==="string")t+=pe(r.content);else for(let o of r.content)if(o.type==="text")t+=pe(o.text);else if(o.type==="file")t+=pe(o.content);else if(gn(o))t+=La(o)}}return t}collectTruncationCandidates(e){let t=[],n=[];for(let r of e){if(r.role==="assistant"&&typeof r.content==="string"){t.push({byteLength:pe(r.content),minBytes:BS,makeMarker:qS,get:()=>r.content,set:(o)=>{r.content=o}});continue}if(!Array.isArray(r.content))continue;for(let o of r.content){if(o.type==="tool_use"){Na(o.input,n);continue}if(r.role==="assistant"&&o.type==="text"){t.push({byteLength:pe(o.text),minBytes:BS,makeMarker:qS,get:()=>o.text,set:(s)=>{o.text=s}});continue}if(o.type!=="tool_result")continue;if(typeof o.content==="string"){t.push({byteLength:pe(o.content),minBytes:Xo,makeMarker:Jo,get:()=>o.content,set:(s)=>{o.content=s}});continue}for(let s of o.content){if(this.recoveryNotices.has(s))continue;if(s.type==="text")t.push({byteLength:pe(s.text),minBytes:Xo,makeMarker:Jo,get:()=>s.text,set:(i)=>{s.text=i}});else if(s.type==="file")t.push({byteLength:pe(s.content),minBytes:Xo,makeMarker:Jo,get:()=>s.content,set:(i)=>{s.content=i}});else if(gn(s))Na(s,t)}}}return t.sort((r,o)=>o.byteLength-r.byteLength),n.sort((r,o)=>o.byteLength-r.byteLength),[...t,...n]}applyMediaBudget(e){let t=this.resolveMediaBudget();if(t.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&t.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&t.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return e;let n=kL(),r=!1,o=e.map((s)=>{if(!Array.isArray(s.content))return s;let i=!1,a=s.content.map((d)=>{let c=this.applyMediaBudgetToBlock(d,t,n);if(c!==d)i=!0;return c});if(!i)return s;return r=!0,{...s,content:a}});return r?o:e}resolveMediaBudget(){return IL(this.mediaBudget)}applyMediaBudgetToBlock(e,t,n){if(Pu(e))return this.limitImageContent(e,t,n);if(e.type!=="tool_result"||typeof e.content==="string")return e;let r=!1,o=e.content.map((s)=>{let i=this.applyMediaBudgetToToolResultEntry(s,t,n);if(i!==s)r=!0;return i});return r?{...e,content:o}:e}applyMediaBudgetToToolResultEntry(e,t,n){if(Pu(e))return this.limitImageContent(e,t,n);if(gn(e))return this.limitNestedMedia(e,t,n);return e}limitNestedMedia(e,t,n){if(Pu(e)){let r=this.limitImageContent(e,t,n);return r.type==="text"?r.text:r}if(Array.isArray(e)){let r=!1,o=e.map((s)=>{let i=this.limitNestedMedia(s,t,n);if(i!==s)r=!0;return i});return r?o:e}if(e!==null&&typeof e==="object"){let r=!1,o={};for(let[s,i]of Object.entries(e)){let a=this.limitNestedMedia(i,t,n);if(a!==i)r=!0;o[s]=a}return r?o:e}return e}limitImageContent(e,t,n){if(!GS(e))return{type:"text",text:FS};let r=CL(e.mediaType,e.data,{maxImageEncodedBytes:t.maxImageEncodedBytes,maxImageDecodedBytes:t.maxImageDecodedBytes,maxTotalMediaBytes:t.maxTotalMediaBytes},n);if(!r.ok)return{type:"text",text:FS};return{...e,data:r.base64,mediaType:r.mediaType}}}var jS=String.raw`[\|\uFF5C]`,NL=new RegExp(String.raw`<\s*(?:${jS}\s*)?DSML\s*(?:${jS}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function pe(e){return Buffer.byteLength(e,"utf8")}function zS(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function DL(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="infinity"||t==="disable")return Number.POSITIVE_INFINITY;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:void 0}function Go(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0?Math.floor(e):t}function UL(e,t){if(typeof e!=="number"||Number.isNaN(e)||e<0)return t;return Number.isFinite(e)?Math.floor(e):e}function Vo(e,t,n){if(e.length<=t)return e;let r=n(e.length-t),o=Math.max(0,Math.floor((t-r.length)/2)),s=Math.max(0,e.length-o*2),i=n(s),a=Math.max(0,Math.floor((t-i.length)/2)),d=e.slice(0,a),c=a>0?e.slice(-a):"";return`${d}${i}${c}`}function FL(e,t,n){if(pe(e)<=t)return e;let r=0,o=e.length,s="";while(r<=o){let i=r+o>>>1,a=Vo(e,i,n);if(pe(a)<=t)s=a,r=i+1;else o=i-1}return s}function HL(e){if(e.type==="tool_use")return{...e,input:Da(e.input)};if(e.type!=="tool_result"||typeof e.content==="string")return{...e};return{...e,content:e.content.map((t)=>gn(t)?Da(t):{...t})}}function gn(e){if(e===null||typeof e!=="object")return!1;let t=e.type;return t!=="text"&&t!=="image"&&t!=="file"}function Pu(e){return e!==null&&typeof e==="object"&&e.type==="image"}function GS(e){return e!==null&&typeof e==="object"&&e.type==="image"&&typeof e.data==="string"&&typeof e.mediaType==="string"}function Mu(e){return GS(e)}function La(e){if(typeof e==="string")return pe(e);if(Array.isArray(e)){let t=0;for(let n of e)t+=La(n);return t}if(e!==null&&typeof e==="object"){if(Mu(e))return 0;let t=0;for(let n of Object.values(e))t+=La(n);return t}return 0}function Na(e,t){if(Array.isArray(e)){e.forEach((n,r)=>{if(typeof n==="string")t.push({byteLength:pe(n),minBytes:Xo,makeMarker:Jo,get:()=>e[r],set:(o)=>{e[r]=o}});else Na(n,t)});return}if(e!==null&&typeof e==="object"){if(Mu(e))return;let n=e;for(let r of Object.keys(n)){let o=n[r];if(typeof o==="string")t.push({byteLength:pe(o),minBytes:Xo,makeMarker:Jo,get:()=>n[r],set:(s)=>{n[r]=s}});else Na(o,t)}}}function Da(e){if(Array.isArray(e))return e.map(Da);if(e!==null&&typeof e==="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Da(r);return t}return e}function Ou(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class Lu{messages=[];conversationId=Ou();sessionStarted=!1;constructor(e){if((e?.length??0)>0)this.restore(e??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(e){this.messages.push(e)}appendMessages(e){if(e.length===0)return;this.messages.push(...e)}replaceMessages(e){let t=new Map(e.map((o,s)=>[o.id,s])),n=new Map,r=-1;for(let o of this.messages){let s=o.id?t.get(o.id):void 0;if(s!==void 0)r=s;else if(o.metadata?.displayOnly===!0){let i=n.get(r)??[];i.push(o),n.set(r,i)}}this.messages=[...n.get(-1)??[]];for(let[o,s]of e.entries())this.messages.push(s,...n.get(o)??[])}resetForRun(){this.messages=[],this.conversationId=Ou(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=Ou(),this.sessionStarted=!1}restore(e){this.messages=[...e],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}var Wr="0.0.94-nightly.1792204233";var qr={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Wr,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","proxy-from-env":"^2.1.0","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/proxy-from-env":"^1.0.4","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};function XS(e){let{agentConfig:t}=e,n=BL(t),r=$L(t),o=e.hooks,s=WL(t.maxParallelToolCalls);return{distinctId:t.distinctId,clientName:t.extensionContext?.client?.name,clientVersion:t.extensionContext?.client?.version,clineCoreVersion:Wr,sessionId:e.sessionId??t.sessionId,agentId:e.agentId,conversationId:e.conversationId,parentAgentId:e.parentAgentId,agentRole:e.agentRole,systemPrompt:e.systemPrompt??t.systemPrompt,messageModelInfo:r,model:e.model,modelOptions:n,modelTools:t.modelTools,tools:e.tools,hooks:o,prepareTurn:e.prepareTurn,consumePendingUserMessage:t.consumePendingUserMessage,plugins:e.plugins,logger:e.logger??t.logger,telemetry:e.telemetry??t.telemetry,initialMessages:e.initialMessages,completionPolicy:e.completionPolicy===null?void 0:e.completionPolicy??t.completionPolicy,maxIterations:t.maxIterations,toolExecution:s,toolPolicies:t.toolPolicies,toolContextMetadata:e.toolContextMetadata,requestToolApproval:t.requestToolApproval}}function BL(e){let t={};if(e.thinking!==void 0)t.thinking=e.thinking;if(e.reasoningEffort!==void 0)t.reasoningEffort=e.reasoningEffort;if(e.thinkingBudgetTokens!==void 0)t.thinkingBudgetTokens=e.thinkingBudgetTokens;if(e.maxTokensPerTurn!==void 0)t.maxTokensPerTurn=e.maxTokensPerTurn;if(e.temperature!==void 0)t.temperature=e.temperature;if(e.apiTimeoutMs!==void 0)t.apiTimeoutMs=e.apiTimeoutMs;return Object.keys(t).length>0?t:void 0}function $L(e){let t=e.providerConfig?.family;return{id:e.modelId,provider:e.providerId,family:t}}function WL(e){if(e===void 0)return;return e>=2?"parallel":"sequential"}function jr(e){let t={...e},n=Object.hasOwn(e,"thinking"),r=Object.hasOwn(e,"thinkingBudgetTokens");if(e.thinking===!1||e.thinking===null)return t.reasoningEffort=void 0,t.thinkingBudgetTokens=void 0,t;if(!n&&r&&typeof e.thinkingBudgetTokens==="number"&&Number.isFinite(e.thinkingBudgetTokens)&&e.thinkingBudgetTokens>0)t.thinking=!0;return t}function qL(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function jL(e){e.lastToolName="",e.lastToolSignature="",e.consecutiveIdenticalCount=0}function Nu(e){if(e==null||typeof e!=="object")return e;if(Array.isArray(e))return e.map(Nu);let t={};for(let n of Object.keys(e).sort())t[n]=Nu(e[n]);return t}function zL(e){if(e==null)return"null";if(typeof e==="string")return e;if(typeof e!=="object")return String(e);try{return JSON.stringify(Nu(e))}catch{return String(e)}}function KL(e,t,n,r){if(t===e.lastToolName&&n===e.lastToolSignature)e.consecutiveIdenticalCount++;else e.consecutiveIdenticalCount=1;return e.lastToolName=t,e.lastToolSignature=n,{softWarning:e.consecutiveIdenticalCount===r.softThreshold,hardEscalation:e.consecutiveIdenticalCount>=r.hardThreshold}}var JS={softThreshold:3,hardThreshold:5};class Du{config;state=qL();constructor(e){this.config={softThreshold:e?.softThreshold??JS.softThreshold,hardThreshold:e?.hardThreshold??JS.hardThreshold}}inspect(e){let t=zL(e.input),n=KL(this.state,e.name,t,this.config);if(n.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${e.name}\`; stopping to avoid a loop.`};if(n.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${e.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){jL(this.state)}}class Uu{consecutiveMistakes=0;options;constructor(e){this.options=e}async record(e){let t=this.options.maxConsecutiveMistakes,n=e.forceAtLimit&&t?t:this.consecutiveMistakes+1;this.consecutiveMistakes=n;let r=e.details?.trim()||`consecutive mistake (${e.reason})`;if(this.options.emit({type:"error",error:Error(r),recoverable:!0,iteration:e.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:e.iteration,reason:e.reason,details:e.details,consecutiveMistakes:n,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!t||n<t)return{action:"continue"};let o={iteration:e.iteration,consecutiveMistakes:n,maxConsecutiveMistakes:t,reason:e.reason,details:e.details};this.options.onLimitTelemetry?.(o);let s=await VL(o,this.options.onLimitReached);if(s.action==="continue"){let i=s.guidance?.trim();if(i)this.options.appendRecoveryNotice(i,e.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:i}}return{action:"stop",reason:s.reason?.trim()||void 0,message:GL({iteration:e.iteration,consecutiveMistakes:n,maxConsecutiveMistakes:t,reason:e.reason,details:e.details,stopReason:s.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function GL(e){let t=[`Stopped after ${e.consecutiveMistakes}/${e.maxConsecutiveMistakes} consecutive mistakes (${e.reason}) at iteration ${e.iteration}.`],n=e.details?.trim();if(n)t.push(`Error: ${n}`);let r=e.stopReason?.trim();if(r)t.push(`Decision: ${r}`);return t.push("Session state was preserved. Send a new prompt to resume from the latest state."),t.join(" ")}async function VL(e,t){if(!t)return{action:"stop",reason:`maximum consecutive mistakes reached (${e.maxConsecutiveMistakes})`};try{return await t(e)}catch(n){return{action:"stop",reason:n instanceof Error?n.message:`maximum consecutive mistakes reached (${e.maxConsecutiveMistakes})`}}}function XL(e){switch(e){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return e;default:return}}function JL(e){let t=e.content.filter((n)=>n.type==="text");if(t.length===0)return;return t.map((n)=>n.text).join("")}function YL(e){let t=e.content.filter((n)=>n.type==="reasoning");if(t.length===0)return;return{reasoning:t.map((n)=>n.text).join(""),redacted:t.some((n)=>n.redacted===!0)}}function QL(e){return e.content.find((t)=>t.type==="tool-result")}function ZL(e){switch(e){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function eN(e){if(!e||e.isError!==!0)return;if(typeof e.output==="string")return e.output;if(e.output instanceof Error)return e.output.message;try{return JSON.stringify(e.output)}catch{return String(e.output)}}class Fu{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0,reasoningTokenCount:0};toolStartedAt=new Map;translate(e){switch(e.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:e.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:e.iteration,hadToolCalls:e.toolCallCount>0,toolCallCount:e.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:e.text,accumulated:e.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:e.text,redacted:e.redacted===!0}];case"assistant-media":return[{type:"content_end",contentType:"media",media:e.media}];case"assistant-message":return this.translateAssistantMessage(e.message);case"tool-started":return this.translateToolStarted(e);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,update:e.update}];case"tool-finished":return this.translateToolFinished(e);case"usage-updated":return this.translateUsage(e.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:e.message,reason:XL(e.metadata?.reason),metadata:e.metadata}];case"run-finished":return this.translateRunFinished(e.result);case"run-failed":return[{type:"error",error:e.error,errorClass:e.errorClass,recoverable:!1,iteration:e.snapshot.iteration}];default:return e}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0,reasoningTokenCount:0},this.toolStartedAt.clear()}translateAssistantMessage(e){let t=[],n=JL(e);if(n!==void 0)t.push({type:"content_end",contentType:"text",text:n});let r=YL(e);if(r!==void 0)t.push({type:"content_end",contentType:"reasoning",reasoning:r.reasoning});return t}translateToolStarted(e){return this.toolStartedAt.set(e.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input,execution:e.toolCall.execution}]}translateToolFinished(e){let t=this.toolStartedAt.get(e.toolCall.toolCallId),n=t===void 0?void 0:Date.now()-t;this.toolStartedAt.delete(e.toolCall.toolCallId);let r=QL(e.message),o=r?.output,s=eN(r);return[{type:"content_end",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,output:o,error:s,durationMs:n,execution:e.toolCall.execution}]}translateUsage(e){let t=e.inputTokens-this.lastUsage.inputTokens,n=e.outputTokens-this.lastUsage.outputTokens,r=e.cacheReadTokens-this.lastUsage.cacheReadTokens,o=e.cacheWriteTokens-this.lastUsage.cacheWriteTokens,s=this.lastUsage.totalCost??0,a=(e.totalCost??0)-s,d=this.lastUsage.reasoningTokenCount??0,l=(e.reasoningTokenCount??0)-d;return this.lastUsage={inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,totalCost:e.totalCost,reasoningTokenCount:e.reasoningTokenCount},[{type:"usage",inputTokens:Math.max(0,t),outputTokens:Math.max(0,n),cacheReadTokens:r===0?void 0:Math.max(0,r),cacheWriteTokens:o===0?void 0:Math.max(0,o),cost:a===0?void 0:a,reasoningTokenCount:l===0?void 0:Math.max(0,l),totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalCacheReadTokens:e.cacheReadTokens===0?void 0:e.cacheReadTokens,totalCacheWriteTokens:e.cacheWriteTokens===0?void 0:e.cacheWriteTokens,totalCost:e.totalCost}]}translateRunFinished(e){let t={inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens,cacheReadTokens:e.usage.cacheReadTokens===0?void 0:e.usage.cacheReadTokens,cacheWriteTokens:e.usage.cacheWriteTokens===0?void 0:e.usage.cacheWriteTokens,totalCost:e.usage.totalCost};return[{type:"done",reason:ZL(e.status),text:e.outputText,iterations:e.iterations,usage:t}]}}var lN="session_run_in_progress";class tb extends Error{agentId;code=lN;constructor(e){super(`SessionRuntime.shutdown called while a run is in progress${e?` (agentId=${e})`:""}`);this.agentId=e;this.name="SessionRunInProgressError"}}function pN(e){if(typeof e==="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}async function mN(e){let n=(typeof e.content==="function"?await e.content():e.content).trim();return n.length>0?n:void 0}function gN(e,t){let n=e.trim(),r=t.map((o)=>o.trim()).filter(Boolean).join(`
257
+ `;function KS(e=process.env){return{maxToolResultChars:zS(e[Ru.maxToolResultChars]),maxTotalTextBytes:zS(e[Ru.maxTotalTextBytes]),minOutdatedRewriteBytes:DL(e[Ru.minOutdatedRewriteBytes])}}class xu{recoveryNotices=new WeakSet;getToolResultRecovery;recoveryNoticeBytes=0;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor(e={}){this.getToolResultRecovery=e.getToolResultRecovery,this.maxToolResultChars=Go(e.maxToolResultChars,_u),this.maxFileContentChars=Go(e.maxFileContentChars,AL),this.maxTotalTextBytes=Go(e.maxTotalTextBytes,EL),this.mediaBudget=e.mediaBudget??{},this.maxAssistantTextChars=Go(e.maxAssistantTextChars,RL),this.maxAssistantToolMarkupChars=Go(e.maxAssistantToolMarkupChars,PL),this.minOutdatedRewriteBytes=UL(e.minOutdatedRewriteBytes,_L)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi(e){this.recoveryNoticeBytes=0,this.reindex(e),this.commitOutdatedRewrites(e);let n=this.addMissingToolResults(e).map((o)=>{if(!Array.isArray(o.content)){if(o.role==="user"&&typeof o.content==="string"){let a=HS(o.content);if(a!==o.content)return{...o,content:a}}if(o.role==="assistant"&&typeof o.content==="string"){let a=this.truncateAssistantText(o.content);if(a!==o.content)return{...o,content:a}}return o}let s=!1,i=o.content.map((a)=>{let d=this.transformBlock(a,o.role);if(d!==a)s=!0;return d});return s?{...o,content:i}:o}),r=this.applyMediaBudget(n);return this.truncateToTotalTextBudget(r)}transformBlock(e,t){if(t==="user"&&e.type==="text"&&typeof e.text==="string"){let s=HS(e.text);if(s!==e.text)return{...e,text:s};return e}if(t==="assistant"&&e.type==="text"&&typeof e.text==="string"){let s=this.truncateAssistantText(e.text);return s===e.text?e:{...e,text:s}}if(e.type==="file"){let s=Vo(e.content,this.maxFileContentChars,WS);return s===e.content?e:{...e,content:s}}if(e.type!=="tool_result")return e;let n=this.resolveToolName(e),r=this.getToolResultRecovery?.({...e,name:n??e.name});if(r){let{text:s,images:i}=Ia(e.content);if(typeof s==="string"&&s.length>this.maxToolResultChars){let a=[{type:"text",text:this.truncateMiddle(s)},...i];if(r.uri){let d={type:"text",text:`Full result is temporarily saved to ${r.uri}. Only read_files can access this cache URI. Use read_files with specific line ranges if omitted content is needed.`},c=pe(d.text);if(this.recoveryNoticeBytes+c<=this.maxTotalTextBytes/2)this.recoveryNoticeBytes+=c,this.recoveryNotices.add(d),a.push(d)}return{...e,content:a}}}let o=e.content;if(this.isReadTool(n)&&e.is_error!==!0){let s=this.committedOutdatedRewrites.get(e.tool_use_id);if(s&&s.size>0){let a=this.getReadLocators(e).filter((d)=>s.has(this.toReadLocatorKey(d))&&this.isOutdatedReadLocator(d,e.tool_use_id));if(a.length>0)o=this.replaceOutdatedReadContent(o,a)}}return o=this.truncateToolResultContent(o),o===e.content?e:{...e,content:o}}reindex(e){let t=this.indexedMessageCount===0||e.length>=this.indexedMessageCount&&e[this.indexedMessageCount-1]===this.indexedTailRef;if(e.length<this.indexedMessageCount||!t)this.resetIndexes();for(let n=this.indexedMessageCount;n<e.length;n++){let r=e[n];if(!Array.isArray(r.content))continue;for(let o=0;o<r.content.length;o++){let s=r.content[o];if(s.type==="file")this.latestFullContentOwnerByPathCache.set(s.path,`file:${n}:${o}`);else if(s.type==="tool_use"){let i=s.name.toLowerCase();if(this.toolNameByIdCache.set(s.id,i),this.isReadTool(i)){let a=this.extractLocatorsFromReadToolInput(s.input);if(a.length>0)this.readLocatorsByToolUseIdCache.set(s.id,a)}}else if(s.type==="tool_result"){let i=this.resolveToolName(s);if(!this.isReadTool(i)||s.is_error===!0)continue;let a=this.getReadLocators(s);for(let d of a)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(d),s.tool_use_id),this.isFullFileRead(d))this.latestFullContentOwnerByPathCache.set(d.path,s.tool_use_id)}}}this.indexedMessageCount=e.length,this.indexedTailRef=e.length>0?e[e.length-1]:void 0}commitOutdatedRewrites(e){let t=new Map,n=new Set,r=0;for(let o of e){if(!Array.isArray(o.content))continue;for(let s of o.content){if(s.type!=="tool_result"||s.is_error===!0)continue;let i=this.resolveToolName(s);if(!this.isReadTool(i))continue;n.add(s.tool_use_id);let a=this.committedOutdatedRewrites.get(s.tool_use_id),d=new Set,c=new Set;for(let u of this.getReadLocators(s)){let p=this.toReadLocatorKey(u);if(!this.isOutdatedReadLocator(u,s.tool_use_id))continue;if(c.add(p),!a?.has(p))d.add(p)}if(a){for(let u of a)if(!c.has(u))a.delete(u);if(a.size===0)this.committedOutdatedRewrites.delete(s.tool_use_id)}if(d.size===0)continue;let l=t.get(s.tool_use_id);if(!l)l=new Set,t.set(s.tool_use_id,l);for(let u of d)l.add(u);r+=this.estimateOutdatedReclaimBytes(s.content,d)}}for(let o of this.committedOutdatedRewrites.keys())if(!n.has(o))this.committedOutdatedRewrites.delete(o);if(t.size===0||r<this.minOutdatedRewriteBytes)return;for(let[o,s]of t){let i=this.committedOutdatedRewrites.get(o);if(!i)i=new Set,this.committedOutdatedRewrites.set(o,i);for(let a of s)i.add(a)}}estimateOutdatedReclaimBytes(e,t){let n=this.extractReadLocatorsFromToolResultContent(e),r=n.length>0&&n.every((d)=>t.has(this.toReadLocatorKey(d))),o=(d)=>{let c;try{c=JSON.parse(d)}catch{return r||n.length===0?pe(this.truncateMiddle(d)):0}let l=Array.isArray(c)?c:[c],u=0;for(let p of l){let m=this.extractLocatorFromResultEntry(p);if(m&&t.has(this.toReadLocatorKey(m)))u+=this.providerBoundEntryBytes(p)}return u};if(typeof e==="string")return o(e);let s=new Set(t),i=0;for(let d of e)if(d.type==="text")i+=this.countOutdatedImageEntries(d.text,s);let a=0;for(let d of e)if(d.type==="text")a+=o(d.text);else if(d.type==="image"){if(i>0)i-=1,a+=pe(d.data)}else if(gn(d)){let c=this.extractLocatorFromResultEntry(d);if(c&&t.has(this.toReadLocatorKey(c)))a+=this.providerBoundEntryBytes(d)}else if(d.type==="file"){if(t.has(this.toReadLocatorKey({path:d.path,startLine:null,endLine:null})))a+=pe(this.truncateMiddle(d.content))}return a}providerBoundEntryBytes(e){let t=this.truncateNestedStrings(e);return pe(JSON.stringify(t))}addMissingToolResults(e){let t=this.collectToolResultIds(e),n=[],r=new Map,o=!1,s=()=>{if(r.size===0)return;i(this.createMissingToolResultMessage(r)),r.clear(),o=!0},i=(a)=>{let d=n.at(-1);if(this.shouldMergeUserAfterToolResults(d,a)){n[n.length-1]={...d,content:[...d.content,...this.contentBlocksForUserMerge(a.content)]},o=!0;return}n.push(a)};for(let a of e){if(this.isToolResultOnlyMessage(a)){if(i(this.appendMissingToolResults(a,r)),r.size>0)r.clear(),o=!0;continue}if(Array.isArray(a.content)){let d=a.content.filter((l)=>l.type==="tool_result"),c=a.content.filter((l)=>l.type!=="tool_result");if(d.length>0){let l=this.appendMissingToolResults({...a,role:"user",content:d},r);if(i(l),r.size>0)r.clear();o=!0}if(c.length>0||d.length===0){if(d.length===0)s();let l=d.length>0?{...a,content:c}:a;if(i(l),l.role==="assistant")this.trackMissingToolCalls(l,t,r)}continue}s(),i(a)}return s(),o?n:e}appendMissingToolResults(e,t){if(t.size===0||!Array.isArray(e.content))return e;return{...e,role:"user",content:[...e.content,...this.createMissingToolResultBlocks(t)]}}shouldMergeUserAfterToolResults(e,t){return e?.role==="user"&&t.role==="user"&&this.isToolResultOnlyMessage(e)&&this.contentBlocksForUserMerge(t.content).length>0}contentBlocksForUserMerge(e){return typeof e==="string"?e.length>0?[{type:"text",text:e}]:[]:e}collectToolResultIds(e){let t=new Set;for(let n of e){if(!Array.isArray(n.content))continue;for(let r of n.content)if(r.type==="tool_result")t.add(r.tool_use_id)}return t}isToolResultOnlyMessage(e){return e.role==="user"&&Array.isArray(e.content)&&e.content.length>0&&e.content.every((t)=>t.type==="tool_result")}trackMissingToolCalls(e,t,n){if(!Array.isArray(e.content))return;for(let r of e.content){if(r.type!=="tool_use"||t.has(r.id))continue;n.set(r.id,r.name)}}createMissingToolResultMessage(e){return{role:"user",content:this.createMissingToolResultBlocks(e)}}createMissingToolResultBlocks(e){return Array.from(e,([t,n])=>({type:"tool_result",tool_use_id:t,name:n,content:[{type:"text",text:this.formatMissingToolResultText(n)}],is_error:!0}))}formatMissingToolResultText(e){return e?`${$S} Tool: ${e}.`:$S}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators(e){let t=e,n=this.readResultLocatorCache.get(t);if(n===void 0)n=this.extractReadLocatorsFromToolResultContent(e.content),this.readResultLocatorCache.set(t,n);if(n.length>0)return n;return this.readLocatorsByToolUseIdCache.get(e.tool_use_id)??[]}extractLocatorsFromReadToolInput(e){if(!e||typeof e!=="object")return[];let t=e,n=[],r=this.extractLocatorFromReadRequest(t);if(r)n.push(r);if(Array.isArray(t.files))for(let o of t.files){let s=this.extractLocatorFromReadRequest(o);if(s)n.push(s)}if(Array.isArray(t.file_paths)){for(let o of t.file_paths)if(typeof o==="string"&&o.length>0)n.push({path:o,startLine:null,endLine:null})}return this.dedupeReadLocators(n)}extractReadLocatorsFromToolResultContent(e){if(typeof e==="string")return this.tryParseReadLocators(e);let t=[];for(let n of e){if(n.type==="text"){t.push(...this.tryParseReadLocators(n.text));continue}if(gn(n)){let r=this.extractLocatorFromResultEntry(n);if(r)t.push(r)}}return this.dedupeReadLocators(t)}tryParseReadLocators(e){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(e))}catch{return[]}}extractLocatorsFromParsedReadResult(e){if(Array.isArray(e)){let n=[];for(let r of e){let o=this.extractLocatorFromResultEntry(r);if(o)n.push(o)}return this.dedupeReadLocators(n)}let t=this.extractLocatorFromResultEntry(e);return t?[t]:[]}extractLocatorFromReadRequest(e){if(!e||typeof e!=="object")return;let t=e,n=this.extractPath(t);if(!n)return;return{path:n,startLine:this.extractLineNumber(t.start_line),endLine:this.extractLineNumber(t.end_line)}}extractLocatorFromResultEntry(e){if(!e||typeof e!=="object")return;let t=e,n=this.extractPath(t);if(n)return{path:n,startLine:this.extractLineNumber(t.start_line),endLine:this.extractLineNumber(t.end_line)};if(typeof t.query==="string"&&t.query.length>0)return this.parseReadQuery(t.query);return}extractPath(e){let t=[e.path,e.file_path,e.filePath];for(let n of t)if(typeof n==="string"&&n.length>0)return n;return}extractLineNumber(e){return typeof e==="number"&&Number.isInteger(e)?e:null}parseReadQuery(e){let t=/^(.*):(\d+)-(EOF|\d+)$/.exec(e);if(!t)return{path:e,startLine:null,endLine:null};return{path:t[1],startLine:Number(t[2]),endLine:t[3]==="EOF"?null:Number(t[3])}}dedupeReadLocators(e){let t=new Map;for(let n of e)t.set(this.toReadLocatorKey(n),n);return Array.from(t.values())}toReadLocatorKey(e){if(this.isFullFileRead(e))return e.path;return`${e.path}:${e.startLine??1}-${e.endLine??"EOF"}`}isFullFileRead(e){return e.startLine==null&&e.endLine==null}isOutdatedReadLocator(e,t){let n=this.latestFullContentOwnerByPathCache.get(e.path);if(n&&n!==t)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(e))!==t}replaceOutdatedReadContent(e,t){let n=new Set(t.map((s)=>this.toReadLocatorKey(s))),r=new Set(t.map((s)=>s.path));if(typeof e==="string")return this.replaceOutdatedInString(e,n)??qn;let o=0;for(let s of e)if(s.type==="text")o+=this.countOutdatedImageEntries(s.text,n);return e.map((s)=>{if(s.type==="file"){if(!r.has(s.path))return s;return{...s,content:qn}}if(s.type==="image"){if(o===0)return s;return o-=1,{type:"text",text:qn}}if(gn(s))return this.replaceOutdatedReadEntry(s,n);if(s.type!=="text")return s;let i=this.replaceOutdatedInString(s.text,n);if(i===null)return{...s,text:qn};return i===s.text?s:{...s,text:i}})}countOutdatedImageEntries(e,t){let n;try{n=JSON.parse(e)}catch{return 0}let r=Array.isArray(n)?n:[n],o=0;for(let s of r){if(!s||typeof s!=="object")continue;let i=s,a=this.extractLocatorFromResultEntry(i);if(!a)continue;if(!t.has(this.toReadLocatorKey(a)))continue;if(i.result==="Successfully read image"||i.content==="Successfully read image")o+=1}return o}replaceOutdatedInString(e,t){let n;try{n=JSON.parse(e)}catch{return null}let r=Array.isArray(n)?n.map((o)=>this.replaceOutdatedReadEntry(o,t)):this.replaceOutdatedReadEntry(n,t);return JSON.stringify(r)}replaceOutdatedReadEntry(e,t){if(!e||typeof e!=="object")return e;let n=this.extractLocatorFromResultEntry(e);if(!n||!t.has(this.toReadLocatorKey(n)))return e;let r={...e};if(typeof r.result==="string")r.result=qn;else if(typeof r.content==="string")r.content=qn;else r.result=qn;return r}isReadTool(e){return!!e&&ML.has(e)}resolveToolName(e){let t=this.toolNameByIdCache.get(e.tool_use_id);if(t!==void 0)return t;return typeof e.name==="string"&&e.name.length>0?e.name.toLowerCase():void 0}truncateToolResultContent(e){if(typeof e==="string")return this.truncateMiddle(e);return e.map((t)=>{if(this.recoveryNotices.has(t))return t;if(t.type==="file"){let n=this.truncateMiddle(t.content);return n===t.content?t:{...t,content:n}}if(t.type==="text"){let n=this.truncateMiddle(t.text);return n===t.text?t:{...t,text:n}}if(gn(t))return this.truncateNestedStrings(t);return t})}truncateNestedStrings(e){if(typeof e==="string")return this.truncateMiddle(e);if(Array.isArray(e)){let t=!1,n=e.map((r)=>{let o=this.truncateNestedStrings(r);if(o!==r)t=!0;return o});return t?n:e}if(e!==null&&typeof e==="object"){if(Mu(e))return e;let t=!1,n={};for(let[r,o]of Object.entries(e)){let s=this.truncateNestedStrings(o);if(s!==o)t=!0;n[r]=s}return t?n:e}return e}truncateMiddle(e){return Vo(e,this.maxToolResultChars,WS)}truncateAssistantText(e){if(this.hasRepeatedToolCallMarkup(e))return Vo(e,this.maxAssistantToolMarkupChars,LL);return Vo(e,this.maxAssistantTextChars,OL)}hasRepeatedToolCallMarkup(e){if(e.length<=this.maxAssistantToolMarkupChars)return!1;let t=0;for(let n of e.matchAll(NL))if(t+=1,t>=xL)return!0;return!1}truncateToTotalTextBudget(e){let t=this.countMessageTextBytes(e);if(t<=this.maxTotalTextBytes)return e;let n=e.map((s)=>{if(!Array.isArray(s.content))return{...s};return{...s,content:s.content.map((i)=>{let a=HL(i);if(i.type==="tool_result"&&a.type==="tool_result"&&Array.isArray(i.content)&&Array.isArray(a.content))i.content.forEach((d,c)=>{if(this.recoveryNotices.has(d))this.recoveryNotices.add(a.content[c])});return a})}}),r=this.collectTruncationCandidates(n),o=Math.floor(this.maxTotalTextBytes/(2*Math.max(1,r.length)));for(let s of r){if(t<=this.maxTotalTextBytes)break;let i=s.byteLength,a=Math.min(s.minBytes,o);if(i<=a)continue;let d=t-this.maxTotalTextBytes,c=Math.max(a,i-d),l=FL(s.get(),c,s.makeMarker);s.set(l),t-=i-pe(l)}return n}countMessageTextBytes(e){let t=0;for(let n of e){if(typeof n.content==="string"){t+=pe(n.content);continue}for(let r of n.content)if(r.type==="text")t+=pe(r.text);else if(r.type==="thinking")t+=pe(r.thinking);else if(r.type==="file")t+=pe(r.content);else if(r.type==="tool_use")t+=La(r.input);else if(r.type==="tool_result"){if(typeof r.content==="string")t+=pe(r.content);else for(let o of r.content)if(o.type==="text")t+=pe(o.text);else if(o.type==="file")t+=pe(o.content);else if(gn(o))t+=La(o)}}return t}collectTruncationCandidates(e){let t=[],n=[];for(let r of e){if(r.role==="assistant"&&typeof r.content==="string"){t.push({byteLength:pe(r.content),minBytes:BS,makeMarker:qS,get:()=>r.content,set:(o)=>{r.content=o}});continue}if(!Array.isArray(r.content))continue;for(let o of r.content){if(o.type==="tool_use"){Na(o.input,n);continue}if(r.role==="assistant"&&o.type==="text"){t.push({byteLength:pe(o.text),minBytes:BS,makeMarker:qS,get:()=>o.text,set:(s)=>{o.text=s}});continue}if(o.type!=="tool_result")continue;if(typeof o.content==="string"){t.push({byteLength:pe(o.content),minBytes:Xo,makeMarker:Jo,get:()=>o.content,set:(s)=>{o.content=s}});continue}for(let s of o.content){if(this.recoveryNotices.has(s))continue;if(s.type==="text")t.push({byteLength:pe(s.text),minBytes:Xo,makeMarker:Jo,get:()=>s.text,set:(i)=>{s.text=i}});else if(s.type==="file")t.push({byteLength:pe(s.content),minBytes:Xo,makeMarker:Jo,get:()=>s.content,set:(i)=>{s.content=i}});else if(gn(s))Na(s,t)}}}return t.sort((r,o)=>o.byteLength-r.byteLength),n.sort((r,o)=>o.byteLength-r.byteLength),[...t,...n]}applyMediaBudget(e){let t=this.resolveMediaBudget();if(t.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&t.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&t.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return e;let n=kL(),r=!1,o=e.map((s)=>{if(!Array.isArray(s.content))return s;let i=!1,a=s.content.map((d)=>{let c=this.applyMediaBudgetToBlock(d,t,n);if(c!==d)i=!0;return c});if(!i)return s;return r=!0,{...s,content:a}});return r?o:e}resolveMediaBudget(){return IL(this.mediaBudget)}applyMediaBudgetToBlock(e,t,n){if(Pu(e))return this.limitImageContent(e,t,n);if(e.type!=="tool_result"||typeof e.content==="string")return e;let r=!1,o=e.content.map((s)=>{let i=this.applyMediaBudgetToToolResultEntry(s,t,n);if(i!==s)r=!0;return i});return r?{...e,content:o}:e}applyMediaBudgetToToolResultEntry(e,t,n){if(Pu(e))return this.limitImageContent(e,t,n);if(gn(e))return this.limitNestedMedia(e,t,n);return e}limitNestedMedia(e,t,n){if(Pu(e)){let r=this.limitImageContent(e,t,n);return r.type==="text"?r.text:r}if(Array.isArray(e)){let r=!1,o=e.map((s)=>{let i=this.limitNestedMedia(s,t,n);if(i!==s)r=!0;return i});return r?o:e}if(e!==null&&typeof e==="object"){let r=!1,o={};for(let[s,i]of Object.entries(e)){let a=this.limitNestedMedia(i,t,n);if(a!==i)r=!0;o[s]=a}return r?o:e}return e}limitImageContent(e,t,n){if(!GS(e))return{type:"text",text:FS};let r=CL(e.mediaType,e.data,{maxImageEncodedBytes:t.maxImageEncodedBytes,maxImageDecodedBytes:t.maxImageDecodedBytes,maxTotalMediaBytes:t.maxTotalMediaBytes},n);if(!r.ok)return{type:"text",text:FS};return{...e,data:r.base64,mediaType:r.mediaType}}}var jS=String.raw`[\|\uFF5C]`,NL=new RegExp(String.raw`<\s*(?:${jS}\s*)?DSML\s*(?:${jS}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function pe(e){return Buffer.byteLength(e,"utf8")}function zS(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function DL(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="infinity"||t==="disable")return Number.POSITIVE_INFINITY;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:void 0}function Go(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0?Math.floor(e):t}function UL(e,t){if(typeof e!=="number"||Number.isNaN(e)||e<0)return t;return Number.isFinite(e)?Math.floor(e):e}function Vo(e,t,n){if(e.length<=t)return e;let r=n(e.length-t),o=Math.max(0,Math.floor((t-r.length)/2)),s=Math.max(0,e.length-o*2),i=n(s),a=Math.max(0,Math.floor((t-i.length)/2)),d=e.slice(0,a),c=a>0?e.slice(-a):"";return`${d}${i}${c}`}function FL(e,t,n){if(pe(e)<=t)return e;let r=0,o=e.length,s="";while(r<=o){let i=r+o>>>1,a=Vo(e,i,n);if(pe(a)<=t)s=a,r=i+1;else o=i-1}return s}function HL(e){if(e.type==="tool_use")return{...e,input:Da(e.input)};if(e.type!=="tool_result"||typeof e.content==="string")return{...e};return{...e,content:e.content.map((t)=>gn(t)?Da(t):{...t})}}function gn(e){if(e===null||typeof e!=="object")return!1;let t=e.type;return t!=="text"&&t!=="image"&&t!=="file"}function Pu(e){return e!==null&&typeof e==="object"&&e.type==="image"}function GS(e){return e!==null&&typeof e==="object"&&e.type==="image"&&typeof e.data==="string"&&typeof e.mediaType==="string"}function Mu(e){return GS(e)}function La(e){if(typeof e==="string")return pe(e);if(Array.isArray(e)){let t=0;for(let n of e)t+=La(n);return t}if(e!==null&&typeof e==="object"){if(Mu(e))return 0;let t=0;for(let n of Object.values(e))t+=La(n);return t}return 0}function Na(e,t){if(Array.isArray(e)){e.forEach((n,r)=>{if(typeof n==="string")t.push({byteLength:pe(n),minBytes:Xo,makeMarker:Jo,get:()=>e[r],set:(o)=>{e[r]=o}});else Na(n,t)});return}if(e!==null&&typeof e==="object"){if(Mu(e))return;let n=e;for(let r of Object.keys(n)){let o=n[r];if(typeof o==="string")t.push({byteLength:pe(o),minBytes:Xo,makeMarker:Jo,get:()=>n[r],set:(s)=>{n[r]=s}});else Na(o,t)}}}function Da(e){if(Array.isArray(e))return e.map(Da);if(e!==null&&typeof e==="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Da(r);return t}return e}function Ou(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class Lu{messages=[];conversationId=Ou();sessionStarted=!1;constructor(e){if((e?.length??0)>0)this.restore(e??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(e){this.messages.push(e)}appendMessages(e){if(e.length===0)return;this.messages.push(...e)}replaceMessages(e){let t=new Map(e.map((o,s)=>[o.id,s])),n=new Map,r=-1;for(let o of this.messages){let s=o.id?t.get(o.id):void 0;if(s!==void 0)r=s;else if(o.metadata?.displayOnly===!0){let i=n.get(r)??[];i.push(o),n.set(r,i)}}this.messages=[...n.get(-1)??[]];for(let[o,s]of e.entries())this.messages.push(s,...n.get(o)??[])}resetForRun(){this.messages=[],this.conversationId=Ou(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=Ou(),this.sessionStarted=!1}restore(e){this.messages=[...e],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}var Wr="0.0.95";var qr={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Wr,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","proxy-from-env":"^2.1.0","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/proxy-from-env":"^1.0.4","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};function XS(e){let{agentConfig:t}=e,n=BL(t),r=$L(t),o=e.hooks,s=WL(t.maxParallelToolCalls);return{distinctId:t.distinctId,clientName:t.extensionContext?.client?.name,clientVersion:t.extensionContext?.client?.version,clineCoreVersion:Wr,sessionId:e.sessionId??t.sessionId,agentId:e.agentId,conversationId:e.conversationId,parentAgentId:e.parentAgentId,agentRole:e.agentRole,systemPrompt:e.systemPrompt??t.systemPrompt,messageModelInfo:r,model:e.model,modelOptions:n,modelTools:t.modelTools,tools:e.tools,hooks:o,prepareTurn:e.prepareTurn,consumePendingUserMessage:t.consumePendingUserMessage,plugins:e.plugins,logger:e.logger??t.logger,telemetry:e.telemetry??t.telemetry,initialMessages:e.initialMessages,completionPolicy:e.completionPolicy===null?void 0:e.completionPolicy??t.completionPolicy,maxIterations:t.maxIterations,toolExecution:s,toolPolicies:t.toolPolicies,toolContextMetadata:e.toolContextMetadata,requestToolApproval:t.requestToolApproval}}function BL(e){let t={};if(e.thinking!==void 0)t.thinking=e.thinking;if(e.reasoningEffort!==void 0)t.reasoningEffort=e.reasoningEffort;if(e.thinkingBudgetTokens!==void 0)t.thinkingBudgetTokens=e.thinkingBudgetTokens;if(e.maxTokensPerTurn!==void 0)t.maxTokensPerTurn=e.maxTokensPerTurn;if(e.temperature!==void 0)t.temperature=e.temperature;if(e.apiTimeoutMs!==void 0)t.apiTimeoutMs=e.apiTimeoutMs;return Object.keys(t).length>0?t:void 0}function $L(e){let t=e.providerConfig?.family;return{id:e.modelId,provider:e.providerId,family:t}}function WL(e){if(e===void 0)return;return e>=2?"parallel":"sequential"}function jr(e){let t={...e},n=Object.hasOwn(e,"thinking"),r=Object.hasOwn(e,"thinkingBudgetTokens");if(e.thinking===!1||e.thinking===null)return t.reasoningEffort=void 0,t.thinkingBudgetTokens=void 0,t;if(!n&&r&&typeof e.thinkingBudgetTokens==="number"&&Number.isFinite(e.thinkingBudgetTokens)&&e.thinkingBudgetTokens>0)t.thinking=!0;return t}function qL(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function jL(e){e.lastToolName="",e.lastToolSignature="",e.consecutiveIdenticalCount=0}function Nu(e){if(e==null||typeof e!=="object")return e;if(Array.isArray(e))return e.map(Nu);let t={};for(let n of Object.keys(e).sort())t[n]=Nu(e[n]);return t}function zL(e){if(e==null)return"null";if(typeof e==="string")return e;if(typeof e!=="object")return String(e);try{return JSON.stringify(Nu(e))}catch{return String(e)}}function KL(e,t,n,r){if(t===e.lastToolName&&n===e.lastToolSignature)e.consecutiveIdenticalCount++;else e.consecutiveIdenticalCount=1;return e.lastToolName=t,e.lastToolSignature=n,{softWarning:e.consecutiveIdenticalCount===r.softThreshold,hardEscalation:e.consecutiveIdenticalCount>=r.hardThreshold}}var JS={softThreshold:3,hardThreshold:5};class Du{config;state=qL();constructor(e){this.config={softThreshold:e?.softThreshold??JS.softThreshold,hardThreshold:e?.hardThreshold??JS.hardThreshold}}inspect(e){let t=zL(e.input),n=KL(this.state,e.name,t,this.config);if(n.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${e.name}\`; stopping to avoid a loop.`};if(n.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${e.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){jL(this.state)}}class Uu{consecutiveMistakes=0;options;constructor(e){this.options=e}async record(e){let t=this.options.maxConsecutiveMistakes,n=e.forceAtLimit&&t?t:this.consecutiveMistakes+1;this.consecutiveMistakes=n;let r=e.details?.trim()||`consecutive mistake (${e.reason})`;if(this.options.emit({type:"error",error:Error(r),recoverable:!0,iteration:e.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:e.iteration,reason:e.reason,details:e.details,consecutiveMistakes:n,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!t||n<t)return{action:"continue"};let o={iteration:e.iteration,consecutiveMistakes:n,maxConsecutiveMistakes:t,reason:e.reason,details:e.details};this.options.onLimitTelemetry?.(o);let s=await VL(o,this.options.onLimitReached);if(s.action==="continue"){let i=s.guidance?.trim();if(i)this.options.appendRecoveryNotice(i,e.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:i}}return{action:"stop",reason:s.reason?.trim()||void 0,message:GL({iteration:e.iteration,consecutiveMistakes:n,maxConsecutiveMistakes:t,reason:e.reason,details:e.details,stopReason:s.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function GL(e){let t=[`Stopped after ${e.consecutiveMistakes}/${e.maxConsecutiveMistakes} consecutive mistakes (${e.reason}) at iteration ${e.iteration}.`],n=e.details?.trim();if(n)t.push(`Error: ${n}`);let r=e.stopReason?.trim();if(r)t.push(`Decision: ${r}`);return t.push("Session state was preserved. Send a new prompt to resume from the latest state."),t.join(" ")}async function VL(e,t){if(!t)return{action:"stop",reason:`maximum consecutive mistakes reached (${e.maxConsecutiveMistakes})`};try{return await t(e)}catch(n){return{action:"stop",reason:n instanceof Error?n.message:`maximum consecutive mistakes reached (${e.maxConsecutiveMistakes})`}}}function XL(e){switch(e){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return e;default:return}}function JL(e){let t=e.content.filter((n)=>n.type==="text");if(t.length===0)return;return t.map((n)=>n.text).join("")}function YL(e){let t=e.content.filter((n)=>n.type==="reasoning");if(t.length===0)return;return{reasoning:t.map((n)=>n.text).join(""),redacted:t.some((n)=>n.redacted===!0)}}function QL(e){return e.content.find((t)=>t.type==="tool-result")}function ZL(e){switch(e){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function eN(e){if(!e||e.isError!==!0)return;if(typeof e.output==="string")return e.output;if(e.output instanceof Error)return e.output.message;try{return JSON.stringify(e.output)}catch{return String(e.output)}}class Fu{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0,reasoningTokenCount:0};toolStartedAt=new Map;translate(e){switch(e.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:e.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:e.iteration,hadToolCalls:e.toolCallCount>0,toolCallCount:e.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:e.text,accumulated:e.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:e.text,redacted:e.redacted===!0}];case"assistant-media":return[{type:"content_end",contentType:"media",media:e.media}];case"assistant-message":return this.translateAssistantMessage(e.message);case"tool-started":return this.translateToolStarted(e);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,update:e.update}];case"tool-finished":return this.translateToolFinished(e);case"usage-updated":return this.translateUsage(e.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:e.message,reason:XL(e.metadata?.reason),metadata:e.metadata}];case"run-finished":return this.translateRunFinished(e.result);case"run-failed":return[{type:"error",error:e.error,errorClass:e.errorClass,recoverable:!1,iteration:e.snapshot.iteration}];default:return e}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0,reasoningTokenCount:0},this.toolStartedAt.clear()}translateAssistantMessage(e){let t=[],n=JL(e);if(n!==void 0)t.push({type:"content_end",contentType:"text",text:n});let r=YL(e);if(r!==void 0)t.push({type:"content_end",contentType:"reasoning",reasoning:r.reasoning});return t}translateToolStarted(e){return this.toolStartedAt.set(e.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input,execution:e.toolCall.execution}]}translateToolFinished(e){let t=this.toolStartedAt.get(e.toolCall.toolCallId),n=t===void 0?void 0:Date.now()-t;this.toolStartedAt.delete(e.toolCall.toolCallId);let r=QL(e.message),o=r?.output,s=eN(r);return[{type:"content_end",contentType:"tool",toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,output:o,error:s,durationMs:n,execution:e.toolCall.execution}]}translateUsage(e){let t=e.inputTokens-this.lastUsage.inputTokens,n=e.outputTokens-this.lastUsage.outputTokens,r=e.cacheReadTokens-this.lastUsage.cacheReadTokens,o=e.cacheWriteTokens-this.lastUsage.cacheWriteTokens,s=this.lastUsage.totalCost??0,a=(e.totalCost??0)-s,d=this.lastUsage.reasoningTokenCount??0,l=(e.reasoningTokenCount??0)-d;return this.lastUsage={inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,totalCost:e.totalCost,reasoningTokenCount:e.reasoningTokenCount},[{type:"usage",inputTokens:Math.max(0,t),outputTokens:Math.max(0,n),cacheReadTokens:r===0?void 0:Math.max(0,r),cacheWriteTokens:o===0?void 0:Math.max(0,o),cost:a===0?void 0:a,reasoningTokenCount:l===0?void 0:Math.max(0,l),totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalCacheReadTokens:e.cacheReadTokens===0?void 0:e.cacheReadTokens,totalCacheWriteTokens:e.cacheWriteTokens===0?void 0:e.cacheWriteTokens,totalCost:e.totalCost}]}translateRunFinished(e){let t={inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens,cacheReadTokens:e.usage.cacheReadTokens===0?void 0:e.usage.cacheReadTokens,cacheWriteTokens:e.usage.cacheWriteTokens===0?void 0:e.usage.cacheWriteTokens,totalCost:e.usage.totalCost};return[{type:"done",reason:ZL(e.status),text:e.outputText,iterations:e.iterations,usage:t}]}}var lN="session_run_in_progress";class tb extends Error{agentId;code=lN;constructor(e){super(`SessionRuntime.shutdown called while a run is in progress${e?` (agentId=${e})`:""}`);this.agentId=e;this.name="SessionRunInProgressError"}}function pN(e){if(typeof e==="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}async function mN(e){let n=(typeof e.content==="function"?await e.content():e.content).trim();return n.length>0?n:void 0}function gN(e,t){let n=e.trim(),r=t.map((o)=>o.trim()).filter(Boolean).join(`
258
258
 
259
259
  `);if(n&&r)return`${n}
260
260
 
@@ -544,7 +544,7 @@ ${a}`:s.instructions}})}})}}class hw{watcher;ready;stopped=!1;constructor(e){thi
544
544
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
545
545
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
546
546
  metadata_json, transcript_path, hook_path, messages_path, updated_at
547
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.sessionId,e.source,e.pid,e.startedAt,null,null,"running",0,e.interactive?1:0,e.provider,e.model,e.cwd,e.workspaceRoot,e.teamName??null,e.enableTools?1:0,e.enableSpawn?1:0,e.enableTeams?1:0,null,null,null,null,0,e.prompt??null,e.metadata?JSON.stringify(e.metadata):null,"","",e.messagesPath,le()])}}function Sq(e){return{text:e.text,usage:e.usage,inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens,iterations:e.iterations,finishReason:e.finishReason,toolCalls:e.toolCalls.map((t)=>({name:t.name,input:t.input,output:t.output,error:t.error,durationMs:t.durationMs}))}}function bq(e){return e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act"}function xk(e={}){let t=async(r)=>r,n=new $s({sessionService:new zs(new js),capabilities:{toolExecutors:{submit:t}},fetch:e.fetch,connectorsRequest:e.connectorsRequest,telemetry:e.telemetry});return{async startSession(r,o){let s=(r.cwd?.trim()||r.workspaceRoot).trim(),i=await n.startSession({source:Pe.CORE,mode:"automation",sessionMetadata:Ze(o?.sessionMetadata,{mode:"automation",trigger:r.source}),interactive:!1,config:{providerId:yq(r.provider),modelId:r.model,apiKey:r.apiKey?.trim()||void 0,cwd:s,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:bq(r),maxIterations:r.maxIterations,enableTools:r.enableTools!==!1,enableSpawnAgent:r.enableSpawn!==!1,enableAgentTeams:r.enableTeams!==!1,disableMcpSettingsTools:r.disableMcpSettingsTools,agentPluginPaths:r.agentPluginPaths,missionLogIntervalSteps:r.missionStepInterval,missionLogIntervalMs:r.missionTimeIntervalMs},toolPolicies:r.toolPolicies??{"*":{autoApprove:r.autoApproveTools!==!1}},localRuntime:{configExtensions:r.configExtensions}});return{sessionId:i.sessionId,startResult:{sessionId:i.sessionId,manifestPath:i.manifestPath,messagesPath:i.messagesPath}}},async sendSession(r,o){let s=await n.runTurn({sessionId:r,prompt:o.prompt,userImages:o.attachments?.userImages,userFiles:o.attachments?.userFiles?.map((i)=>i.content)});if(!s)throw Error("local hub schedule runtime returned no turn result");return{result:Sq(s)}},async abortSession(r){return await n.abort(r,Error("hub schedule abort")),{applied:!0}},async stopSession(r){return await n.stopSession(r),{applied:!0}}}}import{CLINE_HUB_DEV_PORT as vq,CLINE_HUB_PORT as Tq,resolveClineBuildEnv as wq}from"@cline/shared";var kq="CLINE_HUB_HOST",Iq="CLINE_HUB_PORT",Cq="CLINE_HUB_PATHNAME",Aq="127.0.0.1",Eq=Tq,Rq="/hub";function Mk(e){return wq(e)==="development"?vq:Eq}function Pq(e={}){return(e.env??process.env)[kq]?.trim()||Aq}function cm(e={}){let n=(e.env??process.env)[Iq]?.trim();if(!n)return Mk(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return Mk(e);return r}function _q(e={}){return(e.env??process.env)[Cq]?.trim()||Rq}function um(e={},t={}){return{host:e.host??Pq(t),port:e.port??cm(t),pathname:e.pathname??_q(t)}}import{chmodSync as xq,existsSync as Mq,mkdirSync as Oq}from"node:fs";import{dirname as Lq}from"node:path";import{loadSqliteDb as Nq}from"@cline/shared/db";var Ok=3;class Lk extends Error{lockFile;constructor(e){super(`Hub instance lock is held by a live Hub: ${e}. Connect to the running Hub or diagnose it; never replace it.`);this.name="HubLockHeldError",this.lockFile=e}}function Ks(e){return e instanceof Error&&e.name==="HubLockHeldError"}function Nk(e){return`${e}.instance.lock`}class so{db;lockFile;constructor(e,t){this.lockFile=e,this.db=t}get held(){return this.db!==void 0}release(){let e=this.db;if(!e)return;this.db=void 0;try{e.exec("ROLLBACK;")}catch{}e.close?.()}static acquire(e){let t=!1,n;try{Oq(Lq(e),{recursive:!0}),t=Mq(e),n=Nq(e)}catch{return new so(e,void 0)}try{n.exec("PRAGMA busy_timeout = 0;"),n.exec("BEGIN EXCLUSIVE;")}catch(r){if(n.close?.(),Dq(r))throw new Lk(e);return new so(e,void 0)}if(!t)try{xq(e,384)}catch{}return new so(e,n)}}function Dq(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return n==="SQLITE_BUSY"||n==="SQLITE_LOCKED"||t.includes("SQLITE_BUSY")||t.includes("SQLITE_LOCKED")||t.includes("database is locked")}import{join as Zq}from"node:path";import{createHash as Uq,randomBytes as Hk}from"node:crypto";import{mkdir as pm,open as Dk,readFile as Bk,rename as Fq,rm as mm,writeFile as Hq}from"node:fs/promises";import{dirname as $k,join as gm}from"node:path";import{ensureLoopbackProxyBypass as Bq,isHubProtocolCompatible as eoe}from"@cline/shared";import{resolveClineDataDir as Ud,resolveClineDir as noe}from"@cline/shared/storage";var $q="CLINE_HUB_DISCOVERY_PATH",Wq="CLINE_HUB_BUILD_ID",qq="CLINE_HUB_BUILD_EPOCH_MS",jq=30000,zq=15000,Uk=100;function Kq(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Gq(e){return Uq("sha256").update(e).digest("hex").slice(0,12)}function Vq(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 Wk(){return Hk(32).toString("hex")}function Fk(e){return new Promise((t)=>setTimeout(t,e))}function Xq(e){return`${e}.lock`}async function Jq(e){try{let t=JSON.parse(await Bk(gm(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 lm(e){await mm(e,{recursive:!0,force:!0}).catch(()=>{return})}function or(){let e=process.env[Wq]?.trim();if(e)return e;return"sdk-v1-f5a1fc2ba8d43f15033fc87e8829924161d986b0704ba71d3b1f2052a2bf3e40".trim()||`source-${String(qr.version)}`}function qk(){let e=Number(process.env[qq]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792204255621)?1792204255621:void 0}function Fd(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Gq(e)}`,n=process.env[$q]?.trim()||gm(Ud(),"locks","hub","owners",`${Kq(t)}.json`);return{ownerId:t,discoveryPath:n}}async function Hd(e,t={}){try{let n;try{n=await Bk(e,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r;try{r=JSON.parse(n)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!r||typeof r.hubId!=="string"||typeof r.protocolVersion!=="string"||typeof r.authToken!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string"||typeof r.startedAt!=="string"||typeof r.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:r.hubId,protocolVersion:r.protocolVersion,minClientProtocolVersion:typeof r.minClientProtocolVersion==="string"?r.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof r.maxClientProtocolVersion==="string"?r.maxClientProtocolVersion:void 0,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof r.coreVersion==="string"?r.coreVersion:void 0,buildId:typeof r.buildId==="string"?r.buildId:void 0,buildEpochMs:typeof r.buildEpochMs==="number"?r.buildEpochMs:void 0,authToken:r.authToken,host:r.host,port:r.port,url:r.url,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:r.startedAt,updatedAt:r.updatedAt}}catch(n){if(t.onError==="throw")throw n;return}}async function fm(e,t){await zk(e,async()=>{let n=$k(e);await pm(n,{recursive:!0});let r=`${e}.${process.pid}.${Hk(6).toString("hex")}.tmp`,o;try{o=await Dk(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
547
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.sessionId,e.source,e.pid,e.startedAt,null,null,"running",0,e.interactive?1:0,e.provider,e.model,e.cwd,e.workspaceRoot,e.teamName??null,e.enableTools?1:0,e.enableSpawn?1:0,e.enableTeams?1:0,null,null,null,null,0,e.prompt??null,e.metadata?JSON.stringify(e.metadata):null,"","",e.messagesPath,le()])}}function Sq(e){return{text:e.text,usage:e.usage,inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens,iterations:e.iterations,finishReason:e.finishReason,toolCalls:e.toolCalls.map((t)=>({name:t.name,input:t.input,output:t.output,error:t.error,durationMs:t.durationMs}))}}function bq(e){return e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act"}function xk(e={}){let t=async(r)=>r,n=new $s({sessionService:new zs(new js),capabilities:{toolExecutors:{submit:t}},fetch:e.fetch,connectorsRequest:e.connectorsRequest,telemetry:e.telemetry});return{async startSession(r,o){let s=(r.cwd?.trim()||r.workspaceRoot).trim(),i=await n.startSession({source:Pe.CORE,mode:"automation",sessionMetadata:Ze(o?.sessionMetadata,{mode:"automation",trigger:r.source}),interactive:!1,config:{providerId:yq(r.provider),modelId:r.model,apiKey:r.apiKey?.trim()||void 0,cwd:s,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:bq(r),maxIterations:r.maxIterations,enableTools:r.enableTools!==!1,enableSpawnAgent:r.enableSpawn!==!1,enableAgentTeams:r.enableTeams!==!1,disableMcpSettingsTools:r.disableMcpSettingsTools,agentPluginPaths:r.agentPluginPaths,missionLogIntervalSteps:r.missionStepInterval,missionLogIntervalMs:r.missionTimeIntervalMs},toolPolicies:r.toolPolicies??{"*":{autoApprove:r.autoApproveTools!==!1}},localRuntime:{configExtensions:r.configExtensions}});return{sessionId:i.sessionId,startResult:{sessionId:i.sessionId,manifestPath:i.manifestPath,messagesPath:i.messagesPath}}},async sendSession(r,o){let s=await n.runTurn({sessionId:r,prompt:o.prompt,userImages:o.attachments?.userImages,userFiles:o.attachments?.userFiles?.map((i)=>i.content)});if(!s)throw Error("local hub schedule runtime returned no turn result");return{result:Sq(s)}},async abortSession(r){return await n.abort(r,Error("hub schedule abort")),{applied:!0}},async stopSession(r){return await n.stopSession(r),{applied:!0}}}}import{CLINE_HUB_DEV_PORT as vq,CLINE_HUB_PORT as Tq,resolveClineBuildEnv as wq}from"@cline/shared";var kq="CLINE_HUB_HOST",Iq="CLINE_HUB_PORT",Cq="CLINE_HUB_PATHNAME",Aq="127.0.0.1",Eq=Tq,Rq="/hub";function Mk(e){return wq(e)==="development"?vq:Eq}function Pq(e={}){return(e.env??process.env)[kq]?.trim()||Aq}function cm(e={}){let n=(e.env??process.env)[Iq]?.trim();if(!n)return Mk(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return Mk(e);return r}function _q(e={}){return(e.env??process.env)[Cq]?.trim()||Rq}function um(e={},t={}){return{host:e.host??Pq(t),port:e.port??cm(t),pathname:e.pathname??_q(t)}}import{chmodSync as xq,existsSync as Mq,mkdirSync as Oq}from"node:fs";import{dirname as Lq}from"node:path";import{loadSqliteDb as Nq}from"@cline/shared/db";var Ok=3;class Lk extends Error{lockFile;constructor(e){super(`Hub instance lock is held by a live Hub: ${e}. Connect to the running Hub or diagnose it; never replace it.`);this.name="HubLockHeldError",this.lockFile=e}}function Ks(e){return e instanceof Error&&e.name==="HubLockHeldError"}function Nk(e){return`${e}.instance.lock`}class so{db;lockFile;constructor(e,t){this.lockFile=e,this.db=t}get held(){return this.db!==void 0}release(){let e=this.db;if(!e)return;this.db=void 0;try{e.exec("ROLLBACK;")}catch{}e.close?.()}static acquire(e){let t=!1,n;try{Oq(Lq(e),{recursive:!0}),t=Mq(e),n=Nq(e)}catch{return new so(e,void 0)}try{n.exec("PRAGMA busy_timeout = 0;"),n.exec("BEGIN EXCLUSIVE;")}catch(r){if(n.close?.(),Dq(r))throw new Lk(e);return new so(e,void 0)}if(!t)try{xq(e,384)}catch{}return new so(e,n)}}function Dq(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return n==="SQLITE_BUSY"||n==="SQLITE_LOCKED"||t.includes("SQLITE_BUSY")||t.includes("SQLITE_LOCKED")||t.includes("database is locked")}import{join as Zq}from"node:path";import{createHash as Uq,randomBytes as Hk}from"node:crypto";import{mkdir as pm,open as Dk,readFile as Bk,rename as Fq,rm as mm,writeFile as Hq}from"node:fs/promises";import{dirname as $k,join as gm}from"node:path";import{ensureLoopbackProxyBypass as Bq,isHubProtocolCompatible as eoe}from"@cline/shared";import{resolveClineDataDir as Ud,resolveClineDir as noe}from"@cline/shared/storage";var $q="CLINE_HUB_DISCOVERY_PATH",Wq="CLINE_HUB_BUILD_ID",qq="CLINE_HUB_BUILD_EPOCH_MS",jq=30000,zq=15000,Uk=100;function Kq(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Gq(e){return Uq("sha256").update(e).digest("hex").slice(0,12)}function Vq(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 Wk(){return Hk(32).toString("hex")}function Fk(e){return new Promise((t)=>setTimeout(t,e))}function Xq(e){return`${e}.lock`}async function Jq(e){try{let t=JSON.parse(await Bk(gm(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 lm(e){await mm(e,{recursive:!0,force:!0}).catch(()=>{return})}function or(){let e=process.env[Wq]?.trim();if(e)return e;return"sdk-v1-d7fc6ac75da1ec6a985419452ab0576ef1178c82233d7370cd14e6261884bd99".trim()||`source-${String(qr.version)}`}function qk(){let e=Number(process.env[qq]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792205906587)?1792205906587:void 0}function Fd(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Gq(e)}`,n=process.env[$q]?.trim()||gm(Ud(),"locks","hub","owners",`${Kq(t)}.json`);return{ownerId:t,discoveryPath:n}}async function Hd(e,t={}){try{let n;try{n=await Bk(e,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r;try{r=JSON.parse(n)}catch{throw Error(`Invalid JSON in Hub discovery record: ${e}`)}if(!r||typeof r.hubId!=="string"||typeof r.protocolVersion!=="string"||typeof r.authToken!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string"||typeof r.startedAt!=="string"||typeof r.updatedAt!=="string")throw Error(`Invalid Hub discovery record: ${e}`);return{hubId:r.hubId,protocolVersion:r.protocolVersion,minClientProtocolVersion:typeof r.minClientProtocolVersion==="string"?r.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof r.maxClientProtocolVersion==="string"?r.maxClientProtocolVersion:void 0,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof r.coreVersion==="string"?r.coreVersion:void 0,buildId:typeof r.buildId==="string"?r.buildId:void 0,buildEpochMs:typeof r.buildEpochMs==="number"?r.buildEpochMs:void 0,authToken:r.authToken,host:r.host,port:r.port,url:r.url,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:r.startedAt,updatedAt:r.updatedAt}}catch(n){if(t.onError==="throw")throw n;return}}async function fm(e,t){await zk(e,async()=>{let n=$k(e);await pm(n,{recursive:!0});let r=`${e}.${process.pid}.${Hk(6).toString("hex")}.tmp`,o;try{o=await Dk(r,"wx",384),await o.writeFile(`${JSON.stringify(t,null,2)}
548
548
  `,{encoding:"utf8"}),await o.sync(),await o.close(),o=void 0,await Fq(r,e);let s;try{s=await Dk(n,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await o?.close().catch(()=>{return}),await mm(r,{force:!0}).catch(()=>{return}),s}})}async function jk(e,t){return await zk(e,async()=>{if((await Hd(e))?.hubId!==t)return!1;return await mm(e,{force:!0}),!0})}async function Yq(e,t,n){let r=Xq(e);await pm($k(r),{recursive:!0});let o=Date.now()+zq;while(!0){try{await pm(r,{recursive:!1})}catch(s){if((s instanceof Error&&"code"in s?String(s.code):"")!=="EEXIST")throw s;let a=await Jq(r);if(!a){if(Date.now()>=o){await lm(r);continue}await Fk(Uk);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!Vq(a.pid)||d>jq){await lm(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await Fk(Uk);continue}try{return await Hq(gm(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
549
549
  `,"utf8"),await n()}finally{await lm(r)}}}function zk(e,t){return Yq(`${e}.mutation`,"discovery mutation",t)}async function Gs(e,t){Bq();try{let n=await fetch(t?.authToken?Qq(e):Kk(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let r=await n.json();if(typeof r.protocolVersion!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string")return;return{protocolVersion:r.protocolVersion,minClientProtocolVersion:typeof r.minClientProtocolVersion==="string"?r.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof r.maxClientProtocolVersion==="string"?r.maxClientProtocolVersion:void 0,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof r.coreVersion==="string"?r.coreVersion:void 0,buildId:typeof r.buildId==="string"?r.buildId:void 0,buildEpochMs:typeof r.buildEpochMs==="number"?r.buildEpochMs:void 0,host:r.host,port:r.port,url:r.url,hubId:typeof r.hubId==="string"?r.hubId:void 0,authToken:typeof r.authToken==="string"?r.authToken:void 0,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:typeof r.startedAt==="string"?r.startedAt:void 0,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:void 0}}catch{return}}function io(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Kk(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function Qq(e){let t=new URL(Kk(e));return t.pathname="/status",t.toString()}var ej="shared:cline",tj="CLINE_HUB_DISCOVERY_PATH",nj="hub-production";function Bd(e=ej){return Fd(`${e}@${or()}`)}function $d(){return{ownerId:nj,discoveryPath:process.env[tj]?.trim()||Zq(Ud(),"locks","hub","production.json")}}function rj(e){if(typeof e==="string")return e.trim()||void 0;if(!Array.isArray(e))return;return e.map((n)=>{if(n&&typeof n==="object"&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text==="string")return n.text.trim();return""}).filter(Boolean).join(`
550
550
  `).trim()||void 0}var Gk=120,hm="...";function ym(e){let t=e.trim();if(!t)return"";if(Buffer.byteLength(t,"utf8")<=Gk)return t;let n=Gk-Buffer.byteLength(hm,"utf8");if(n<=0)return hm;let r="";for(let o of t){if(Buffer.byteLength(r+o,"utf8")>n)break;r+=o}return`${r}${hm}`}async function Vk(e){let t=e?.sessionId?.trim()||"unknown",n=typeof e?.metadata?.messagesPath==="string"?e.metadata.messagesPath:void 0,o=[...await nr(n)].reverse().find((d)=>d.role==="assistant"),s=o?rj(o.content):void 0,i=e?.workspaceRoot?.trim()||"workspace",a=typeof e?.metadata?.prompt==="string"?e.metadata.prompt.trim():i;return{title:`Task completed (${t})`,body:ym(s&&s.length>0?s:a.length>0?a:i),severity:"info"}}import{resolve as EG}from"node:path";import{CLINE_DEFAULT_MODEL_ID as RG,captureSdkError as ac,createSessionId as Cg,HUB_CLIENT_TOOL_APPROVAL_CAPABILITY as PG}from"@cline/shared";import{isChatWorkspacePath as _G}from"@cline/shared/storage";function Vs(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Sm(e){let t=e?.trim();return t?t:void 0}function oj(e,t){let n=e?.trim();if(!n)return t;let r=Date.parse(n);if(!Number.isFinite(r))return t;return new Date(r).toISOString()}function Xk(e,t){return new Date(new Date(e).getTime()+Math.max(0,Math.floor(t))*1000).toISOString()}function Jk(e,t){return new Date(new Date(e).getTime()-Math.max(0,Math.floor(t))*1000).toISOString()}function sj(e,t){if(!e)return t;return new Date(e).getTime()>=new Date(t).getTime()?e:t}function ij(e,t){let n=e.eventId.trim(),r=e.eventType.trim(),o=e.source.trim(),s=Sm(e.subject),i=Sm(e.dedupeKey)??`${r}:${o}:${s??n}`;return{eventId:n,eventType:r,source:o,subject:s,occurredAt:oj(e.occurredAt,t),workspaceRoot:Sm(e.workspaceRoot),payload:Vs(e.payload)?e.payload:void 0,attributes:Vs(e.attributes)?e.attributes:void 0,dedupeKey:i}}function bm(e,t){if(!t)return;let n=t.split("."),r=e;for(let o of n){if(!Vs(r))return;r=r[o]}return r}function aj(e,t){if(e.attributes&&Object.hasOwn(e.attributes,t))return e.attributes[t];if(e.payload&&Object.hasOwn(e.payload,t))return e.payload[t];let n={eventId:e.eventId,eventType:e.eventType,source:e.source,subject:e.subject,occurredAt:e.occurredAt,workspaceRoot:e.workspaceRoot,dedupeKey:e.dedupeKey,attributes:e.attributes,payload:e.payload},r=bm(n,t);if(r!==void 0)return r;if(e.attributes){let o=bm(e.attributes,t);if(o!==void 0)return o}if(e.payload)return bm(e.payload,t);return}function Wd(e,t){if(Array.isArray(t))return t.some((n)=>Wd(e,n));if(Array.isArray(e))return e.some((n)=>Wd(n,t));if(Vs(t)){if(!Vs(e))return!1;return Object.entries(t).every(([n,r])=>Wd(e[n],r))}return Object.is(e,t)}function dj(e,t){if(!t||Object.keys(t).length===0)return!0;return Object.entries(t).every(([n,r])=>Wd(aj(e,n),r))}class vm{store;nowFn;logger;constructor(e){this.store=e.store,this.nowFn=e.now??(()=>Date.now()),this.logger=e.logger}ingestEvent(e){let t=new Date(this.nowFn()).toISOString(),n=ij(e,t);try{let r=this.store.eventTransaction(()=>this.materializeEvent(n,t));return this.logger?.debug(r.duplicate?"cron.event.duplicate":"cron.event.processed",{eventId:r.event.eventId,eventType:r.event.eventType,source:r.event.source,status:r.event.processingStatus,matchedSpecCount:r.event.matchedSpecCount,queuedRunCount:r.event.queuedRunCount}),r}catch(r){throw this.logger?.error?.("cron.event.failed",{eventId:n.eventId,eventType:n.eventType,error:r}),r}}materializeEvent(e,t){let n=this.store.insertEventLog(e,{receivedAtIso:t});if(!n.created)return{event:n.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:n.record.dedupeKey}]};let r=this.store.listEventSpecsForType(e.eventType),o=[],s=[],i=[];for(let c of r){if(!dj(e,c.filters)){o.push({specId:c.specId,externalId:c.externalId,reason:"filter_mismatch",dedupeKey:e.dedupeKey});continue}s.push(c);let l=this.materializeForSpec(c,e,n.record.receivedAt);if(l.run)i.push(l.run);else o.push({specId:c.specId,externalId:c.externalId,reason:l.reason,dedupeKey:e.dedupeKey})}let a=s.length===0?"unmatched":i.length>0?"queued":"suppressed";return this.store.updateEventLogProcessing(n.record.eventId,{status:a,matchedSpecCount:s.length,queuedRunCount:i.length,suppressedCount:o.filter((c)=>c.reason!=="filter_mismatch").length}),{event:this.store.getEventLog(n.record.eventId)??n.record,duplicate:!1,matchedSpecs:s,queuedRuns:i,suppressions:o}}materializeForSpec(e,t,n){let r=t.dedupeKey??t.eventId,o=e.debounceSeconds??0;if(o>0){let d=this.store.findQueuedEventRunForDedupe({specId:e.specId,dedupeKey:r});if(d){let c=sj(d.scheduledFor,Xk(n,o)),l=this.store.updateQueuedEventRunForDebounce({runId:d.runId,triggerEventId:t.eventId,scheduledFor:c});if(l)return{run:l,reason:"dedupe_window"}}}let s=e.dedupeWindowSeconds??0;if(s>0&&this.store.hasRecentEventRunForDedupe({specId:e.specId,dedupeKey:r,sinceIso:Jk(n,s)}))return{reason:"dedupe_window"};let i=e.cooldownSeconds??0;if(i>0&&this.store.hasRecentEventRunForSpec({specId:e.specId,sinceIso:Jk(n,i)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:e.specId,specRevision:e.revision,triggerKind:"event",triggerEventId:t.eventId,scheduledFor:o>0?Xk(n,o):n}),reason:"dedupe_window"}}}class Xs{store;nowFn;constructor(e){this.store=e.store,this.nowFn=e.now??(()=>Date.now())}materializeAll(){let e={oneOffQueued:0,scheduleQueued:0},t=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let r of t)if(this.materializeOneOff(r))e.oneOffQueued+=1;let n=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let r of n)try{if(this.materializeSchedule(r))e.scheduleQueued+=1}catch{}return e}materializeOneOff(e){if(e.triggerKind!=="one_off")return!1;if(!e.enabled||e.removed)return!1;if(this.store.hasConsumedOneOffRevision(e.specId,e.revision))return!1;return this.store.enqueueRun({specId:e.specId,specRevision:e.revision,triggerKind:"one_off",scheduledFor:e.nextRunAt??new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(e){if(e.triggerKind!=="schedule")return!1;if(!e.enabled||e.removed)return!1;if(!e.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:e.specId,nowMs:this.nowFn()}).queued}}import{basename as bj}from"node:path";import{buildClineSystemPrompt as vj}from"@cline/shared";import{nowIso as tI}from"@cline/shared/db";import{mkdirSync as cj,writeFileSync as uj}from"node:fs";import{isAbsolute as lj,join as Qk}from"node:path";import{resolveCronReportsDir as pj,resolveCronSpecsDir as mj}from"@cline/shared/storage";function bn(e){if(/[:#\n]/.test(e)||e.includes('"'))return JSON.stringify(e);return e}function gt(e,t){if(t===void 0||t===null)return;return`${e}: ${bn(t)}`}function Zk(e){let t=0;for(let r of e.matchAll(/`+/g))t=Math.max(t,r[0].length);let n="`".repeat(Math.max(3,t+1));return`${n}