@cerebriline/core 4.100.257 → 4.100.258

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 sn}from"node:child_process";import{basename as To,resolve as
5
5
  ...and ${l.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
  ${m}${y}`)}let i;try{i=await t.symbolicBranch()}catch(l){let m=Q(l)===1,y=K(l),w=m?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new _(m?"detached_head":"git_command_failed",y?`${w} (${y})`:w,{cause:l})}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 u=a.slice(11),f=r;if(!Ze(r))try{f=await t.remoteUrl(r)}catch{throw new _("missing_upstream","Could not resolve the upstream remote.")}let c=Ze(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(l){let m=Q(l)===2,y=m?`The upstream branch ${u} was not found. Push it before handing off.`:"Could not verify the remote branch. Check your network and GitHub authentication, then try again.";throw new _(m?"remote_branch_missing":"git_command_failed",y)}let p=cn(h,u);if(!p)throw new _("remote_branch_missing",`The upstream branch ${u} 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 ${u}. Push the current commit before handing off.`);return{repoUrl:c,branch:u,headSha:d,...s?{workspaceRelativePath:s}:{}}}function fe(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 ln(e){return typeof e==="string"&&e.length>0?e:void 0}function pn(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=ln(e.workspaceRelativePath),a=e.mode;return{repoUrl:t,branch:n,headSha:s,modelId:o,...i?{organizationId:i}:{},...r?{workspaceRelativePath:r}:{},...a?{mode:a}:{}}}function Lo(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 fn(e){let t=fe(e);if(!t||typeof t.repoUrl!=="string"||typeof t.branch!=="string"||typeof t.headSha!=="string"||typeof t.modelId!=="string")return;try{return pn({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 Bo(e){let t=fe(fe(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=fn(t.fingerprint);return{toCloudSessionId:n,handedOffAt:s,status:o,...i?{innerSessionId:i}:{},...r?{dashboardUrl:r}:{},...a?{fingerprint:a}:{}}}function qo(e,t){return{...e??{},handoff:t}}function No(e){let{handoff:t,cloudHandoffIntent:n,cloudHandoffSeedDispatched:s,...o}=e??{};return o}function $o(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 et(e){return e.map((t)=>{let n=t&&typeof t==="object"?t:{};return{role:n.role,content:n.content}})}function he(e,t){return e.length===t.length&&JSON.stringify(et(e))===JSON.stringify(et(t))}class me extends Error{constructor(e,t){super(`Cloud transcript verification failed (local ${e} messages, cloud ${t}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as hn}from"node:crypto";import{decodeJwtPayload as mn}from"@cerebriline/shared";var gn=610000,yn=3000,B=15000,bn="CLOUD_SESSION_ERROR:",st="__cline_create_request__:";function ot(e){return(e.trim().split(`
8
- `)[0]??"").trim().slice(0,72)}class g extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${bn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class it extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function be(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function wn(e){return`${st}${e}`.slice(0,255)}function tt(e){return e?.startsWith(st)===!0}function we(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function ge(e){let t=mn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function nt(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()},yn);e.addEventListener("abort",s,{once:!0})})}function vn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function ye(e,t,n,s){let o=vn(t,`Cloud session request failed (${e})`);if(e===401)return new g("authentication_required",o);if(e===404)return new g("session_not_found",o);if(e===410)return new g("session_expired",o);if(e===412)return new g("github_not_connected",o,s??`${be(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new g("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new g("request_failed",o,void 0,e)}class Cn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=be(e.apiBaseUrl),this.appBaseUrl=be(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??gn}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 ye(401,void 0,this.appBaseUrl,n);throw f}if(!a?.trim())throw new g("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new g("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?ge(a.trim())!==s.subject:a.trim()!==s.token)throw new g("authentication_required","The signed-in account changed during cloud session creation.");s.token=a.trim()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),u=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,r=a.trim();continue}throw ye(d.status,u,this.appBaseUrl,n)}return u?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&tt(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&&tt(i.title)?{createRequestTitle:i.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let o=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:o.flatMap((i)=>{let r=Number(i.id),a=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(i.name??"").trim();return[{id:r,name:d,fullName:String(i.full_name??(d||a)).trim(),url:a,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof g&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new g("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,r=n.query?.trim(),a=n.cursor?.trim();if(r)i.set("query",r);if(a)i.set("cursor",a);let d=i.size>0?`${o}?${i}`:o;try{let u=await this.request(d),f=Array.isArray(u)?u:Array.isArray(u?.items)?u.items:[],c=r?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let p=String(h.name??"").trim();return p&&(!Array.isArray(u)||!c||p.toLowerCase().includes(c))?[p]:[]}),nextToken:Array.isArray(u)?"":String(u?.nextToken??"").trim()}}catch(u){if(u instanceof g&&u.code==="session_not_found")return{available:!1,branches:[]};throw u}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new g("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new g("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:ge(t)},s=wn(e.requestId?.trim()||hn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new g("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),r=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let p=new g(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(l){if(!(l instanceof g&&(l.code==="session_not_found"||l.code==="session_expired")))throw AggregateError([p,l],"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 g("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await r(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(p){if(p instanceof g&&(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 g("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),u,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new g("request_failed","The cloud session service returned no session id.");u=h,await this.persistHandoffOuterSession(e,h,n,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(u)throw c;let h=!f||c instanceof g&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new it(c);if(a.signal.aborted||!(c instanceof g)||c instanceof g&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let l=[];try{l=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(l.length>1)throw new g("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let m=l[0];if(m){if(e.handoff)return await r(m);return{sessionId:m.id,status:m.status,sandboxUrl:m.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof g&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject:ge(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 g&&a.code!=="request_failed")throw a;await nt(t);continue}let r=i?.status?.trim().toLowerCase();if(n?.({phase:we(i?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new g("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new g("request_failed","The cloud session service returned an unexpected provisioning status.");await nt(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof g)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new g("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw ye(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new g("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as yo}from"node:crypto";import{posix as le}from"node:path";import{createSessionId as qs,ensureLoopbackProxyBypass as qt,isHubProtocolCompatible as Ns,resolveClineBuildEnv as $s,resolveHubCommandTimeoutMs as Ws}from"@cerebriline/shared";import js from"ws";var q={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var rt="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 ve(e){return e instanceof Y||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as os}from"node:child_process";import{closeSync as is,mkdirSync as rs,openSync as as,readFileSync as ds,unlinkSync as cs}from"node:fs";import{basename as us,dirname as ls,join as ps}from"node:path";import{fileURLToPath as fs}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as hs,isBunEmbeddedModulePath as ms,isHubDaemonProcess as gs,resolveClineBuildEnv as Et,withResolvedClineBuildEnv as ys}from"@cerebriline/shared";import{createHash as kn,randomBytes as Rn}from"node:crypto";import{mkdir as Se,open as at,readFile as pt,rename as _n,rm as ke,writeFile as Pn}from"node:fs/promises";import{dirname as ft,join as Re}from"node:path";import{ensureLoopbackProxyBypass as An,isHubProtocolCompatible as Tn}from"@cerebriline/shared";import{resolveClineDataDir as N,resolveClineDir as ii}from"@cerebriline/shared/storage";var xn="CLINE_HUB_DISCOVERY_PATH",En="CLINE_HUB_BUILD_ID",Hn="CLINE_HUB_BUILD_EPOCH_MS",In=30000,Mn=15000,dt=100;function On(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Un(e){return kn("sha256").update(e).digest("hex").slice(0,12)}function Dn(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 ct(e){return new Promise((t)=>setTimeout(t,e))}function Ln(e){return`${e}.lock`}async function Bn(e){try{let t=JSON.parse(await pt(Re(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 Ce(e){await ke(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[En]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(q.version)}`}function qn(){let e=Number(process.env[Hn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792707017870)?1792707017870:void 0}function X(e,t=U()){let n=Tn(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 ut(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function lt(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 Nn(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 ht(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=ut(e.buildEpochMs),i=ut(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let r=lt(e.coreVersion),a=lt(t.coreVersion);if(r&&a){let d=Nn(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function mt(){return{buildId:U(),buildEpochMs:qn(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??mt(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return ht(n,e)<=0}function gt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Un(e)}`,n=process.env[xn]?.trim()||Re(N(),"locks","hub","owners",`${On(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e){try{let t=JSON.parse(await pt(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function yt(e,t,n){await wt(e,async()=>{let s=ft(e);await Se(s,{recursive:!0});let o=`${e}.${process.pid}.${Rn(6).toString("hex")}.tmp`,i;try{i=await at(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
8
+ `)[0]??"").trim().slice(0,72)}class g extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${bn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class it extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function be(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function wn(e){return`${st}${e}`.slice(0,255)}function tt(e){return e?.startsWith(st)===!0}function we(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function ge(e){let t=mn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function nt(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()},yn);e.addEventListener("abort",s,{once:!0})})}function vn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function ye(e,t,n,s){let o=vn(t,`Cloud session request failed (${e})`);if(e===401)return new g("authentication_required",o);if(e===404)return new g("session_not_found",o);if(e===410)return new g("session_expired",o);if(e===412)return new g("github_not_connected",o,s??`${be(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new g("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new g("request_failed",o,void 0,e)}class Cn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=be(e.apiBaseUrl),this.appBaseUrl=be(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??gn}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 ye(401,void 0,this.appBaseUrl,n);throw f}if(!a?.trim())throw new g("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new g("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?ge(a.trim())!==s.subject:a.trim()!==s.token)throw new g("authentication_required","The signed-in account changed during cloud session creation.");s.token=a.trim()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),u=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,r=a.trim();continue}throw ye(d.status,u,this.appBaseUrl,n)}return u?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&tt(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&&tt(i.title)?{createRequestTitle:i.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let o=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:o.flatMap((i)=>{let r=Number(i.id),a=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(i.name??"").trim();return[{id:r,name:d,fullName:String(i.full_name??(d||a)).trim(),url:a,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof g&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new g("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,r=n.query?.trim(),a=n.cursor?.trim();if(r)i.set("query",r);if(a)i.set("cursor",a);let d=i.size>0?`${o}?${i}`:o;try{let u=await this.request(d),f=Array.isArray(u)?u:Array.isArray(u?.items)?u.items:[],c=r?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let p=String(h.name??"").trim();return p&&(!Array.isArray(u)||!c||p.toLowerCase().includes(c))?[p]:[]}),nextToken:Array.isArray(u)?"":String(u?.nextToken??"").trim()}}catch(u){if(u instanceof g&&u.code==="session_not_found")return{available:!1,branches:[]};throw u}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new g("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new g("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:ge(t)},s=wn(e.requestId?.trim()||hn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new g("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),r=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let p=new g(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(l){if(!(l instanceof g&&(l.code==="session_not_found"||l.code==="session_expired")))throw AggregateError([p,l],"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 g("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await r(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(p){if(p instanceof g&&(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 g("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),u,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new g("request_failed","The cloud session service returned no session id.");u=h,await this.persistHandoffOuterSession(e,h,n,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(u)throw c;let h=!f||c instanceof g&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new it(c);if(a.signal.aborted||!(c instanceof g)||c instanceof g&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let l=[];try{l=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(l.length>1)throw new g("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let m=l[0];if(m){if(e.handoff)return await r(m);return{sessionId:m.id,status:m.status,sandboxUrl:m.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof g&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject:ge(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 g&&a.code!=="request_failed")throw a;await nt(t);continue}let r=i?.status?.trim().toLowerCase();if(n?.({phase:we(i?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new g("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new g("request_failed","The cloud session service returned an unexpected provisioning status.");await nt(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof g)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new g("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw ye(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new g("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as yo}from"node:crypto";import{posix as le}from"node:path";import{createSessionId as qs,ensureLoopbackProxyBypass as qt,isHubProtocolCompatible as Ns,resolveClineBuildEnv as $s,resolveHubCommandTimeoutMs as Ws}from"@cerebriline/shared";import js from"ws";var q={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var rt="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 ve(e){return e instanceof Y||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as os}from"node:child_process";import{closeSync as is,mkdirSync as rs,openSync as as,readFileSync as ds,unlinkSync as cs}from"node:fs";import{basename as us,dirname as ls,join as ps}from"node:path";import{fileURLToPath as fs}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as hs,isBunEmbeddedModulePath as ms,isHubDaemonProcess as gs,resolveClineBuildEnv as Et,withResolvedClineBuildEnv as ys}from"@cerebriline/shared";import{createHash as kn,randomBytes as Rn}from"node:crypto";import{mkdir as Se,open as at,readFile as pt,rename as _n,rm as ke,writeFile as Pn}from"node:fs/promises";import{dirname as ft,join as Re}from"node:path";import{ensureLoopbackProxyBypass as An,isHubProtocolCompatible as Tn}from"@cerebriline/shared";import{resolveClineDataDir as N,resolveClineDir as ii}from"@cerebriline/shared/storage";var xn="CLINE_HUB_DISCOVERY_PATH",En="CLINE_HUB_BUILD_ID",Hn="CLINE_HUB_BUILD_EPOCH_MS",In=30000,Mn=15000,dt=100;function On(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Un(e){return kn("sha256").update(e).digest("hex").slice(0,12)}function Dn(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 ct(e){return new Promise((t)=>setTimeout(t,e))}function Ln(e){return`${e}.lock`}async function Bn(e){try{let t=JSON.parse(await pt(Re(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 Ce(e){await ke(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[En]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(q.version)}`}function qn(){let e=Number(process.env[Hn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792737149862)?1792737149862:void 0}function X(e,t=U()){let n=Tn(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 ut(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function lt(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 Nn(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 ht(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=ut(e.buildEpochMs),i=ut(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let r=lt(e.coreVersion),a=lt(t.coreVersion);if(r&&a){let d=Nn(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function mt(){return{buildId:U(),buildEpochMs:qn(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??mt(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return ht(n,e)<=0}function gt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Un(e)}`,n=process.env[xn]?.trim()||Re(N(),"locks","hub","owners",`${On(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e){try{let t=JSON.parse(await pt(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function yt(e,t,n){await wt(e,async()=>{let s=ft(e);await Se(s,{recursive:!0});let o=`${e}.${process.pid}.${Rn(6).toString("hex")}.tmp`,i;try{i=await at(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
9
9
  `,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,n?.beforePublish?.(),await _n(o,e);let r;try{r=await at(s,"r"),await r.sync()}catch{}finally{await r?.close().catch(()=>{return})}}catch(r){throw await i?.close().catch(()=>{return}),await ke(o,{force:!0}).catch(()=>{return}),r}})}async function D(e){await wt(e,async()=>{await ke(e,{force:!0}).catch(()=>{return})})}async function bt(e,t,n){let s=Ln(e);await Se(ft(s),{recursive:!0});let o=Date.now()+Mn;while(!0){try{await Se(s,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await Bn(s);if(!a){if(Date.now()>=o){await Ce(s);continue}await ct(dt);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!Dn(a.pid)||d>In){await Ce(s);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${s}`);await ct(dt);continue}try{return await Pn(Re(s,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
10
10
  `,"utf8"),await n()}finally{await Ce(s)}}}function wt(e,t){return bt(`${e}.mutation`,"discovery mutation",t)}function vt(e,t){return bt(e,"startup",t)}async function ee(e,t){An();try{let n=await fetch(t?.authToken?$n(e):St(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 Ct(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function St(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function $n(e){let t=new URL(St(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as Wn,CLINE_HUB_PORT as jn,resolveClineBuildEnv as Fn}from"@cerebriline/shared";var zn="CLINE_HUB_HOST",Vn="CLINE_HUB_PORT",Gn="CLINE_HUB_PATHNAME",Jn="127.0.0.1",Kn=jn,Qn="/hub";function kt(e){return Fn(e)==="development"?Wn:Kn}function Yn(e={}){return(e.env??process.env)[zn]?.trim()||Jn}function Xn(e={}){let n=(e.env??process.env)[Vn]?.trim();if(!n)return kt(e);let s=Number.parseInt(n,10);if(!Number.isInteger(s)||s<1||s>65535)return kt(e);return s}function Zn(e={}){return(e.env??process.env)[Gn]?.trim()||Qn}function Rt(e={},t={}){return{host:e.host??Yn(t),port:e.port??Xn(t),pathname:e.pathname??Zn(t)}}import{join as es}from"node:path";var ts="shared:cline",ns="CLINE_HUB_DISCOVERY_PATH",ss="hub-production";function W(e=ts){return gt(`${e}@${U()}`)}function te(){return{ownerId:ss,discoveryPath:process.env[ns]?.trim()||es(N(),"locks","hub","production.json")}}var _t=15000,bs=200,Pt=3000,ws=100,vs=[100,250,500,1000,2000],Cs="--cline-hub-daemon",Ss=3,ks=60000,At=new Map;function Rs(e,t=Date.now()){let n=At.get(e);if(!n||t-n.windowStartedAt>ks)return At.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Ss}function _s(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function Ps(){try{let e=ps(N(),"logs","hub-daemon.log");return rs(ls(e),{recursive:!0}),{fd:as(e,"a"),logPath:e}}catch{return}}function As(){return Et()==="production"?te():W()}function j(e){return Z(e)}function Ts(e){try{let t=JSON.parse(ds(`${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 _e(e){try{cs(`${e}.superseded`)}catch{}}function Tt(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 xt(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await F(e))?.url)return!0;await new Promise((o)=>setTimeout(o,ws))}return!1}async function Ae(e,t){if(!Rs(e.url))return!1;await z(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Mt(e.url,e.authToken).catch(()=>!1);let n=await xt(e.url,Pt);if(!n&&e.pid&&xs(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await xt(e.url,Pt)}if(n)await D(t).catch(()=>{return});return n}function xs(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Es(e){try{return(await Te(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function Pe(e,t){if(j(e))return"reusable";let n=await z(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await Es(e)){if(n)await z(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let s=await 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 Hs(e){if(Et()!=="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 D(t.discoveryPath).catch(()=>{return})}function Is(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return fs(new URL(`./entry.${e}`,import.meta.url))}function Ms(e,t){if(ms(e))return[Cs];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function Os(e,t){let n=Is(),s=process.execPath?.trim();if(!s)throw Error("unable to resolve runtime executable for hub daemon");let o=us(s).toLowerCase().includes("bun"),i=Ms(n,o);return{launcher:s,args:[...i,"--cwd",e,..._s(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...ys(process.env),CLINE_NO_INTERACTIVE:"1",[hs]:"1"}}}function Us(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 Ds(e,t={}){if(gs())return;let n=Os(e,t),s=Ps();try{os(n.launcher,n.args,{detached:!0,stdio:s?["ignore",s.fd,s.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(s)is(s.fd)}}async function Ls(e,t={}){for(let n=0;;n++)try{Ds(e,t);return}catch(s){let o=vs[n];if(!Us(s)||o===void 0)throw s;await new Promise((i)=>setTimeout(i,o))}}async function Bs(e,t,n={}){let s=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Rt(n),i=Ct(o.host,o.port,o.pathname),r=(l)=>{if(!s)ne(l.url,l.authToken);else It(l.url,l.authToken);return l};await Hs(e).catch(()=>{return});let a=await I(e.discoveryPath),d=a?.url?void 0:Ts(e.discoveryPath),u=!1;if(a?.url){let l=a.authToken;if(!l)u=!0,await Ae(a,e.discoveryPath);else{let m=await F(a.url,l);if(m?.url&&j(m)&&await E(m.url,{authToken:l}))return _e(e.discoveryPath),r({url:m.url,authToken:l});if(m?.url){if(await Pe({...m,authToken:l},e.discoveryPath)==="deferred_busy"&&await E(m.url,{authToken:l}))return r({url:m.url,authToken:l})}else await D(e.discoveryPath).catch(()=>{return})}}let f=await F(i);if(f?.url){let l=Tt(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 yt(e.discoveryPath,P)}catch{}return _e(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.${u?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let m=await Pe(l,e.discoveryPath);if(m==="deferred_busy"){for(let y of[l.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(m==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let h=n.allowPortFallback===!0&&o.port!==0?{...o,port:0}:o;await Ls(t,{...h,manageConnectors:n.manageConnectors});let p=Date.now()+_t;while(Date.now()<p){let l=await I(e.discoveryPath);if(l?.url&&l.authToken){let y=await F(l.url,l.authToken);if(y?.url&&j(y)&&await E(y.url,{authToken:l.authToken}))return _e(e.discoveryPath),r({url:y.url,authToken:l.authToken})}let m=await F(i);if(m?.url&&!j(m)){let y=Tt(m,l??d,i),w=await Pe(y,e.discoveryPath);if(w==="deferred_busy"&&l?.authToken&&await E(m.url,{authToken:l.authToken}))return r({url:m.url,authToken:l.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,bs))}throw Error(`Timed out after ${_t}ms waiting for detached hub startup.`)}async function Ht(e,t={}){let n=As();return await vt(n.discoveryPath,async()=>Bs(n,e,t))}function Fs(){return $s()==="production"?te():W()}function zs(){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 Nt(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 Nt(e.data);return String(e)}function Vs(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 Ot(e){let t=e,n=Vs(t.reason);return new k("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Ee,{closeCode:t.code,closeReason:n||void 0})}function Ut(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 xe="*",se=8000,Gs="cline-hub-auth.",Me=new Map,$t=new Set,Js=3000;var Ee="Hub connection closed",Ks=250,Qs=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 Ys(e){return e instanceof k}class He 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=oe(e.toString());return s?Me.get(s):void 0}function Xs(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 oe(e){if(!Xs(e))return;let t=new URL(Wt(e));return t.search="",t.hash="",t.toString()}function Lt(e){let t=oe(e);return!!t&&$t.has(t)}function ne(e,t){let n=oe(e);if(n){if($t.add(n),t?.trim())Me.set(n,t)}return e}function It(e,t){let n=oe(e);if(n&&t?.trim())Me.set(n,t)}class V{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new k("hub_connection_closed",Ee);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||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=Ut(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 d;try{o=await Promise.race([Promise.resolve().then(()=>s()),new Promise((u,f)=>{d=setTimeout(()=>{f(new k("hub_connect_timeout",`Timed out resolving hub connection headers after ${se}ms`))},se)})])}catch(u){let f=u instanceof k?u:new k("hub_connect_failed",u instanceof Error?u.message:String(u));if(n===this.connectGeneration)this.lastCloseError=f;throw f}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new k("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let i=o?new js(e.toString(),{headers:{...o}}):new(zs())(e.toString(),t?[`${Gs}${t}`]:void 0);this.socket=i;let r=!1,a=new Promise((d,u)=>{let f=!1,c=setTimeout(()=>{if(f)return;f=!0,r=!0;let h=new k("hub_connect_timeout",`Timed out connecting to hub after ${se}ms`);if(this.socket===i)this.lastCloseError=h,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}u(h)},se);i.addEventListener("open",()=>{if(f)return;f=!0,clearTimeout(c),d()}),i.addEventListener("error",(h)=>{if(f)return;f=!0,clearTimeout(c);let p=Ut(h,e);if(this.socket===i)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;u(p)}),i.addEventListener("close",(h)=>{if(f)return;f=!0,clearTimeout(c);let p=r?this.lastCloseError:Ot(h);if(this.socket===i){if(!r)this.lastCloseError=p,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}u(p)})});return i.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(Nt(d)))}),i.addEventListener("close",(d)=>{if(this.socket!==i)return;if(!r)this.lastCloseError=Ot(d),this.sawSocketClose=!0;this.registered=!1;for(let u of this.pendingReplies.values())u.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await a,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,s={listener:e,sessionId:n};return this.listeners.add(s),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(s))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,s){let o=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,s)}catch(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=qs("hubreq_");s?.onDispatch?.(i);let r=Ws(e,s?.timeoutMs),a=new Promise((u,f)=>{let c=r===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;f(new He(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);u(h)},reject:(h)=>{if(c)clearTimeout(c);f(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:r,payload:t}})}catch(u){throw this.pendingReplies.delete(i),u}let d=await a;if(!d.ok){if(d.error?.code===rt){let u=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Y(u,d.error.message)}throw new He(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Lt(this.currentUrl)||!Ys(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Bt({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(Ks*2**this.reconnectAttempt,Qs),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(!Lt(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Bt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new k("hub_connection_closed",Ee);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new k("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),s=(this.subscriptionCounts.get(n)??0)+t;if(s<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,s),t>0&&s===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??xe}subscriptionSessionIdFromKey(e){return e===xe?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[xe,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 Wt(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 V({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 Ie(e,t){let n=Wt(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(!Ns(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 Zs(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 V({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await s.command("session.list",{limit:500},void 0,{timeoutMs:Js});return Zs(o.payload)}finally{await s.dispose().catch(()=>{return})}}async function eo(e,t,n){try{return(await Te(e,t,n)).activeSessionCount===0}catch{return!1}}async function to(e,t){let n=`${e.discoveryPath}.superseded`,s=await I(n);if(!s?.url||!s.authToken)return;let o=await Ie(s.url,{authToken:s.authToken});if(o.status!=="compatible")return;if(await eo(o.url,s.authToken,t))return;return ne(o.url,s.authToken)}async function no(e={}){if(e.endpoint?.trim()){let o=await Ie(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=Fs(),n=await I(t.discoveryPath);if(!n?.url)return await to(t,e);let s=await Ie(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(s.status==="compatible")return ne(s.url,n.authToken);if(s.status==="protocol_mismatch")await D(t.discoveryPath).catch(()=>{return});return}async function Bt(e={}){let t=await no(e);if(t&&await E(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Ht(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function z(e,t,n,s){qt();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 Mt(e,t){qt();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 so(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 Ue(e,t){return Array.isArray(e)?e.flatMap((n)=>{let s=so(n,t);return s?[s]:[]}):[]}async function jt(e,t={}){let n=e.trim(),s=n.length;while(s>0&&n[s-1]==="/")s--;let o=n.slice(0,s),i=async(m)=>{let y=await(t.fetchImpl??fetch)(`${o}${m}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!y.ok)throw Error(`HTTP ${y.status}`);return await y.json()},r,a;try{[r,a]=await Promise.all([i("/api/v1/ai/cline/models"),i("/api/v1/ai/cline/recommended-models")])}catch(m){throw Error("Could not load the cloud model catalog.",{cause:m})}let d=r&&typeof r==="object"?r:void 0,u=Ue(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=Ue(c?.clinePass,"cline-pass"),p=Ue(c?.clineCloud,"cline-cloud"),l=new Set;return[...t.isOrganizationSession?[]:h,...p,...u].filter((m)=>{if(l.has(m.id))return!1;return l.add(m.id),!0})}import{formatDisplayUserInput as Ft}from"@cerebriline/shared";var oo=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function io(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function ro(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function ao(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function co(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 uo(e){let t=Ft(e);return t.startsWith("[TASK RESUMPTION]")||t==="The user approved switching to act mode. Continue with the approved plan now."}function lo(e){if(io(e.role)!=="user")return 0;let t=ro(e),n=typeof t?.kind==="string"?t.kind:void 0,s=ao(t);if(n==="compaction"||n==="compaction_summary")return s??1;if(s!==void 0)return s;if(n&&oo.has(n))return 0;let o=co(e);if(!o.hasAttachment&&!Ft(o.text))return 0;if(!o.hasAttachment&&uo(o.text))return 0;return 1}function zt(e){return lo(e)>0}function ae(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 Le(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return String(t?.model??e?.model??"").trim()}function de(e){let t=e.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return!String(t?.parentSessionId??e.parentSessionId??"").trim()}function Kt(e,t="text"){if(!e||typeof e!=="object"||Array.isArray(e))return"";let n=e.content;if(typeof n==="string")return t==="text"?n.trim():"";if(!Array.isArray(n))return"";return n.map((s)=>s&&typeof s==="object"&&!Array.isArray(s)?t==="thinking"&&s.type==="redacted_thinking"?"[redacted]":String(s[t]??""):"").join("").trim()}function ie(e){let t=e.trim(),n=t.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(n?n[1]:t).trim()}function G(e,t,n){let s=ie(n);return e.filter((o)=>Boolean(o)&&typeof o==="object"&&!Array.isArray(o)&&String(o.role??"").toLowerCase()==="user"&&(s!==""||zt(o))&&ie(Kt(o))===s).length+t.filter((o)=>ie(o.prompt)===s).length}function Be(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 po=new Set(["run.completed","run.aborted","run.failed"]),fo=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)=>Kt(n,t)).filter(Boolean)}function Gt(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 re(e,t,n=new Set){if(!e||typeof e!=="object")return n;if(Array.isArray(e)){for(let i of e)re(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))re(i,t,n);return n}function Jt(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 Qt(e,t,n={}){let s=n.queueSnapshotApplied!==!1,o=Gt(t,n.baselineMessages??[]),i=Gt(t,n.baselineMessages??[],"thinking"),r=re(t,"tool_use"),a=re(t,"tool_result"),d=new Set(e.slice(0,n.messagesSnapshotEventCutoff??e.length)),u=new Set,f=new Map;for(let y of e.slice(0,n.messagesSnapshotEventCutoff??e.length)){let w=Be([y])[0];if(!w)continue;let v=ie(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)u.add(y)}let h=[...s?e.slice(n.queueSnapshotEventCutoff??e.length):e].reverse().find((y)=>y.event==="session.pending_prompts"),p=[],l=[],m=(y)=>{if(l.length===0)return;let w=l.filter((A)=>d.has(A)),v=(A)=>{if(!y)return-1;let S=[...w].reverse().findIndex((nn)=>nn.event===`${A}.finished`),L=S<0?-1:w.length-1-S;return L>=0||l.at(-1)?.event==="run.aborted"?L:w.length-1},P=v("assistant"),H=v("reasoning"),b=Jt(w.slice(0,P+1)),R=b?o.findIndex((A)=>A.endsWith(b)):-1,M=R>=0;if(M)o.splice(R,1);let J=Jt(w.slice(0,H+1),"reasoning"),pe=J?i.findIndex((A)=>A.endsWith(J)):-1;if(pe>=0)i.splice(pe,1);for(let[A,S]of l.entries()){if(u.has(S)){p.push({...S,payload:{...S.payload,transcriptReflected:!0}});continue}if(d.has(S)&&fo.has(S.event)&&(S.event.startsWith("reasoning.")?pe>=0&&A<=H:M&&A<=P))continue;if(S.event==="session.pending_prompts"&&S!==h)continue;if(d.has(S)&&S.event.startsWith("tool.")){let L=String(S.payload?.toolCallId??"").trim();if(a.has(L)||S.event==="tool.started"&&r.has(L))continue}p.push(S)}l=[]};for(let y of e)if(l.push(y),po.has(y.event))m(!0);return m(!1),p}import{formatDisplayUserInput as ho}from"@cerebriline/shared";function ce(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 ue(e){let t=e?.trim();return t?ho(t).slice(0,120):void 0}function qe(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]
@@ -1531,7 +1531,7 @@ ${a}`:a,t.mode??e.config.mode),l=this.resolveAbsoluteFilePaths(e.config.cwd,t.us
1531
1531
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
1532
1532
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
1533
1533
  metadata_json, transcript_path, hook_path, messages_path, updated_at
1534
- ) 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,pt()])}}function CDe(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 PDe(e){return e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act"}function EV(e={}){let t=async(r)=>r,n=new sm({sessionService:new cm(new lm),capabilities:{toolExecutors:{submit:t}},fetch:e.fetch,telemetry:e.telemetry});return{async startSession(r,o){let i=(r.cwd?.trim()||r.workspaceRoot).trim(),s=await n.startSession({source:Gt.CORE,mode:"automation",sessionMetadata:Xn(o?.sessionMetadata,{mode:"automation",trigger:r.source}),interactive:!1,config:{providerId:IDe(r.provider),modelId:r.model,apiKey:r.apiKey?.trim()||void 0,cwd:i,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:PDe(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:s.sessionId,startResult:{sessionId:s.sessionId,manifestPath:s.manifestPath,messagesPath:s.messagesPath}}},async sendSession(r,o){let i=await n.runTurn({sessionId:r,prompt:o.prompt,userImages:o.attachments?.userImages,userFiles:o.attachments?.userFiles?.map((s)=>s.content)});if(!i)throw Error("local hub schedule runtime returned no turn result");return{result:CDe(i)}},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 MDe,CLINE_HUB_PORT as ODe,resolveClineBuildEnv as LDe}from"@cerebriline/shared";var NDe="CLINE_HUB_HOST",DDe="CLINE_HUB_PORT",$De="CLINE_HUB_PATHNAME",FDe="127.0.0.1",UDe=ODe,BDe="/hub";function AV(e){return LDe(e)==="development"?MDe:UDe}function HDe(e={}){return(e.env??process.env)[NDe]?.trim()||FDe}function dP(e={}){let n=(e.env??process.env)[DDe]?.trim();if(!n)return AV(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return AV(e);return r}function WDe(e={}){return(e.env??process.env)[$De]?.trim()||BDe}function lP(e={},t={}){return{host:e.host??HDe(t),port:e.port??dP(t),pathname:e.pathname??WDe(t)}}import{chmodSync as qDe,existsSync as jDe,mkdirSync as zDe}from"node:fs";import{dirname as GDe}from"node:path";import{loadSqliteDb as KDe}from"@cerebriline/shared/db";var RV=3;class IV 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 um(e){return e instanceof Error&&e.name==="HubLockHeldError"}function CV(e){return`${e}.instance.lock`}class Fc{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{zDe(GDe(e),{recursive:!0}),t=jDe(e),n=KDe(e)}catch{return new Fc(e,void 0)}try{n.exec("PRAGMA busy_timeout = 0;"),n.exec("BEGIN EXCLUSIVE;")}catch(r){if(n.close?.(),VDe(r))throw new IV(e);return new Fc(e,void 0)}if(!t)try{qDe(e,384)}catch{}return new Fc(e,n)}}function VDe(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 u$e}from"node:path";import{createHash as XDe,randomBytes as LV}from"node:crypto";import{mkdir as uP,open as PV,readFile as NV,rename as YDe,rm as hP,writeFile as JDe}from"node:fs/promises";import{dirname as DV,join as pP}from"node:path";import{ensureLoopbackProxyBypass as QDe,isHubProtocolCompatible as Nft}from"@cerebriline/shared";import{resolveClineDataDir as Cv,resolveClineDir as $ft}from"@cerebriline/shared/storage";var ZDe="CLINE_HUB_DISCOVERY_PATH",e$e="CLINE_HUB_BUILD_ID",t$e="CLINE_HUB_BUILD_EPOCH_MS",n$e=30000,r$e=15000,MV=100;function o$e(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function i$e(e){return XDe("sha256").update(e).digest("hex").slice(0,12)}function s$e(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 $V(){return LV(32).toString("hex")}function OV(e){return new Promise((t)=>setTimeout(t,e))}function a$e(e){return`${e}.lock`}async function d$e(e){try{let t=JSON.parse(await NV(pP(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 cP(e){await hP(e,{recursive:!0,force:!0}).catch(()=>{return})}function hm(){let e=process.env[e$e]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(Zl.version)}`}function FV(){let e=Number(process.env[t$e]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792707017870)?1792707017870:void 0}function Pv(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${i$e(e)}`,n=process.env[ZDe]?.trim()||pP(Cv(),"locks","hub","owners",`${o$e(t)}.json`);return{ownerId:t,discoveryPath:n}}async function Mv(e){try{let t=JSON.parse(await NV(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function mP(e,t,n){await BV(e,async()=>{let r=DV(e);await uP(r,{recursive:!0});let o=`${e}.${process.pid}.${LV(6).toString("hex")}.tmp`,i;try{i=await PV(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
1534
+ ) 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,pt()])}}function CDe(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 PDe(e){return e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act"}function EV(e={}){let t=async(r)=>r,n=new sm({sessionService:new cm(new lm),capabilities:{toolExecutors:{submit:t}},fetch:e.fetch,telemetry:e.telemetry});return{async startSession(r,o){let i=(r.cwd?.trim()||r.workspaceRoot).trim(),s=await n.startSession({source:Gt.CORE,mode:"automation",sessionMetadata:Xn(o?.sessionMetadata,{mode:"automation",trigger:r.source}),interactive:!1,config:{providerId:IDe(r.provider),modelId:r.model,apiKey:r.apiKey?.trim()||void 0,cwd:i,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:PDe(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:s.sessionId,startResult:{sessionId:s.sessionId,manifestPath:s.manifestPath,messagesPath:s.messagesPath}}},async sendSession(r,o){let i=await n.runTurn({sessionId:r,prompt:o.prompt,userImages:o.attachments?.userImages,userFiles:o.attachments?.userFiles?.map((s)=>s.content)});if(!i)throw Error("local hub schedule runtime returned no turn result");return{result:CDe(i)}},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 MDe,CLINE_HUB_PORT as ODe,resolveClineBuildEnv as LDe}from"@cerebriline/shared";var NDe="CLINE_HUB_HOST",DDe="CLINE_HUB_PORT",$De="CLINE_HUB_PATHNAME",FDe="127.0.0.1",UDe=ODe,BDe="/hub";function AV(e){return LDe(e)==="development"?MDe:UDe}function HDe(e={}){return(e.env??process.env)[NDe]?.trim()||FDe}function dP(e={}){let n=(e.env??process.env)[DDe]?.trim();if(!n)return AV(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return AV(e);return r}function WDe(e={}){return(e.env??process.env)[$De]?.trim()||BDe}function lP(e={},t={}){return{host:e.host??HDe(t),port:e.port??dP(t),pathname:e.pathname??WDe(t)}}import{chmodSync as qDe,existsSync as jDe,mkdirSync as zDe}from"node:fs";import{dirname as GDe}from"node:path";import{loadSqliteDb as KDe}from"@cerebriline/shared/db";var RV=3;class IV 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 um(e){return e instanceof Error&&e.name==="HubLockHeldError"}function CV(e){return`${e}.instance.lock`}class Fc{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{zDe(GDe(e),{recursive:!0}),t=jDe(e),n=KDe(e)}catch{return new Fc(e,void 0)}try{n.exec("PRAGMA busy_timeout = 0;"),n.exec("BEGIN EXCLUSIVE;")}catch(r){if(n.close?.(),VDe(r))throw new IV(e);return new Fc(e,void 0)}if(!t)try{qDe(e,384)}catch{}return new Fc(e,n)}}function VDe(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 u$e}from"node:path";import{createHash as XDe,randomBytes as LV}from"node:crypto";import{mkdir as uP,open as PV,readFile as NV,rename as YDe,rm as hP,writeFile as JDe}from"node:fs/promises";import{dirname as DV,join as pP}from"node:path";import{ensureLoopbackProxyBypass as QDe,isHubProtocolCompatible as Nft}from"@cerebriline/shared";import{resolveClineDataDir as Cv,resolveClineDir as $ft}from"@cerebriline/shared/storage";var ZDe="CLINE_HUB_DISCOVERY_PATH",e$e="CLINE_HUB_BUILD_ID",t$e="CLINE_HUB_BUILD_EPOCH_MS",n$e=30000,r$e=15000,MV=100;function o$e(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function i$e(e){return XDe("sha256").update(e).digest("hex").slice(0,12)}function s$e(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 $V(){return LV(32).toString("hex")}function OV(e){return new Promise((t)=>setTimeout(t,e))}function a$e(e){return`${e}.lock`}async function d$e(e){try{let t=JSON.parse(await NV(pP(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 cP(e){await hP(e,{recursive:!0,force:!0}).catch(()=>{return})}function hm(){let e=process.env[e$e]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(Zl.version)}`}function FV(){let e=Number(process.env[t$e]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792737149862)?1792737149862:void 0}function Pv(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${i$e(e)}`,n=process.env[ZDe]?.trim()||pP(Cv(),"locks","hub","owners",`${o$e(t)}.json`);return{ownerId:t,discoveryPath:n}}async function Mv(e){try{let t=JSON.parse(await NV(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function mP(e,t,n){await BV(e,async()=>{let r=DV(e);await uP(r,{recursive:!0});let o=`${e}.${process.pid}.${LV(6).toString("hex")}.tmp`,i;try{i=await PV(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
1535
1535
  `,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,n?.beforePublish?.(),await YDe(o,e);let s;try{s=await PV(r,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await hP(o,{force:!0}).catch(()=>{return}),s}})}async function UV(e,t){return await BV(e,async()=>{if((await Mv(e))?.hubId!==t)return!1;return await hP(e,{force:!0}),!0})}async function l$e(e,t,n){let r=a$e(e);await uP(DV(r),{recursive:!0});let o=Date.now()+r$e;while(!0){try{await uP(r,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await d$e(r);if(!a){if(Date.now()>=o){await cP(r);continue}await OV(MV);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!s$e(a.pid)||d>n$e){await cP(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await OV(MV);continue}try{return await JDe(pP(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
1536
1536
  `,"utf8"),await n()}finally{await cP(r)}}}function BV(e,t){return l$e(`${e}.mutation`,"discovery mutation",t)}async function pm(e,t){QDe();try{let n=await fetch(t?.authToken?c$e(e):HV(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 Uc(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function HV(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function c$e(e){let t=new URL(HV(e));return t.pathname="/status",t.toString()}var h$e="shared:cline",p$e="CLINE_HUB_DISCOVERY_PATH",m$e="hub-production";function Ov(e=h$e){return Pv(`${e}@${hm()}`)}function Lv(){return{ownerId:m$e,discoveryPath:process.env[p$e]?.trim()||u$e(Cv(),"locks","hub","production.json")}}function f$e(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(`
1537
1537
  `).trim()||void 0}var WV=120,fP="...";function gP(e){let t=e.trim();if(!t)return"";if(Buffer.byteLength(t,"utf8")<=WV)return t;let n=WV-Buffer.byteLength(fP,"utf8");if(n<=0)return fP;let r="";for(let o of t){if(Buffer.byteLength(r+o,"utf8")>n)break;r+=o}return`${r}${fP}`}async function qV(e){let t=e?.sessionId?.trim()||"unknown",n=typeof e?.metadata?.messagesPath==="string"?e.metadata.messagesPath:void 0,o=[...await Dc(n)].reverse().find((d)=>d.role==="assistant"),i=o?f$e(o.content):void 0,s=e?.workspaceRoot?.trim()||"workspace",a=typeof e?.metadata?.prompt==="string"?e.metadata.prompt.trim():s;return{title:`Task completed (${t})`,body:gP(i&&i.length>0?i:a.length>0?a:s),severity:"info"}}import{resolve as BBe}from"node:path";import{CLINE_DEFAULT_MODEL_ID as HBe,captureSdkError as ek,createSessionId as x0,HUB_CLIENT_TOOL_APPROVAL_CAPABILITY as WBe}from"@cerebriline/shared";import{isChatWorkspacePath as qBe}from"@cerebriline/shared/storage";function mm(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function yP(e){let t=e?.trim();return t?t:void 0}function g$e(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 jV(e,t){return new Date(new Date(e).getTime()+Math.max(0,Math.floor(t))*1000).toISOString()}function zV(e,t){return new Date(new Date(e).getTime()-Math.max(0,Math.floor(t))*1000).toISOString()}function y$e(e,t){if(!e)return t;return new Date(e).getTime()>=new Date(t).getTime()?e:t}function w$e(e,t){let n=e.eventId.trim(),r=e.eventType.trim(),o=e.source.trim(),i=yP(e.subject),s=yP(e.dedupeKey)??`${r}:${o}:${i??n}`;return{eventId:n,eventType:r,source:o,subject:i,occurredAt:g$e(e.occurredAt,t),workspaceRoot:yP(e.workspaceRoot),payload:mm(e.payload)?e.payload:void 0,attributes:mm(e.attributes)?e.attributes:void 0,dedupeKey:s}}function wP(e,t){if(!t)return;let n=t.split("."),r=e;for(let o of n){if(!mm(r))return;r=r[o]}return r}function b$e(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=wP(n,t);if(r!==void 0)return r;if(e.attributes){let o=wP(e.attributes,t);if(o!==void 0)return o}if(e.payload)return wP(e.payload,t);return}function Nv(e,t){if(Array.isArray(t))return t.some((n)=>Nv(e,n));if(Array.isArray(e))return e.some((n)=>Nv(n,t));if(mm(t)){if(!mm(e))return!1;return Object.entries(t).every(([n,r])=>Nv(e[n],r))}return Object.is(e,t)}function v$e(e,t){if(!t||Object.keys(t).length===0)return!0;return Object.entries(t).every(([n,r])=>Nv(b$e(e,n),r))}class bP{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=w$e(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=[],i=[],s=[];for(let l of r){if(!v$e(e,l.filters)){o.push({specId:l.specId,externalId:l.externalId,reason:"filter_mismatch",dedupeKey:e.dedupeKey});continue}i.push(l);let c=this.materializeForSpec(l,e,n.record.receivedAt);if(c.run)s.push(c.run);else o.push({specId:l.specId,externalId:l.externalId,reason:c.reason,dedupeKey:e.dedupeKey})}let a=i.length===0?"unmatched":s.length>0?"queued":"suppressed";return this.store.updateEventLogProcessing(n.record.eventId,{status:a,matchedSpecCount:i.length,queuedRunCount:s.length,suppressedCount:o.filter((l)=>l.reason!=="filter_mismatch").length}),{event:this.store.getEventLog(n.record.eventId)??n.record,duplicate:!1,matchedSpecs:i,queuedRuns:s,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 l=y$e(d.scheduledFor,jV(n,o)),c=this.store.updateQueuedEventRunForDebounce({runId:d.runId,triggerEventId:t.eventId,scheduledFor:l});if(c)return{run:c,reason:"dedupe_window"}}}let i=e.dedupeWindowSeconds??0;if(i>0&&this.store.hasRecentEventRunForDedupe({specId:e.specId,dedupeKey:r,sinceIso:zV(n,i)}))return{reason:"dedupe_window"};let s=e.cooldownSeconds??0;if(s>0&&this.store.hasRecentEventRunForSpec({specId:e.specId,sinceIso:zV(n,s)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:e.specId,specRevision:e.revision,triggerKind:"event",triggerEventId:t.eventId,scheduledFor:o>0?jV(n,o):n}),reason:"dedupe_window"}}}class fm{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 P$e}from"node:path";import{buildClineSystemPrompt as M$e}from"@cerebriline/shared";import{nowIso as YV}from"@cerebriline/shared/db";import{mkdirSync as k$e,writeFileSync as T$e}from"node:fs";import{isAbsolute as S$e,join as KV}from"node:path";import{resolveCronReportsDir as x$e,resolveCronSpecsDir as _$e}from"@cerebriline/shared/storage";function us(e){if(/[:#\n]/.test(e)||e.includes('"'))return JSON.stringify(e);return e}function vr(e,t){if(t===void 0||t===null)return;return`${e}: ${us(t)}`}function VV(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}
package/dist/hub/index.js CHANGED
@@ -318,7 +318,7 @@ ${JSON.stringify(r,null,2)}`}startClaimLeaseHeartbeat(e){let t=Math.max(1000,Mat
318
318
  scheduled_for = COALESCE(?, scheduled_for),
319
319
  updated_at = ?
320
320
  WHERE run_id = ? AND claim_token = ?`).run(e.releaseAttempt?1:0,e.error??null,e.scheduledFor??null,t,e.runId,e.claimToken).changes??0)>0}attachSessionIdToRun(e,t,n){return(this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ? AND claim_token = ? AND status = 'running'").run(t,Wt(),e,n).changes??0)===1}attachReportPathToRun(e,t){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(t,Wt(),e)}}function gf(e){return e?new Date(e).getTime():void 0}function l7(e){let t=e.metadata?{...e.metadata}:void 0;if(t)delete t.__hubScheduleCreatedBy,delete t.__hubScheduleCwd,delete t.__hubRuntimeOptions;return t}function xu(e){let t=e.metadata;return{scheduleId:e.externalId,name:e.title,cronPattern:e.triggerKind==="one_off"?_u:e.scheduleExpr??"",timezone:e.triggerKind==="schedule"?e.timezone:void 0,prompt:e.prompt??"",workspaceRoot:e.workspaceRoot??"",cwd:typeof t?.__hubScheduleCwd==="string"?t.__hubScheduleCwd:void 0,modelSelection:e.providerId||e.modelId?{providerId:e.providerId??"",modelId:e.modelId??""}:void 0,enabled:e.enabled&&!e.removed&&e.parseStatus==="valid",mode:e.mode==="plan"?"plan":e.mode==="act"?"act":"yolo",systemPrompt:e.systemPrompt,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,maxParallel:e.maxParallel??1,createdAt:new Date(e.createdAt).getTime(),updatedAt:new Date(e.updatedAt).getTime(),nextRunAt:gf(e.nextRunAt),lastRunAt:gf(e.lastRunAt),createdBy:typeof t?.__hubScheduleCreatedBy==="string"?t.__hubScheduleCreatedBy:void 0,tags:e.tags,runtimeOptions:t?.__hubRuntimeOptions&&typeof t.__hubRuntimeOptions==="object"&&!Array.isArray(t.__hubRuntimeOptions)?t.__hubRuntimeOptions:void 0,metadata:l7(e)}}function c7(e){switch(e){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function Vk(e,t){return{executionId:e.runId,scheduleId:t,sessionId:e.sessionId,triggeredAt:new Date(e.scheduledFor??e.createdAt).getTime(),startedAt:gf(e.startedAt),endedAt:gf(e.completedAt),status:c7(e.status),errorMessage:e.error}}class yf{store;materializer;runner;started=!1;disposed=!1;constructor(e){this.store=new Su({dbPath:e.dbPath}),this.materializer=new gu({store:this.store}),this.runner=new wu({store:this.store,materializer:this.materializer,runtimeHandlers:e.runtimeHandlers,eventPublisher:e.eventPublisher,workspaceRoot:"",specs:e.specs,logger:e.logger,telemetry:e.telemetry,pollIntervalMs:e.pollIntervalMs,claimLeaseSeconds:e.claimLeaseSeconds,globalMaxConcurrency:e.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule(e){let t=e.cronPattern===_u?e.timezone:e.timezone?.trim()||Intl.DateTimeFormat().resolvedOptions().timeZone;if(this.validateScheduleTiming(e.cronPattern,t,e.metadata,!0),!e.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return xu(this.store.createHubSchedule({...e,timezone:t}))}getSchedule(e){let t=this.store.getHubSchedule(e);return t?xu(t):void 0}listSchedules(e={}){return this.store.listHubSchedules(e).map((t)=>xu(t))}updateSchedule(e,t){let n=this.store.getHubSchedule(e);if(!n)return;let r=t.workspaceRoot!==void 0?t.workspaceRoot.trim():n.workspaceRoot,o=t.enabled??n.enabled,i=xu(n),s=t.cronPattern??i.cronPattern;if(s.trim()===_u&&typeof t.timezone==="string"&&t.timezone.trim())throw Error("timezone is only supported for recurring schedules");if(this.validateScheduleTiming(s,s.trim()===_u?void 0:t.timezone===null?void 0:t.timezone??i.timezone,t.metadata??i.metadata,o),o&&!r)throw Error("workspaceRoot is required for enabled schedules");let a=this.store.updateHubSchedule(e,{...t,scheduleId:e});return a?xu(a):void 0}validateScheduleTiming(e,t,n,r){if(e.trim()!==_u){TO(e),zk(t);return}if(t?.trim())throw Error("timezone is only supported for recurring schedules");let o=n?.[d7];if(typeof o!=="number"||!Number.isFinite(o)||r&&o<=Date.now())throw Error("runAt must be a future timestamp")}deleteSchedule(e){return this.store.deleteHubSchedule(e)}pauseSchedule(e){return this.updateSchedule(e,{scheduleId:e,enabled:!1})}resumeSchedule(e){return this.updateSchedule(e,{scheduleId:e,enabled:!0})}async triggerScheduleNow(e){let t=this.store.enqueueHubScheduleRun(e,"manual");if(!t)return;await this.runner.tick();let n=this.store.getRun(t.runId)??t;return Vk(n,e)}triggerScheduleNowDetached(e){let t=this.store.enqueueHubScheduleRun(e,"manual");if(!t)return;return this.runner.tick().catch(()=>{return}),Vk(t,e)}listScheduleExecutions(e){let t=e.scheduleId?this.store.getHubSchedule(e.scheduleId):void 0,n={specId:t?.specId,limit:e.limit};return this.store.listRuns(n).map((o)=>{let i=t??this.store.getSpec(o.specId);if(!i||i.source!=="hub-schedule")return;return Vk(o,i.externalId)}).filter((o)=>{if(!o)return!1;return!e.status||o.status===e.status})}getScheduleStats(e){let t=this.listScheduleExecutions({scheduleId:e,limit:1e4});if(t.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let n=0,r=0,o=0,i;for(let s of t){if(s.status==="success"||s.status==="completed")n+=1;if(!i&&s.status!=="success"&&s.status!=="completed")i=s;if(s.startedAt&&s.endedAt)o+=s.endedAt-s.startedAt,r+=1}return{totalRuns:t.length,successRate:n/t.length,avgDurationSeconds:r>0?o/r/1000:0,lastFailure:i}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((e)=>{let t=this.store.getSpec(e.specId);if(!t||t.source!=="hub-schedule"||!e.sessionId)return[];return[{executionId:e.runId,scheduleId:t.externalId,sessionId:e.sessionId,startedAt:e.startedAt??new Date().toISOString(),timeoutAt:t.timeoutSeconds&&e.startedAt?new Date(new Date(e.startedAt).getTime()+t.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(e=20){let t={triggerKind:"schedule",enabled:!0,limit:e};return this.store.listSpecs(t).flatMap((n)=>n.source==="hub-schedule"&&n.nextRunAt?[{spec:n,nextRunAt:n.nextRunAt}]:[]).sort((n,r)=>String(n.nextRunAt).localeCompare(String(r.nextRunAt))).slice(0,e).map(({spec:n,nextRunAt:r})=>({scheduleId:n.externalId,name:n.title,nextRunAt:r}))}}import{realpathSync as Yk,statSync as u7}from"node:fs";import{isAbsolute as OO,relative as h7,sep as LO}from"node:path";import{ONE_TIME_SCHEDULE_CRON_PATTERN as NO,ONE_TIME_SCHEDULE_RUN_AT_METADATA_KEY as DO}from"@cerebriline/shared";import{z as St}from"zod";var p7=St.enum(["create","update","list","get","pause","resume","delete","run_now"]),m7=St.object({provider_id:St.string().min(1),model_id:St.string().min(1).optional()}),Pd=St.object({operation:p7,schedule_id:St.string().min(1).optional(),schedule_type:St.enum(["once","recurring"]).optional(),name:St.string().min(1).optional(),prompt:St.string().min(1).optional(),run_at:St.string().datetime({offset:!0}).optional(),cron_pattern:St.string().min(1).optional(),timezone:St.string().min(1).nullable().optional().describe("IANA timezone for recurring schedules. Omit unless the user explicitly requests a timezone; new schedules default to the local timezone. Updates preserve the existing timezone when omitted."),enabled:St.boolean().optional(),mode:St.enum(["act","plan","yolo"]).optional(),system_prompt:St.string().nullable().optional(),max_iterations:St.number().int().positive().nullable().optional(),timeout_seconds:St.number().int().positive().nullable().optional(),max_parallel:St.number().int().positive().max(32).optional(),tags:St.array(St.string().min(1)).optional(),model_selection:m7.optional(),limit:St.number().int().positive().max(200).optional()});function Rd(e,t,n,r){if(!$O.has(t.operation))return;Ii(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.scheduled.${t.operation}`,success:r,agentId:n.agentId})}var $O=new Set(["create","update","pause","resume","delete","run_now"]);function Cd(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Jk(e,t){try{let n=Yk.native(e);if(!u7(n).isDirectory())throw Error("not a directory");return n}catch{throw Error(`${t} does not resolve to an existing safe path`)}}function f7(e,t){try{return Yk.native(e)===Yk.native(t)}catch{return!1}}function FO(e,t,n){let r=h7(e,t);if(r===".."||r.startsWith(`..${LO}`)||OO(r))throw Error(`${n} is outside the workspace scope`)}function UO(e,t,n){return Jk(OO(t)?t:`${e}${LO}${t}`,n)}function g7(e){let t=Jk(e.workspaceRoot,"workspaceRoot"),n=e.cwd?UO(t,e.cwd,"cwd"):t;return FO(t,n,"cwd"),{...e,workspaceRoot:t,cwd:n}}function Id(e,t){if(!e)throw Error("schedule does not exist");if(!f7(e.workspaceRoot,t.workspaceRoot))throw Error("schedule is outside this session's workspace scope");let n=Jk(e.workspaceRoot,"schedule workspaceRoot");if(e.cwd){let r=UO(n,e.cwd,"schedule cwd");FO(n,r,"schedule cwd")}}function MO(e){if(!e)return;return{providerId:e.provider_id.trim(),modelId:e.model_id?.trim()||void 0}}function Xk(e){if(!e)return;return[...new Set(e.map((t)=>t.trim()).filter(Boolean))]}function BO(e){let t=Date.parse(Cd(e,"run_at"));if(!Number.isFinite(t))throw Error("run_at must be an ISO timestamp");if(t<=Date.now())throw Error("run_at must be in the future");return t}function y7(e){if(e.schedule_type==="once"){if(e.cron_pattern)throw Error("cron_pattern cannot be used with a one-time schedule");if(e.timezone)throw Error("timezone is encoded in run_at for a one-time schedule");return{cronPattern:NO,metadata:{[DO]:BO(e.run_at)}}}if(e.schedule_type==="recurring"){if(e.run_at)throw Error("run_at cannot be used with a recurring schedule");return{cronPattern:Cd(e.cron_pattern,"cron_pattern"),timezone:e.timezone?.trim()||void 0}}throw Error("schedule_type is required for create")}function w7(e){if(e.run_at&&e.cron_pattern)throw Error("run_at and cron_pattern cannot be updated together");if(e.schedule_type==="once"||e.run_at){if(e.cron_pattern)throw Error("cron_pattern cannot be used with a one-time schedule");if(e.timezone)throw Error("timezone is encoded in run_at for a one-time schedule");return{cronPattern:NO,timezone:null,metadata:{[DO]:BO(e.run_at)}}}if(e.schedule_type==="recurring"||e.cron_pattern)return{cronPattern:Cd(e.cron_pattern,"cron_pattern"),timezone:e.timezone===null?null:e.timezone?.trim()||void 0};return{timezone:e.timezone===null?null:e.timezone?.trim()||void 0}}function Eu(e){return Cd(e.schedule_id,"schedule_id")}async function Qk(e,t,n){let r=Pd.safeParse(t);if(!r.success)return{ok:!1,error:{code:"invalid_schedule_input",message:r.error.issues[0]?.message??"Invalid schedule input"}};let o=r.data;try{if(!n.sessionId)throw Error("tasks requires a Hub session");let i=await e.resolveSessionDefaults(n.sessionId);if(!i?.workspaceRoot.trim())throw Error("tasks could not resolve the current workspace");let s=g7(i);if($O.has(o.operation)&&!s.interactive)throw Error("schedule mutations require an interactive user session");switch(o.operation){case"create":{let a=e.schedules.createSchedule({name:Cd(o.name,"name"),...y7(o),prompt:Cd(o.prompt,"prompt"),workspaceRoot:s.workspaceRoot,cwd:s.cwd,modelSelection:MO(o.model_selection)??s.modelSelection,enabled:o.enabled,mode:o.mode??"yolo",systemPrompt:o.system_prompt??void 0,maxIterations:o.max_iterations??void 0,timeoutSeconds:o.timeout_seconds??void 0,maxParallel:o.max_parallel??1,createdBy:`agent:${n.agentId}`,tags:Xk(o.tags)});return e.publish?.("schedule.created",{schedule:a},n.sessionId),Rd(e,o,n,!0),{ok:!0,operation:o.operation,schedule:a}}case"update":{let a=Eu(o);Id(e.schedules.getSchedule(a),s);let d=e.schedules.updateSchedule(a,{scheduleId:a,...w7(o),name:o.name?.trim()||void 0,prompt:o.prompt?.trim()||void 0,modelSelection:MO(o.model_selection),enabled:o.enabled,mode:o.mode,systemPrompt:o.system_prompt,maxIterations:o.max_iterations,timeoutSeconds:o.timeout_seconds,maxParallel:o.max_parallel,tags:Xk(o.tags)});if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.updated",{schedule:d},n.sessionId),Rd(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"list":{let a=e.schedules.listSchedules({enabled:o.enabled,tags:Xk(o.tags),workspaceRoot:s.workspaceRoot,limit:o.limit??50}).filter((d)=>{try{return Id(d,s),!0}catch{return!1}}).slice(0,o.limit??50);return{ok:!0,operation:o.operation,schedules:a}}case"get":{let a=e.schedules.getSchedule(Eu(o));return Id(a,s),{ok:!0,operation:o.operation,schedule:a}}case"pause":case"resume":{let a=Eu(o);Id(e.schedules.getSchedule(a),s);let d=o.operation==="pause"?e.schedules.pauseSchedule(a):e.schedules.resumeSchedule(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.updated",{schedule:d},n.sessionId),Rd(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"delete":{let a=Eu(o);Id(e.schedules.getSchedule(a),s);let d=e.schedules.deleteSchedule(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.deleted",{deleted:d,scheduleId:a},n.sessionId),Rd(e,o,n,!0),{ok:!0,operation:o.operation,deleted:d}}case"run_now":{let a=Eu(o);Id(e.schedules.getSchedule(a),s);let d=e.schedules.triggerScheduleNowDetached(a);if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.triggered",{execution:d},n.sessionId),Rd(e,o,n,!0),{ok:!0,operation:o.operation,execution:d}}}}catch(i){return Rd(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"schedule_operation_failed",message:i instanceof Error?i.message:String(i)}}}}import{LangfuseAttributesSpanProcessor as z7}from"@cerebriline/llms";import{markOtlpTraceRelayProvider as K7}from"@cerebriline/shared";import{metrics as G7,trace as V7}from"@opentelemetry/api";import{logs as X7}from"@opentelemetry/api-logs";import{OTLPLogExporter as Y7}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as J7}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as Q7}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as Z7}from"@opentelemetry/resources";import{BatchLogRecordProcessor as eQ,ConsoleLogRecordExporter as tQ,LoggerProvider as nQ}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as rQ,MeterProvider as oQ,PeriodicExportingMetricReader as oL}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as iQ,ConsoleSpanExporter as sQ,SimpleSpanProcessor as aQ}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as dQ}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as lQ,ATTR_SERVICE_VERSION as cQ}from"@opentelemetry/semantic-conventions";import{mkdirSync as b7,readFileSync as v7,statSync as k7,writeFileSync as T7}from"node:fs";import{dirname as S7}from"node:path";import{CONFIGURABLE_MODEL_TOOL_NAMES as HO}from"@cerebriline/shared";import{resolveGlobalSettingsPath as WO}from"@cerebriline/shared/storage";import{z as Dt}from"zod";var Zk=Dt.preprocess((e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string").map((t)=>t.trim()).filter(Boolean):void 0,Dt.array(Dt.string()).optional()).transform((e)=>{if(!e)return;let t=[...new Set(e)].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}),x7=Dt.enum(["basic","agentic"]).catch("agentic"),_7=Dt.partialRecord(Dt.enum(HO),Dt.object({enabled:Dt.boolean()}).strip()).optional(),E7=Dt.record(Dt.string(),Dt.object({enabled:Dt.boolean()}).strip()).optional().catch(void 0),A7=Dt.enum(["plan","act"]),eT=Dt.object({telemetryOptOut:Dt.boolean().default(!1).catch(!1),autoUpdateEnabled:Dt.boolean().default(!0).catch(!0),compactionStrategy:x7.optional(),compactionEnabled:Dt.boolean().optional().catch(void 0),planActMode:A7.optional().catch(void 0),toolAutoApprove:Dt.boolean().optional().catch(void 0),tuiTheme:Dt.string().optional().catch(void 0),disabledTools:Zk.optional(),tools:_7,disabledPlugins:Zk.optional(),disabledAgentPlugins:Zk.optional(),bundledSkills:E7}).strip().transform((e)=>{let t={autoUpdateEnabled:e.autoUpdateEnabled,telemetryOptOut:e.telemetryOptOut};if(e.compactionStrategy)t.compactionStrategy=e.compactionStrategy;if(e.compactionEnabled!==void 0)t.compactionEnabled=e.compactionEnabled;if(e.planActMode)t.planActMode=e.planActMode;if(e.toolAutoApprove!==void 0)t.toolAutoApprove=e.toolAutoApprove;if(e.tuiTheme?.trim())t.tuiTheme=e.tuiTheme.trim();if(e.disabledTools?.length)t.disabledTools=e.disabledTools;if(e.tools&&Object.keys(e.tools).length>0)t.tools=e.tools;if(e.disabledPlugins?.length)t.disabledPlugins=e.disabledPlugins;if(e.disabledAgentPlugins?.length)t.disabledAgentPlugins=e.disabledAgentPlugins;if(e.bundledSkills&&Object.keys(e.bundledSkills).length>0)t.bundledSkills=e.bundledSkills;return t});function wf(){return eT.parse({})}var bf;function R7(){bf=void 0}function I7(e){if(e.disabledTools)Object.freeze(e.disabledTools);if(e.tools){for(let t of Object.values(e.tools))Object.freeze(t);Object.freeze(e.tools)}if(e.disabledPlugins)Object.freeze(e.disabledPlugins);if(e.disabledAgentPlugins)Object.freeze(e.disabledAgentPlugins);return Object.freeze(e)}function C7(e){let t;try{t=v7(e,"utf8")}catch{return{value:wf(),loadFailed:!0}}try{let n=eT.safeParse(JSON.parse(t));return n.success?{value:n.data,loadFailed:!1}:{value:wf(),loadFailed:!0}}catch{return{value:wf(),loadFailed:!0}}}function jO(){let e=WO(),t=k7(e,{throwIfNoEntry:!1}),n=t?.mtimeMs??0,r=t?.size??0,o=bf;if(o&&o.path===e&&o.mtimeMs===n&&o.size===r)return o;let i=t?C7(e):{value:wf(),loadFailed:!1},s=I7(i.value);return bf={path:e,mtimeMs:n,size:r,value:s,loadFailed:i.loadFailed},bf}function hn(){return jO().value}function Ds(e,t={}){let n=WO(),r=hn();b7(S7(n),{recursive:!0});let o=eT.parse(e);if(!r.telemetryOptOut&&o.telemetryOptOut)$M(t.telemetry);T7(n,`${JSON.stringify(o,null,2)}
321
- `,"utf8"),R7()}function qO(){return hn().telemetryOptOut}function $s(e){return new Set(e??hn().disabledTools??[])}function zO(e){return new Set(e??hn().disabledPlugins??[])}function Au(e){return new Set(e??hn().disabledAgentPlugins??[])}function KO(e){return HO.includes(e)}function P7(){let e=jO();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function tT(e){return P7()[e]?.enabled===!0}function M7(e,t){let n=hn();Ds({...n,tools:{...n.tools,[e]:{enabled:t}}})}function GO(e){if(KO(e)){let o=tT(e);return M7(e,!o),o}let t=hn(),n=new Set(t.disabledTools??[]),r=n.has(e);if(r)n.delete(e);else n.add(e);return Ds({...t,disabledTools:[...n]}),!r}function O7(e,t){let n=[...new Set(e.map((s)=>s.trim()).filter(Boolean))];if(n.length===0)return;let r=hn(),o=$s(r.disabledTools),i={...r.tools};for(let s of n){if(KO(s)){i[s]={enabled:!t};continue}if(t)o.add(s);else o.delete(s)}Ds({...r,disabledTools:[...o],tools:i})}function VO(e,t){return O7([e],t),t}function XO(e,t){let n=e.trim();if(!n)return;let r=hn(),o=zO(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Ds({...r,disabledPlugins:[...o]})}function YO(e,t){let n=e.trim();if(!n)return;let r=hn(),o=Au(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Ds({...r,disabledAgentPlugins:[...o]})}function JO(e,t){let n=zO(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r))}function Mi(e,t){let n=$s(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r.name))}function QO(e,t){if(!e||e.length===0)return e;let n=$s(t);if(n.size===0)return e;return e.map((r)=>{if(!r.setup)return r;return{...r,setup:(o,i)=>r.setup?.({...o,registerTool:(s)=>{if(!n.has(s.name))o.registerTool(s)}},i)}})}import{existsSync as L7,mkdirSync as N7,readFileSync as D7,writeFileSync as $7}from"node:fs";import{resolve as F7}from"node:path";import{resolveSessionDataDir as U7}from"@cerebriline/shared/storage";import{nanoid as B7}from"nanoid";import*as H7 from"node-machine-id";var W7="machine-id",ZO,eL=!1;function tL(){if(!eL)ZO=nL(),eL=!0;return ZO??rL()}function Ru(e){let t=e?.trim();if(t)return t;let n=nL();if(n)return n;return rL()}function j7(){let e=H7;return e.machineIdSync??e.default?.machineIdSync}function nL(){try{let e=j7();if(!e)return;return e().trim()||void 0}catch{return}}function rL(){let e=U7(),t=F7(e,W7);try{if(L7(t)){let r=D7(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${B7()}`;try{N7(e,{recursive:!0}),$7(t,n,"utf8")}catch{}return n}class nT{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(e){this.name=e.name??"OpenTelemetryAdapter",this.metadata={...e.metadata},this.meterProvider=e.meterProvider,this.loggerProvider=e.loggerProvider,this.meter=e.meterProvider?.getMeter("cline")??null,this.logger=e.loggerProvider?.getLogger("cline")??null,this.enabled=e.enabled??!0,this.distinctId=e.distinctId,this.commonProperties=e.commonProperties?{...e.commonProperties}:{}}emit(e,t){if(!this.isEnabled())return;this.emitLog(e,t,!1)}emitRequired(e,t){this.emitLog(e,t,!0)}recordCounter(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let i=this.counters.get(e);if(!i)i=this.meter.createCounter(e,r?{description:r}:void 0),this.counters.set(e,i);i.add(t,this.flattenProperties(this.buildAttributes(n)))}recordHistogram(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let i=this.histograms.get(e);if(!i)i=this.meter.createHistogram(e,r?{description:r}:void 0),this.histograms.set(e,i);i.record(t,this.flattenProperties(this.buildAttributes(n)))}recordGauge(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let i=this.buildAttributes(n),s=JSON.stringify(i),a=this.gaugeValues.get(e);if(t===null){if(a){if(a.delete(s),a.size===0)this.gaugeValues.delete(e),this.gauges.delete(e)}return}let d=a;if(!d)d=new Map,this.gaugeValues.set(e,d);if(!this.gauges.has(e)){let l=this.meter.createObservableGauge(e,r?{description:r}:void 0);l.addCallback((c)=>{for(let u of this.snapshotGaugeSeries(e))c.observe(u.value,this.flattenProperties(u.attributes))}),this.gauges.set(e,l)}d.set(s,{value:t,attributes:i})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(e){this.distinctId=e}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(e,t,n){if(!this.logger)return;let r=this.flattenProperties(this.buildAttributes(t,n));this.logger.emit({severityText:"INFO",body:e,attributes:r})}buildAttributes(e,t=!1){return{...this.commonProperties,...this.metadata,...e,...this.distinctId?{distinct_id:this.distinctId}:{},...t?{_required:!0}:{}}}snapshotGaugeSeries(e){let t=this.gaugeValues.get(e);if(!t)return[];return Array.from(t.values(),(n)=>({value:n.value,attributes:n.attributes?{...n.attributes}:void 0}))}flattenProperties(e,t="",n=new WeakSet,r=0){if(!e)return{};let o={},i=100,s=10;for(let[a,d]of Object.entries(e)){if(a==="__proto__"||a==="constructor"||a==="prototype")continue;let l=t?`${t}.${a}`:a;if(d===null||d===void 0){o[l]=String(d);continue}if(Array.isArray(d)){let c=d.length>i?d.slice(0,i):d;try{o[l]=JSON.stringify(c)}catch{o[l]="[UnserializableArray]"}if(d.length>i)o[`${l}_truncated`]=!0,o[`${l}_original_length`]=d.length;continue}if(typeof d==="object"){if(d instanceof Date){o[l]=d.toISOString();continue}if(d instanceof Error){o[l]=d.message;continue}if(n.has(d)){o[l]="[Circular]";continue}if(r>=s){o[l]="[MaxDepthExceeded]";continue}n.add(d),Object.assign(o,this.flattenProperties(d,l,n,r+1));continue}if(q7(d)){o[l]=d;continue}try{o[l]=JSON.stringify(d)}catch{o[l]=String(d)}}return o}}function q7(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class rT{name;logger;enabled;constructor(e={}){this.name=e.name??"TelemetryLoggerSink",this.logger=e.logger,this.enabled=e.enabled??!0}emit(e,t){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:e,properties:t})}emitRequired(e,t){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:e,properties:t})}recordCounter(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:e,value:t,attributes:n,description:r,required:o===!0})}recordHistogram(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:e,value:t,attributes:n,description:r,required:o===!0})}recordGauge(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:e,value:t,attributes:n,description:r,required:o===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class vf{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new rT({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??tL(),this.commonProperties={...e.commonProperties??{}}}addAdapter(e){this.adapters.push(e)}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return this.adapters.some((e)=>e.isEnabled())}capture(e){let t=this.buildAttributes(e.properties);for(let n of this.adapters)n.emit(e.event,t)}captureRequired(e,t){let n=this.buildAttributes(t);for(let r of this.adapters)r.emitRequired(e,n)}recordCounter(e,t,n,r,o=!1){let i=this.buildAttributes(n);for(let s of this.adapters)s.recordCounter(e,t,i,r,o)}recordHistogram(e,t,n,r,o=!1){let i=this.buildAttributes(n);for(let s of this.adapters)s.recordHistogram(e,t,i,r,o)}recordGauge(e,t,n,r,o=!1){let i=this.buildAttributes(n);for(let s of this.adapters)s.recordGauge(e,t,i,r,o)}async flush(){await Promise.all(this.adapters.map((e)=>e.flush()))}async dispose(){await Promise.all(this.adapters.map((e)=>e.dispose()))}buildAttributes(e){let t=typeof e?.distinct_id==="string"&&e.distinct_id.trim()?e.distinct_id.trim():this.distinctId,n={...this.commonProperties,...this.metadata,...e,...t?{distinct_id:t}:{},device_id:this.deviceId};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}}class iL{distinctId;metadata;commonProperties;constructor(e={}){this.distinctId=e.distinctId,this.metadata={...e.metadata??{}},this.commonProperties={...e.commonProperties??{}}}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return!1}capture(e){this.resolveProperties(e.properties)}captureRequired(e,t){this.resolveProperties(t)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(e){let t=typeof e?.distinct_id==="string"&&e.distinct_id.trim()?e.distinct_id.trim():this.distinctId,n={...this.commonProperties,...this.metadata,...e,...t?{distinct_id:t}:{}};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}}class sL{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=Z7({[lQ]:e.serviceName??"cline",...e.serviceVersion?{[cQ]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)G7.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)X7.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return V7.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new nT({...e,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(e){let t=this.createAdapter({name:e.name,enabled:this.options.enabled,metadata:e.metadata});return new vf({...e,adapters:[t],distinctId:Ru(e.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(e){let t=oT(this.options.metricsExporter);if(t.length===0)return null;let n=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),r=Math.min(30000,Math.floor(n*0.8)),o=t.map((i)=>fQ(i,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:n,timeout:r})).filter((i)=>i!==null);if(o.length===0)return null;return new oQ({resource:e,readers:o})}createTracerProvider(e){let t=oT(this.options.tracesExporter);if(t.length===0)return null;let n=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,r=this.options.otlpTracesHeaders??this.options.otlpHeaders,o=[],i=!1;for(let a of t){let d=mQ(a,{endpoint:n,headers:r,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(d){if(o.push(d),a!=="console")i=!0}}if(o.length===0)return null;let s=new dQ({resource:e,spanProcessors:i?[new z7,...o]:o});if(i)K7(s);return s}createLoggerProvider(e){let t=oT(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=pQ(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new eQ(o,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((r)=>r!==null);if(n.length===0)return null;return new nQ({resource:e,processors:n})}}function uQ(e){let t=new sL(e),n=t.createTelemetryService(e),r=()=>{n.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:e.enabled??!0,logsExporter:Array.isArray(e.logsExporter)?e.logsExporter.join(","):e.logsExporter,metricsExporter:Array.isArray(e.metricsExporter)?e.metricsExporter.join(","):e.metricsExporter,tracesExporter:Array.isArray(e.tracesExporter)?e.tracesExporter.join(","):e.tracesExporter,otlpProtocol:e.otlpProtocol,hasOtlpEndpoint:Boolean(e.otlpEndpoint),serviceName:e.serviceName,serviceVersion:e.serviceVersion})};if(!e.deferProviderCreatedEvent)r();return{provider:t,telemetry:n,emitProviderCreated:r}}function aL(e){if(qO())return{telemetry:new iL(e)};if(e.enabled!==!0)return{telemetry:new vf({...e,distinctId:Ru(e.distinctId)})};return uQ(e)}function hQ(e){let{telemetry:t,provider:n,emitProviderCreated:r}=aL(e);return{telemetry:t,provider:n,flush:async()=>{let s=n;if(s&&typeof s.forceFlush==="function")try{await s.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([t.dispose(),n?.dispose()])},...e.deferProviderCreatedEvent&&r?{emitProviderCreated:r}:{}}}function oT(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function pQ(e,t){if(e==="console")return new tQ;if(!t.endpoint)return null;let n=iT(t.endpoint,"/v1/logs");return new Y7({url:n,headers:t.headers})}function mQ(e,t){if(e==="console")return new aQ(new sQ);if(!t.endpoint)return null;let n=iT(t.endpoint,"/v1/traces");return new iQ(new Q7({url:n,headers:t.headers}))}function fQ(e,t){if(e==="console")return new oL({exporter:new rQ,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=iT(t.endpoint,"/v1/metrics");return new oL({exporter:new J7({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function iT(e,t){let n=new URL(e),r=n.pathname.endsWith("/")?n.pathname.slice(0,-1):n.pathname;return n.pathname=r.endsWith(t)?r:`${r}${t}`,n.toString()}import{createTool as vQ,zodToJsonSchema as kQ}from"@cerebriline/shared";import{z as Zr}from"zod";import{resolve as dL}from"node:path";import{z as Ce}from"zod";var lL=Ce.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),gQ=Ce.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),cL=Ce.union([Ce.literal(0),Ce.literal(1),Ce.literal(2),Ce.literal(3),Ce.literal(4),Ce.literal(5)]),yQ=Ce.object({provider_id:Ce.string().min(1),model_id:Ce.string().min(1).optional()}),kf=Ce.object({operation:Ce.enum(["create","update","list","get"]),task_id:Ce.string().min(1).optional(),expected_revision:Ce.number().int().positive().optional(),type:lL.optional(),title:Ce.string().min(1).optional(),description:Ce.string().nullable().optional(),instructions:Ce.string().min(1).optional(),scope:Ce.enum(["workspace","global"]).optional(),workspace_root:Ce.string().min(1).nullable().optional(),cwd:Ce.string().min(1).nullable().optional(),resource_paths:Ce.array(Ce.string().min(1)).optional(),priority:cL.optional(),assignee:Ce.string().min(1).nullable().optional(),model_selection:yQ.nullable().optional(),mode:Ce.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Ce.string().nullable().optional(),max_iterations:Ce.number().int().positive().nullable().optional(),timeout_seconds:Ce.number().int().positive().nullable().optional(),available_at:Ce.string().datetime().optional(),expires_at:Ce.string().datetime().optional(),automation_eligible:Ce.boolean().optional(),statuses:Ce.array(gQ).optional(),types:Ce.array(lL).optional(),priorities:Ce.array(cL).optional(),limit:Ce.number().int().positive().max(500).optional()}),wQ=new Set(["create","update"]);function sT(e,t,n,r){if(!wQ.has(t.operation))return;Ii(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.todo.${t.operation}`,success:r,agentId:n.agentId})}function Md(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function uL(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function pL(e,t){return dL(e)===dL(t)}function hL(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!pL(e.workspaceRoot,t.workspaceRoot))throw Error("task is outside this session's workspace scope");return}if(e.scope!=="global")throw Error("task is outside this session's global scope")}function bQ(e,t){let n=t.workspaceRoot?"workspace":"global";if(e.scope&&e.scope!==n)throw Error(`this session can only manage ${n} tasks`);if(e.workspace_root!==void 0){if(!t.workspaceRoot||e.workspace_root===null||!pL(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function mL(e,t,n){let r=kf.safeParse(t);if(!r.success)return{ok:!1,error:{code:"invalid_task_input",message:r.error.issues[0]?.message??"Invalid task input"}};let o=r.data,i={kind:"agent",id:n.agentId,agentId:n.agentId,sessionId:n.sessionId};try{if(!n.sessionId)throw Error("tasks requires a Hub session");let s=await e.resolveSessionDefaults(n.sessionId);if(!s)throw Error("tasks could not resolve the current session");let a=bQ(o,s);switch(o.operation){case"create":{let d={type:Md(o.type,"type"),title:Md(o.title,"title"),description:o.description??void 0,instructions:Md(o.instructions,"instructions"),scope:a,workspaceRoot:s.workspaceRoot,cwd:a==="workspace"?(o.cwd??s.cwd)?.trim()||void 0:void 0,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee??void 0,modelSelection:uL(o.model_selection)??s.modelSelection,mode:o.mode??void 0,systemPrompt:o.system_prompt??void 0,maxIterations:o.max_iterations??void 0,timeoutSeconds:o.timeout_seconds??void 0,availableAt:o.available_at,expiresAt:Md(o.expires_at,"expires_at"),automationEligible:o.automation_eligible,createdBy:i,originSessionId:n.sessionId,originTaskId:s.originTaskId},l={ok:!0,operation:o.operation,task:await e.manager.createTask(d)};return sT(e,o,n,!0),l}case"update":{let d=Md(o.task_id,"task_id");if(hL(await e.manager.getTask(d),s),!o.expected_revision)throw Error("expected_revision is required for update");let l={ok:!0,operation:o.operation,task:await e.manager.updateTask({taskId:d,expectedRevision:o.expected_revision,type:o.type,title:o.title,description:o.description,instructions:o.instructions,scope:a,workspaceRoot:s.workspaceRoot??null,cwd:o.cwd,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee,modelSelection:uL(o.model_selection),mode:o.mode,systemPrompt:o.system_prompt,maxIterations:o.max_iterations,timeoutSeconds:o.timeout_seconds,availableAt:o.available_at,expiresAt:o.expires_at,automationEligible:o.automation_eligible,updatedBy:i})};return sT(e,o,n,!0),l}case"list":{let d={statuses:o.statuses,types:o.types,scope:a,workspaceRoot:s.workspaceRoot,priorities:o.priorities,automationEligible:o.automation_eligible,limit:o.limit};return{ok:!0,operation:o.operation,tasks:await e.manager.listTasks(d)}}case"get":{let d=await e.manager.getTask(Md(o.task_id,"task_id"));return hL(d,s),{ok:!0,operation:o.operation,task:d}}}}catch(s){return sT(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:s instanceof Error?s.message:String(s)}}}}var Iu="tasks",fL='# Tasks\n\nUse the `tasks` tool to manage durable Todo items and explicitly requested scheduled agent work.\n\n- Use `kind: "todo"` for meaningful follow-ups, handoffs, ideas, reminders, and other work that should remain visible after this session. This includes useful work you identify and suggest proactively. Agent-created Todos require user approval; Todos created directly by the user are approved immediately. Todo `available_at` controls availability in the list; it never schedules execution.\n- Use `kind: "scheduled"` only when the user explicitly asks Cline to execute work once at a future time or on a recurrence. One-time schedules require an exact future ISO 8601 `run_at` with an offset or Z. Recurring schedules require a five-field `cron_pattern` and default to the local timezone. Omit `timezone` unless the user explicitly requests a different timezone; never guess EST, UTC, or another zone. When a timezone is requested, use its IANA name (for example, America/New_York) so daylight-saving changes are handled.\n- "Remind me" is ambiguous: ask whether the user wants a reviewed Todo note or an agent to execute work at that time when intent is unclear.\n- Never create both kinds for the same request unless the user explicitly requests both. Check existing items before creating a likely duplicate.\n- Todo instructions and scheduled prompts must be self-contained. Include the goal, constraints, relevant project context, and expected output.\n- Scheduled sessions run in the user\'s schedules home workspace, not this conversation\'s folder. Include absolute paths in the scheduled `prompt` for any project files or repositories the work must touch.\n- Never approve or start a Todo yourself. Only mutate schedules from an interactive user session, and only update, pause, resume, delete, or run one immediately when the user asks.',TQ="# Tasks\n\nUse the `tasks` tool only when the user explicitly asks Cline to execute work once at a future time or on a recurrence. Always pass `kind: \"scheduled\"`.\n\n- One-time schedules require an exact future ISO 8601 `run_at` with an offset or Z. Recurring schedules require a five-field `cron_pattern` and default to the local timezone. Omit `timezone` unless the user explicitly requests a different timezone; never guess EST, UTC, or another zone. When a timezone is requested, use its IANA name (for example, America/New_York) so daylight-saving changes are handled.\n- Never create a schedule proactively. Check existing schedules before creating a likely duplicate.\n- Make the scheduled `prompt` self-contained because it runs in a new unattended session in the user's schedules home workspace, not this conversation's folder. Include the goal, constraints, expected output, and absolute paths for any project files or repositories the work must touch.\n- Only update, pause, resume, delete, or run a schedule immediately when the user asks for that action.",SQ=kf.extend({kind:Zr.literal("todo")}).strict(),gL=Pd.extend({kind:Zr.literal("scheduled")}).strict(),yL=Zr.discriminatedUnion("kind",[SQ,gL]),xQ=Zr.discriminatedUnion("kind",[gL]),wL=["create","update","list","get","pause","resume","delete","run_now"],_Q=Zr.object({...Pd.shape,...kf.shape,kind:Zr.enum(["todo","scheduled"]),operation:Zr.enum(wL)}).strict(),EQ=Zr.object({...Pd.shape,kind:Zr.enum(["scheduled"]),operation:Zr.enum(wL)}).strict();function aT(e){let t=e.todo;return vQ({name:Iu,description:t?'Create and manage reviewed Todo items or explicitly requested scheduled agent work. Use kind "todo" for durable Agenda items that require user or automation approval. Use kind "scheduled" for one-time or recurring autonomous execution. Todo available_at is not an execution timer; schedules use run_at or cron_pattern.':'Create and manage explicitly requested scheduled agent work with kind "scheduled". One-time schedules use a future ISO 8601 run_at; recurring schedules use a five-field cron_pattern.',inputSchema:kQ(t?_Q:EQ),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?yL:xQ).safeParse(n);if(!o.success)return{ok:!1,kind:typeof n==="object"&&n!==null&&"kind"in n&&(n.kind==="todo"||n.kind==="scheduled")?n.kind:void 0,error:{code:"invalid_tasks_input",message:o.error.issues[0]?.message??"Invalid tasks input"}};if(o.data.kind==="todo"){if(!t)return{ok:!1,kind:"todo",error:{code:"invalid_tasks_input",message:'kind "todo" is not available in this session'}};return{kind:"todo",...await mL(t,o.data,r)}}return{kind:"scheduled",...await Qk(e.scheduled,o.data,r)}}})}function dT(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?TQ:fL,whenToolAvailable:Iu})}}}import{createSessionId as UZ,ensureLoopbackProxyBypass as zL,isHubProtocolCompatible as BZ,resolveClineBuildEnv as HZ,resolveHubCommandTimeoutMs as WZ}from"@cerebriline/shared";import jZ from"ws";var Tf="0.0.92";var Oi={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:Tf,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var Sf="session_not_found";class Od 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 xf(e){return e instanceof Od||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as sZ}from"node:child_process";import{closeSync as aZ,mkdirSync as dZ,openSync as lZ,readFileSync as cZ,unlinkSync as uZ}from"node:fs";import{basename as hZ,dirname as pZ,join as mZ}from"node:path";import{fileURLToPath as fZ}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as gZ,isBunEmbeddedModulePath as yZ,isHubDaemonProcess as $L,resolveClineBuildEnv as FL,withResolvedClineBuildEnv as wZ}from"@cerebriline/shared";import{createHash as AQ,randomBytes as _L}from"node:crypto";import{existsSync as RQ}from"node:fs";import{mkdir as cT,open as vL,readFile as EL,rename as IQ,rm as _f,writeFile as CQ}from"node:fs/promises";import{dirname as AL,join as uT}from"node:path";import{ensureLoopbackProxyBypass as PQ,isHubProtocolCompatible as MQ}from"@cerebriline/shared";import{resolveClineDataDir as Cu,resolveClineDir as Mqe}from"@cerebriline/shared/storage";var OQ="CLINE_HUB_DISCOVERY_PATH",LQ="CLINE_HUB_BUILD_ID",NQ="CLINE_HUB_BUILD_EPOCH_MS",DQ=30000,$Q=15000,kL=100;function FQ(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function UQ(e){return AQ("sha256").update(e).digest("hex").slice(0,12)}function BQ(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 RL(){return _L(32).toString("hex")}function TL(e){return new Promise((t)=>setTimeout(t,e))}function HQ(e){return`${e}.lock`}async function WQ(e){try{let t=JSON.parse(await EL(uT(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 lT(e){await _f(e,{recursive:!0,force:!0}).catch(()=>{return})}function eo(){let e=process.env[LQ]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(Oi.version)}`}function hT(){let e=Number(process.env[NQ]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792707017870)?1792707017870:void 0}function Fs(e,t=eo()){let n=MQ(e);if(!n.compatible)return n;let r=e.buildId?.trim();if(!r)return{compatible:!1,reason:"missing_build"};if(r!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function SL(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function xL(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((r)=>Number(r));if(n.length===0||n.some((r)=>!Number.isInteger(r)||r<0))return;return n}function jQ(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let r=e[n]??0,o=t[n]??0;if(r!==o)return r<o?-1:1}return 0}function Pu(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=SL(e.buildEpochMs),i=SL(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let s=xL(e.coreVersion),a=xL(t.coreVersion);if(s&&a){let d=jQ(s,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function Mu(){return{buildId:eo(),buildEpochMs:hT(),coreVersion:String(Oi.version)}}function Ld(e,t){let n=t?.self??Mu(),r=Fs(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return Pu(n,e)<=0}function Us(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${UQ(e)}`,n=process.env[OQ]?.trim()||uT(Cu(),"locks","hub","owners",`${FQ(t)}.json`);return{ownerId:t,discoveryPath:n}}function Lqe(e=`hub-${Date.now().toString(36)}`){return Us(e)}async function jt(e){try{let t=JSON.parse(await EL(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function Ef(e,t,n){await pT(e,async()=>{let r=AL(e);await cT(r,{recursive:!0});let o=`${e}.${process.pid}.${_L(6).toString("hex")}.tmp`,i;try{i=await vL(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
321
+ `,"utf8"),R7()}function qO(){return hn().telemetryOptOut}function $s(e){return new Set(e??hn().disabledTools??[])}function zO(e){return new Set(e??hn().disabledPlugins??[])}function Au(e){return new Set(e??hn().disabledAgentPlugins??[])}function KO(e){return HO.includes(e)}function P7(){let e=jO();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function tT(e){return P7()[e]?.enabled===!0}function M7(e,t){let n=hn();Ds({...n,tools:{...n.tools,[e]:{enabled:t}}})}function GO(e){if(KO(e)){let o=tT(e);return M7(e,!o),o}let t=hn(),n=new Set(t.disabledTools??[]),r=n.has(e);if(r)n.delete(e);else n.add(e);return Ds({...t,disabledTools:[...n]}),!r}function O7(e,t){let n=[...new Set(e.map((s)=>s.trim()).filter(Boolean))];if(n.length===0)return;let r=hn(),o=$s(r.disabledTools),i={...r.tools};for(let s of n){if(KO(s)){i[s]={enabled:!t};continue}if(t)o.add(s);else o.delete(s)}Ds({...r,disabledTools:[...o],tools:i})}function VO(e,t){return O7([e],t),t}function XO(e,t){let n=e.trim();if(!n)return;let r=hn(),o=zO(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Ds({...r,disabledPlugins:[...o]})}function YO(e,t){let n=e.trim();if(!n)return;let r=hn(),o=Au(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Ds({...r,disabledAgentPlugins:[...o]})}function JO(e,t){let n=zO(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r))}function Mi(e,t){let n=$s(t);if(n.size===0)return[...e];return e.filter((r)=>!n.has(r.name))}function QO(e,t){if(!e||e.length===0)return e;let n=$s(t);if(n.size===0)return e;return e.map((r)=>{if(!r.setup)return r;return{...r,setup:(o,i)=>r.setup?.({...o,registerTool:(s)=>{if(!n.has(s.name))o.registerTool(s)}},i)}})}import{existsSync as L7,mkdirSync as N7,readFileSync as D7,writeFileSync as $7}from"node:fs";import{resolve as F7}from"node:path";import{resolveSessionDataDir as U7}from"@cerebriline/shared/storage";import{nanoid as B7}from"nanoid";import*as H7 from"node-machine-id";var W7="machine-id",ZO,eL=!1;function tL(){if(!eL)ZO=nL(),eL=!0;return ZO??rL()}function Ru(e){let t=e?.trim();if(t)return t;let n=nL();if(n)return n;return rL()}function j7(){let e=H7;return e.machineIdSync??e.default?.machineIdSync}function nL(){try{let e=j7();if(!e)return;return e().trim()||void 0}catch{return}}function rL(){let e=U7(),t=F7(e,W7);try{if(L7(t)){let r=D7(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${B7()}`;try{N7(e,{recursive:!0}),$7(t,n,"utf8")}catch{}return n}class nT{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(e){this.name=e.name??"OpenTelemetryAdapter",this.metadata={...e.metadata},this.meterProvider=e.meterProvider,this.loggerProvider=e.loggerProvider,this.meter=e.meterProvider?.getMeter("cline")??null,this.logger=e.loggerProvider?.getLogger("cline")??null,this.enabled=e.enabled??!0,this.distinctId=e.distinctId,this.commonProperties=e.commonProperties?{...e.commonProperties}:{}}emit(e,t){if(!this.isEnabled())return;this.emitLog(e,t,!1)}emitRequired(e,t){this.emitLog(e,t,!0)}recordCounter(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let i=this.counters.get(e);if(!i)i=this.meter.createCounter(e,r?{description:r}:void 0),this.counters.set(e,i);i.add(t,this.flattenProperties(this.buildAttributes(n)))}recordHistogram(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let i=this.histograms.get(e);if(!i)i=this.meter.createHistogram(e,r?{description:r}:void 0),this.histograms.set(e,i);i.record(t,this.flattenProperties(this.buildAttributes(n)))}recordGauge(e,t,n,r,o=!1){if(!this.meter||!o&&!this.isEnabled())return;let i=this.buildAttributes(n),s=JSON.stringify(i),a=this.gaugeValues.get(e);if(t===null){if(a){if(a.delete(s),a.size===0)this.gaugeValues.delete(e),this.gauges.delete(e)}return}let d=a;if(!d)d=new Map,this.gaugeValues.set(e,d);if(!this.gauges.has(e)){let l=this.meter.createObservableGauge(e,r?{description:r}:void 0);l.addCallback((c)=>{for(let u of this.snapshotGaugeSeries(e))c.observe(u.value,this.flattenProperties(u.attributes))}),this.gauges.set(e,l)}d.set(s,{value:t,attributes:i})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(e){this.distinctId=e}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(e,t,n){if(!this.logger)return;let r=this.flattenProperties(this.buildAttributes(t,n));this.logger.emit({severityText:"INFO",body:e,attributes:r})}buildAttributes(e,t=!1){return{...this.commonProperties,...this.metadata,...e,...this.distinctId?{distinct_id:this.distinctId}:{},...t?{_required:!0}:{}}}snapshotGaugeSeries(e){let t=this.gaugeValues.get(e);if(!t)return[];return Array.from(t.values(),(n)=>({value:n.value,attributes:n.attributes?{...n.attributes}:void 0}))}flattenProperties(e,t="",n=new WeakSet,r=0){if(!e)return{};let o={},i=100,s=10;for(let[a,d]of Object.entries(e)){if(a==="__proto__"||a==="constructor"||a==="prototype")continue;let l=t?`${t}.${a}`:a;if(d===null||d===void 0){o[l]=String(d);continue}if(Array.isArray(d)){let c=d.length>i?d.slice(0,i):d;try{o[l]=JSON.stringify(c)}catch{o[l]="[UnserializableArray]"}if(d.length>i)o[`${l}_truncated`]=!0,o[`${l}_original_length`]=d.length;continue}if(typeof d==="object"){if(d instanceof Date){o[l]=d.toISOString();continue}if(d instanceof Error){o[l]=d.message;continue}if(n.has(d)){o[l]="[Circular]";continue}if(r>=s){o[l]="[MaxDepthExceeded]";continue}n.add(d),Object.assign(o,this.flattenProperties(d,l,n,r+1));continue}if(q7(d)){o[l]=d;continue}try{o[l]=JSON.stringify(d)}catch{o[l]=String(d)}}return o}}function q7(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class rT{name;logger;enabled;constructor(e={}){this.name=e.name??"TelemetryLoggerSink",this.logger=e.logger,this.enabled=e.enabled??!0}emit(e,t){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:e,properties:t})}emitRequired(e,t){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:e,properties:t})}recordCounter(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:e,value:t,attributes:n,description:r,required:o===!0})}recordHistogram(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:e,value:t,attributes:n,description:r,required:o===!0})}recordGauge(e,t,n,r,o){if(!o&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:e,value:t,attributes:n,description:r,required:o===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class vf{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new rT({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??tL(),this.commonProperties={...e.commonProperties??{}}}addAdapter(e){this.adapters.push(e)}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return this.adapters.some((e)=>e.isEnabled())}capture(e){let t=this.buildAttributes(e.properties);for(let n of this.adapters)n.emit(e.event,t)}captureRequired(e,t){let n=this.buildAttributes(t);for(let r of this.adapters)r.emitRequired(e,n)}recordCounter(e,t,n,r,o=!1){let i=this.buildAttributes(n);for(let s of this.adapters)s.recordCounter(e,t,i,r,o)}recordHistogram(e,t,n,r,o=!1){let i=this.buildAttributes(n);for(let s of this.adapters)s.recordHistogram(e,t,i,r,o)}recordGauge(e,t,n,r,o=!1){let i=this.buildAttributes(n);for(let s of this.adapters)s.recordGauge(e,t,i,r,o)}async flush(){await Promise.all(this.adapters.map((e)=>e.flush()))}async dispose(){await Promise.all(this.adapters.map((e)=>e.dispose()))}buildAttributes(e){let t=typeof e?.distinct_id==="string"&&e.distinct_id.trim()?e.distinct_id.trim():this.distinctId,n={...this.commonProperties,...this.metadata,...e,...t?{distinct_id:t}:{},device_id:this.deviceId};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}}class iL{distinctId;metadata;commonProperties;constructor(e={}){this.distinctId=e.distinctId,this.metadata={...e.metadata??{}},this.commonProperties={...e.commonProperties??{}}}setDistinctId(e){this.distinctId=e}setMetadata(e){this.metadata={...e}}updateMetadata(e){this.metadata={...this.metadata,...e}}setCommonProperties(e){this.commonProperties={...e}}updateCommonProperties(e){this.commonProperties={...this.commonProperties,...e}}isEnabled(){return!1}capture(e){this.resolveProperties(e.properties)}captureRequired(e,t){this.resolveProperties(t)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(e){let t=typeof e?.distinct_id==="string"&&e.distinct_id.trim()?e.distinct_id.trim():this.distinctId,n={...this.commonProperties,...this.metadata,...e,...t?{distinct_id:t}:{}};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}}class sL{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=Z7({[lQ]:e.serviceName??"cline",...e.serviceVersion?{[cQ]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)G7.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)X7.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return V7.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new nT({...e,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(e){let t=this.createAdapter({name:e.name,enabled:this.options.enabled,metadata:e.metadata});return new vf({...e,adapters:[t],distinctId:Ru(e.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(e){let t=oT(this.options.metricsExporter);if(t.length===0)return null;let n=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),r=Math.min(30000,Math.floor(n*0.8)),o=t.map((i)=>fQ(i,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:n,timeout:r})).filter((i)=>i!==null);if(o.length===0)return null;return new oQ({resource:e,readers:o})}createTracerProvider(e){let t=oT(this.options.tracesExporter);if(t.length===0)return null;let n=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,r=this.options.otlpTracesHeaders??this.options.otlpHeaders,o=[],i=!1;for(let a of t){let d=mQ(a,{endpoint:n,headers:r,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(d){if(o.push(d),a!=="console")i=!0}}if(o.length===0)return null;let s=new dQ({resource:e,spanProcessors:i?[new z7,...o]:o});if(i)K7(s);return s}createLoggerProvider(e){let t=oT(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=pQ(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new eQ(o,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((r)=>r!==null);if(n.length===0)return null;return new nQ({resource:e,processors:n})}}function uQ(e){let t=new sL(e),n=t.createTelemetryService(e),r=()=>{n.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:e.enabled??!0,logsExporter:Array.isArray(e.logsExporter)?e.logsExporter.join(","):e.logsExporter,metricsExporter:Array.isArray(e.metricsExporter)?e.metricsExporter.join(","):e.metricsExporter,tracesExporter:Array.isArray(e.tracesExporter)?e.tracesExporter.join(","):e.tracesExporter,otlpProtocol:e.otlpProtocol,hasOtlpEndpoint:Boolean(e.otlpEndpoint),serviceName:e.serviceName,serviceVersion:e.serviceVersion})};if(!e.deferProviderCreatedEvent)r();return{provider:t,telemetry:n,emitProviderCreated:r}}function aL(e){if(qO())return{telemetry:new iL(e)};if(e.enabled!==!0)return{telemetry:new vf({...e,distinctId:Ru(e.distinctId)})};return uQ(e)}function hQ(e){let{telemetry:t,provider:n,emitProviderCreated:r}=aL(e);return{telemetry:t,provider:n,flush:async()=>{let s=n;if(s&&typeof s.forceFlush==="function")try{await s.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([t.dispose(),n?.dispose()])},...e.deferProviderCreatedEvent&&r?{emitProviderCreated:r}:{}}}function oT(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function pQ(e,t){if(e==="console")return new tQ;if(!t.endpoint)return null;let n=iT(t.endpoint,"/v1/logs");return new Y7({url:n,headers:t.headers})}function mQ(e,t){if(e==="console")return new aQ(new sQ);if(!t.endpoint)return null;let n=iT(t.endpoint,"/v1/traces");return new iQ(new Q7({url:n,headers:t.headers}))}function fQ(e,t){if(e==="console")return new oL({exporter:new rQ,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=iT(t.endpoint,"/v1/metrics");return new oL({exporter:new J7({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function iT(e,t){let n=new URL(e),r=n.pathname.endsWith("/")?n.pathname.slice(0,-1):n.pathname;return n.pathname=r.endsWith(t)?r:`${r}${t}`,n.toString()}import{createTool as vQ,zodToJsonSchema as kQ}from"@cerebriline/shared";import{z as Zr}from"zod";import{resolve as dL}from"node:path";import{z as Ce}from"zod";var lL=Ce.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),gQ=Ce.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),cL=Ce.union([Ce.literal(0),Ce.literal(1),Ce.literal(2),Ce.literal(3),Ce.literal(4),Ce.literal(5)]),yQ=Ce.object({provider_id:Ce.string().min(1),model_id:Ce.string().min(1).optional()}),kf=Ce.object({operation:Ce.enum(["create","update","list","get"]),task_id:Ce.string().min(1).optional(),expected_revision:Ce.number().int().positive().optional(),type:lL.optional(),title:Ce.string().min(1).optional(),description:Ce.string().nullable().optional(),instructions:Ce.string().min(1).optional(),scope:Ce.enum(["workspace","global"]).optional(),workspace_root:Ce.string().min(1).nullable().optional(),cwd:Ce.string().min(1).nullable().optional(),resource_paths:Ce.array(Ce.string().min(1)).optional(),priority:cL.optional(),assignee:Ce.string().min(1).nullable().optional(),model_selection:yQ.nullable().optional(),mode:Ce.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Ce.string().nullable().optional(),max_iterations:Ce.number().int().positive().nullable().optional(),timeout_seconds:Ce.number().int().positive().nullable().optional(),available_at:Ce.string().datetime().optional(),expires_at:Ce.string().datetime().optional(),automation_eligible:Ce.boolean().optional(),statuses:Ce.array(gQ).optional(),types:Ce.array(lL).optional(),priorities:Ce.array(cL).optional(),limit:Ce.number().int().positive().max(500).optional()}),wQ=new Set(["create","update"]);function sT(e,t,n,r){if(!wQ.has(t.operation))return;Ii(e.telemetry,{ulid:n.sessionId??n.conversationId??n.agentId,tool:`tasks.todo.${t.operation}`,success:r,agentId:n.agentId})}function Md(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function uL(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function pL(e,t){return dL(e)===dL(t)}function hL(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!pL(e.workspaceRoot,t.workspaceRoot))throw Error("task is outside this session's workspace scope");return}if(e.scope!=="global")throw Error("task is outside this session's global scope")}function bQ(e,t){let n=t.workspaceRoot?"workspace":"global";if(e.scope&&e.scope!==n)throw Error(`this session can only manage ${n} tasks`);if(e.workspace_root!==void 0){if(!t.workspaceRoot||e.workspace_root===null||!pL(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function mL(e,t,n){let r=kf.safeParse(t);if(!r.success)return{ok:!1,error:{code:"invalid_task_input",message:r.error.issues[0]?.message??"Invalid task input"}};let o=r.data,i={kind:"agent",id:n.agentId,agentId:n.agentId,sessionId:n.sessionId};try{if(!n.sessionId)throw Error("tasks requires a Hub session");let s=await e.resolveSessionDefaults(n.sessionId);if(!s)throw Error("tasks could not resolve the current session");let a=bQ(o,s);switch(o.operation){case"create":{let d={type:Md(o.type,"type"),title:Md(o.title,"title"),description:o.description??void 0,instructions:Md(o.instructions,"instructions"),scope:a,workspaceRoot:s.workspaceRoot,cwd:a==="workspace"?(o.cwd??s.cwd)?.trim()||void 0:void 0,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee??void 0,modelSelection:uL(o.model_selection)??s.modelSelection,mode:o.mode??void 0,systemPrompt:o.system_prompt??void 0,maxIterations:o.max_iterations??void 0,timeoutSeconds:o.timeout_seconds??void 0,availableAt:o.available_at,expiresAt:Md(o.expires_at,"expires_at"),automationEligible:o.automation_eligible,createdBy:i,originSessionId:n.sessionId,originTaskId:s.originTaskId},l={ok:!0,operation:o.operation,task:await e.manager.createTask(d)};return sT(e,o,n,!0),l}case"update":{let d=Md(o.task_id,"task_id");if(hL(await e.manager.getTask(d),s),!o.expected_revision)throw Error("expected_revision is required for update");let l={ok:!0,operation:o.operation,task:await e.manager.updateTask({taskId:d,expectedRevision:o.expected_revision,type:o.type,title:o.title,description:o.description,instructions:o.instructions,scope:a,workspaceRoot:s.workspaceRoot??null,cwd:o.cwd,resourcePaths:o.resource_paths,priority:o.priority,assignee:o.assignee,modelSelection:uL(o.model_selection),mode:o.mode,systemPrompt:o.system_prompt,maxIterations:o.max_iterations,timeoutSeconds:o.timeout_seconds,availableAt:o.available_at,expiresAt:o.expires_at,automationEligible:o.automation_eligible,updatedBy:i})};return sT(e,o,n,!0),l}case"list":{let d={statuses:o.statuses,types:o.types,scope:a,workspaceRoot:s.workspaceRoot,priorities:o.priorities,automationEligible:o.automation_eligible,limit:o.limit};return{ok:!0,operation:o.operation,tasks:await e.manager.listTasks(d)}}case"get":{let d=await e.manager.getTask(Md(o.task_id,"task_id"));return hL(d,s),{ok:!0,operation:o.operation,task:d}}}}catch(s){return sT(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:s instanceof Error?s.message:String(s)}}}}var Iu="tasks",fL='# Tasks\n\nUse the `tasks` tool to manage durable Todo items and explicitly requested scheduled agent work.\n\n- Use `kind: "todo"` for meaningful follow-ups, handoffs, ideas, reminders, and other work that should remain visible after this session. This includes useful work you identify and suggest proactively. Agent-created Todos require user approval; Todos created directly by the user are approved immediately. Todo `available_at` controls availability in the list; it never schedules execution.\n- Use `kind: "scheduled"` only when the user explicitly asks Cline to execute work once at a future time or on a recurrence. One-time schedules require an exact future ISO 8601 `run_at` with an offset or Z. Recurring schedules require a five-field `cron_pattern` and default to the local timezone. Omit `timezone` unless the user explicitly requests a different timezone; never guess EST, UTC, or another zone. When a timezone is requested, use its IANA name (for example, America/New_York) so daylight-saving changes are handled.\n- "Remind me" is ambiguous: ask whether the user wants a reviewed Todo note or an agent to execute work at that time when intent is unclear.\n- Never create both kinds for the same request unless the user explicitly requests both. Check existing items before creating a likely duplicate.\n- Todo instructions and scheduled prompts must be self-contained. Include the goal, constraints, relevant project context, and expected output.\n- Scheduled sessions run in the user\'s schedules home workspace, not this conversation\'s folder. Include absolute paths in the scheduled `prompt` for any project files or repositories the work must touch.\n- Never approve or start a Todo yourself. Only mutate schedules from an interactive user session, and only update, pause, resume, delete, or run one immediately when the user asks.',TQ="# Tasks\n\nUse the `tasks` tool only when the user explicitly asks Cline to execute work once at a future time or on a recurrence. Always pass `kind: \"scheduled\"`.\n\n- One-time schedules require an exact future ISO 8601 `run_at` with an offset or Z. Recurring schedules require a five-field `cron_pattern` and default to the local timezone. Omit `timezone` unless the user explicitly requests a different timezone; never guess EST, UTC, or another zone. When a timezone is requested, use its IANA name (for example, America/New_York) so daylight-saving changes are handled.\n- Never create a schedule proactively. Check existing schedules before creating a likely duplicate.\n- Make the scheduled `prompt` self-contained because it runs in a new unattended session in the user's schedules home workspace, not this conversation's folder. Include the goal, constraints, expected output, and absolute paths for any project files or repositories the work must touch.\n- Only update, pause, resume, delete, or run a schedule immediately when the user asks for that action.",SQ=kf.extend({kind:Zr.literal("todo")}).strict(),gL=Pd.extend({kind:Zr.literal("scheduled")}).strict(),yL=Zr.discriminatedUnion("kind",[SQ,gL]),xQ=Zr.discriminatedUnion("kind",[gL]),wL=["create","update","list","get","pause","resume","delete","run_now"],_Q=Zr.object({...Pd.shape,...kf.shape,kind:Zr.enum(["todo","scheduled"]),operation:Zr.enum(wL)}).strict(),EQ=Zr.object({...Pd.shape,kind:Zr.enum(["scheduled"]),operation:Zr.enum(wL)}).strict();function aT(e){let t=e.todo;return vQ({name:Iu,description:t?'Create and manage reviewed Todo items or explicitly requested scheduled agent work. Use kind "todo" for durable Agenda items that require user or automation approval. Use kind "scheduled" for one-time or recurring autonomous execution. Todo available_at is not an execution timer; schedules use run_at or cron_pattern.':'Create and manage explicitly requested scheduled agent work with kind "scheduled". One-time schedules use a future ISO 8601 run_at; recurring schedules use a five-field cron_pattern.',inputSchema:kQ(t?_Q:EQ),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?yL:xQ).safeParse(n);if(!o.success)return{ok:!1,kind:typeof n==="object"&&n!==null&&"kind"in n&&(n.kind==="todo"||n.kind==="scheduled")?n.kind:void 0,error:{code:"invalid_tasks_input",message:o.error.issues[0]?.message??"Invalid tasks input"}};if(o.data.kind==="todo"){if(!t)return{ok:!1,kind:"todo",error:{code:"invalid_tasks_input",message:'kind "todo" is not available in this session'}};return{kind:"todo",...await mL(t,o.data,r)}}return{kind:"scheduled",...await Qk(e.scheduled,o.data,r)}}})}function dT(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?TQ:fL,whenToolAvailable:Iu})}}}import{createSessionId as UZ,ensureLoopbackProxyBypass as zL,isHubProtocolCompatible as BZ,resolveClineBuildEnv as HZ,resolveHubCommandTimeoutMs as WZ}from"@cerebriline/shared";import jZ from"ws";var Tf="0.0.92";var Oi={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:Tf,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var Sf="session_not_found";class Od 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 xf(e){return e instanceof Od||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as sZ}from"node:child_process";import{closeSync as aZ,mkdirSync as dZ,openSync as lZ,readFileSync as cZ,unlinkSync as uZ}from"node:fs";import{basename as hZ,dirname as pZ,join as mZ}from"node:path";import{fileURLToPath as fZ}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as gZ,isBunEmbeddedModulePath as yZ,isHubDaemonProcess as $L,resolveClineBuildEnv as FL,withResolvedClineBuildEnv as wZ}from"@cerebriline/shared";import{createHash as AQ,randomBytes as _L}from"node:crypto";import{existsSync as RQ}from"node:fs";import{mkdir as cT,open as vL,readFile as EL,rename as IQ,rm as _f,writeFile as CQ}from"node:fs/promises";import{dirname as AL,join as uT}from"node:path";import{ensureLoopbackProxyBypass as PQ,isHubProtocolCompatible as MQ}from"@cerebriline/shared";import{resolveClineDataDir as Cu,resolveClineDir as Mqe}from"@cerebriline/shared/storage";var OQ="CLINE_HUB_DISCOVERY_PATH",LQ="CLINE_HUB_BUILD_ID",NQ="CLINE_HUB_BUILD_EPOCH_MS",DQ=30000,$Q=15000,kL=100;function FQ(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function UQ(e){return AQ("sha256").update(e).digest("hex").slice(0,12)}function BQ(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 RL(){return _L(32).toString("hex")}function TL(e){return new Promise((t)=>setTimeout(t,e))}function HQ(e){return`${e}.lock`}async function WQ(e){try{let t=JSON.parse(await EL(uT(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 lT(e){await _f(e,{recursive:!0,force:!0}).catch(()=>{return})}function eo(){let e=process.env[LQ]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(Oi.version)}`}function hT(){let e=Number(process.env[NQ]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792737149862)?1792737149862:void 0}function Fs(e,t=eo()){let n=MQ(e);if(!n.compatible)return n;let r=e.buildId?.trim();if(!r)return{compatible:!1,reason:"missing_build"};if(r!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function SL(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function xL(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((r)=>Number(r));if(n.length===0||n.some((r)=>!Number.isInteger(r)||r<0))return;return n}function jQ(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let r=e[n]??0,o=t[n]??0;if(r!==o)return r<o?-1:1}return 0}function Pu(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=SL(e.buildEpochMs),i=SL(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let s=xL(e.coreVersion),a=xL(t.coreVersion);if(s&&a){let d=jQ(s,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function Mu(){return{buildId:eo(),buildEpochMs:hT(),coreVersion:String(Oi.version)}}function Ld(e,t){let n=t?.self??Mu(),r=Fs(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return Pu(n,e)<=0}function Us(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${UQ(e)}`,n=process.env[OQ]?.trim()||uT(Cu(),"locks","hub","owners",`${FQ(t)}.json`);return{ownerId:t,discoveryPath:n}}function Lqe(e=`hub-${Date.now().toString(36)}`){return Us(e)}async function jt(e){try{let t=JSON.parse(await EL(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function Ef(e,t,n){await pT(e,async()=>{let r=AL(e);await cT(r,{recursive:!0});let o=`${e}.${process.pid}.${_L(6).toString("hex")}.tmp`,i;try{i=await vL(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
322
322
  `,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,n?.beforePublish?.(),await IQ(o,e);let s;try{s=await vL(r,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await _f(o,{force:!0}).catch(()=>{return}),s}})}async function Wo(e){await pT(e,async()=>{await _f(e,{force:!0}).catch(()=>{return})})}async function IL(e,t){return await pT(e,async()=>{if((await jt(e))?.hubId!==t)return!1;return await _f(e,{force:!0}),!0})}async function CL(e,t,n){let r=HQ(e);await cT(AL(r),{recursive:!0});let o=Date.now()+$Q;while(!0){try{await cT(r,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await WQ(r);if(!a){if(Date.now()>=o){await lT(r);continue}await TL(kL);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!BQ(a.pid)||d>DQ){await lT(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await TL(kL);continue}try{return await CQ(uT(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
323
323
  `,"utf8"),await n()}finally{await lT(r)}}}function pT(e,t){return CL(`${e}.mutation`,"discovery mutation",t)}function Af(e,t){return CL(e,"startup",t)}async function jo(e,t){PQ();try{let n=await fetch(t?.authToken?qQ(e):PL(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 qo(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function PL(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(PL(e));return t.pathname="/status",t.toString()}function Nqe(e){return RQ(e)}import{CLINE_HUB_DEV_PORT as zQ,CLINE_HUB_PORT as KQ,resolveClineBuildEnv as GQ}from"@cerebriline/shared";var VQ="CLINE_HUB_HOST",XQ="CLINE_HUB_PORT",YQ="CLINE_HUB_PATHNAME",JQ="127.0.0.1",QQ=KQ,ZQ="/hub";function ML(e){return GQ(e)==="development"?zQ:QQ}function eZ(e={}){return(e.env??process.env)[VQ]?.trim()||JQ}function Rf(e={}){let n=(e.env??process.env)[XQ]?.trim();if(!n)return ML(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return ML(e);return r}function tZ(e={}){return(e.env??process.env)[YQ]?.trim()||ZQ}function Bs(e={},t={}){return{host:e.host??eZ(t),port:e.port??Rf(t),pathname:e.pathname??tZ(t)}}import{join as nZ}from"node:path";var rZ="shared:cline",oZ="CLINE_HUB_DISCOVERY_PATH",iZ="hub-production";function Wqe(e){let t=Ms(e.trim());return Us(`workspace:${t||e.trim()}`)}function Ar(e=rZ){return Us(`${e}@${eo()}`)}function to(){return{ownerId:iZ,discoveryPath:process.env[oZ]?.trim()||nZ(Cu(),"locks","hub","production.json")}}var OL=15000,bZ=200,LL=3000,vZ=100,kZ=[100,250,500,1000,2000],TZ="--cline-hub-daemon",SZ=3,xZ=60000,gT=new Map,Zqe={resetRetireAttempts(){gT.clear()},resolveDaemonEntryArgs:BL};function _Z(e,t=Date.now()){let n=gT.get(e);if(!n||t-n.windowStartedAt>xZ)return gT.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=SZ}function EZ(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function AZ(){try{let e=mZ(Cu(),"logs","hub-daemon.log");return dZ(pZ(e),{recursive:!0}),{fd:lZ(e,"a"),logPath:e}}catch{return}}function UL(){return FL()==="production"?to():Ar()}function Ou(e){return Ld(e)}function RZ(e){try{let t=JSON.parse(cZ(`${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 mT(e){try{uZ(`${e}.superseded`)}catch{}}function NL(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Nd(e,t){try{return await jo(e,{authToken:t})}catch{return}}async function DL(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Nd(e))?.url)return!0;await new Promise((o)=>setTimeout(o,vZ))}return!1}async function Dd(e,t){if(!_Z(e.url))return!1;await Hs(e.url,e.authToken,"retired by newer install").catch(()=>!1),await wT(e.url,e.authToken).catch(()=>!1);let n=await DL(e.url,LL);if(!n&&e.pid&&IZ(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await DL(e.url,LL)}if(n)await Wo(t).catch(()=>{return});return n}function IZ(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function yT(e){try{return(await Fd(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function fT(e,t){if(Ou(e))return"reusable";let n=await Hs(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await yT(e)){if(n)await Hs(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Dd(e,t);if(!r&&n)await Hs(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function CZ(e){if(FL()!=="production")return;let t=Ar();if(t.discoveryPath===e.discoveryPath)return;let n=await jt(t.discoveryPath);if(n?.url)await Dd(n,t.discoveryPath);else await Wo(t.discoveryPath).catch(()=>{return})}function PZ(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return fZ(new URL(`./entry.${e}`,import.meta.url))}function BL(e,t){if(yZ(e))return[TZ];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function MZ(e,t){let n=PZ(),r=process.execPath?.trim();if(!r)throw Error("unable to resolve runtime executable for hub daemon");let o=hZ(r).toLowerCase().includes("bun"),i=BL(n,o);return{launcher:r,args:[...i,"--cwd",e,...EZ(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...wZ(process.env),CLINE_NO_INTERACTIVE:"1",[gZ]:"1"}}}function OZ(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 LZ(e,t={}){if($L())return;let n=MZ(e,t),r=AZ();try{sZ(n.launcher,n.args,{detached:!0,stdio:r?["ignore",r.fd,r.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(r)aZ(r.fd)}}async function NZ(e,t={}){for(let n=0;;n++)try{LZ(e,t);return}catch(r){let o=kZ[n];if(!OZ(r)||o===void 0)throw r;await new Promise((i)=>setTimeout(i,o))}}function eze(e,t={}){if($L())return;Lu(e,t).catch(()=>{})}async function DZ(e,t,n={}){let r=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Bs(n),i=qo(o.host,o.port,o.pathname),s=(m)=>{if(!r)$d(m.url,m.authToken);else HL(m.url,m.authToken);return m};await CZ(e).catch(()=>{return});let a=await jt(e.discoveryPath),d=a?.url?void 0:RZ(e.discoveryPath),l=!1;if(a?.url){let m=a.authToken;if(!m)l=!0,await Dd(a,e.discoveryPath);else{let f=await Nd(a.url,m);if(f?.url&&Ou(f)&&await or(f.url,{authToken:m}))return mT(e.discoveryPath),s({url:f.url,authToken:m});if(f?.url){if(await fT({...f,authToken:m},e.discoveryPath)==="deferred_busy"&&await or(f.url,{authToken:m}))return s({url:f.url,authToken:m})}else await Wo(e.discoveryPath).catch(()=>{return})}}let c=await Nd(i);if(c?.url){let m=NL(c,a??d,i);if(Ou(c)){let g=[c.authToken,a?.authToken,d?.authToken].filter((w)=>typeof w==="string"&&w.trim().length>0);for(let w of g){if(!await or(c.url,{authToken:w}))continue;let _={hubId:c.hubId??`repaired-${c.port}`,protocolVersion:c.protocolVersion,minClientProtocolVersion:c.minClientProtocolVersion,maxClientProtocolVersion:c.maxClientProtocolVersion,capabilities:c.capabilities,coreVersion:c.coreVersion,buildId:c.buildId,authToken:w,host:c.host,port:c.port,url:c.url,pid:c.pid??a?.pid??d?.pid,startedAt:c.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await Ef(e.discoveryPath,_)}catch{}return mT(e.discoveryPath),s({url:c.url,authToken:w})}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 f=await fT(m,e.discoveryPath);if(f==="deferred_busy"){for(let g of[m.authToken,a?.authToken].filter((y)=>typeof y==="string"&&y.trim().length>0))if(await or(c.url,{authToken:g}))return s({url:c.url,authToken:g});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(f==="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 NZ(t,{...h,manageConnectors:n.manageConnectors});let p=Date.now()+OL;while(Date.now()<p){let m=await jt(e.discoveryPath);if(m?.url&&m.authToken){let g=await Nd(m.url,m.authToken);if(g?.url&&Ou(g)&&await or(g.url,{authToken:m.authToken}))return mT(e.discoveryPath),s({url:g.url,authToken:m.authToken})}let f=await Nd(i);if(f?.url&&!Ou(f)){let g=NL(f,m??d,i),y=await fT(g,e.discoveryPath);if(y==="deferred_busy"&&m?.authToken&&await or(f.url,{authToken:m.authToken}))return s({url:f.url,authToken:m.authToken});if(y==="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((g)=>setTimeout(g,bZ))}throw Error(`Timed out after ${OL}ms waiting for detached hub startup.`)}async function Lu(e,t={}){let n=UL();return await Af(n.discoveryPath,async()=>DZ(n,e,t))}var $Z=5000,FZ=500;async function tze(e={}){let t=UL(),n=e.workspaceRoot??process.cwd(),r=await jt(t.discoveryPath),o=r?.url?await Nd(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await Lu(n)};let i={...o,authToken:o.authToken??r?.authToken,pid:o.pid??r?.pid};if(Fs(o).compatible)return{outcome:"already_current",url:o.url,authToken:i.authToken};if(Pu(Mu(),o)<=0)return{outcome:"hub_not_older",url:o.url,authToken:i.authToken};if(!await Hs(i.url,i.authToken,e.reason??"hub upgrade requested").catch(()=>!1))throw Error(`The running Cline Hub at ${i.url} did not accept a drain request, so it was not replaced. It is replaced automatically once idle when a Cline client next starts, or run 'cline doctor fix' to stop it now.`);let a=async()=>{await Hs(i.url,i.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},d=Date.now()+(e.waitForIdleMs??$Z),l;for(;;){try{if(l=(await Fd(i.url,i.authToken)).activeSessionCount,l===0)break}catch{}if(Date.now()>=d)break;await new Promise((h)=>setTimeout(h,FZ))}if(l!==0&&e.force!==!0)return await a(),{outcome:"still_busy",url:i.url,authToken:i.authToken,...l!==void 0?{activeSessionCount:l}:{}};if(!await Dd(i,t.discoveryPath))throw await a(),Error(`The running Cline Hub at ${i.url} could not be stopped. Run 'cline doctor fix' to stop stale hub daemons, then try again.`);return{outcome:"replaced",...await Lu(n),activeSessionCount:l??0}}function xT(){return HZ()==="production"?to():Ar()}function qZ(){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 KL(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 KL(e.data);return String(e)}function zZ(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 WL(e){let t=e,n=zZ(t.reason);return new on("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:vT,{closeCode:t.code,closeReason:n||void 0})}function jL(e,t){if(e instanceof on)return e;if(e instanceof Error)return new on("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new on("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 on("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new on("hub_connect_failed",r?`Failed to connect to hub at ${t.toString()} (${r} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var bT="*",If=8000,KZ="cline-hub-auth.",_T=new Map,GL=new Set,GZ=3000,VZ=3000,XZ=100,vT="Hub connection closed",YZ=250,JZ=5000,qL=0.5;class on extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function QZ(e){return e instanceof on}class Cf extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function cze(e,t){return e instanceof Cf&&e.code==="hub_command_timeout"&&(t===void 0||e.command===t)}function ET(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let r=Mf(e.toString());return r?_T.get(r):void 0}function ZZ(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 Mf(e){if(!ZZ(e))return;let t=new URL(Pf(e));return t.search="",t.hash="",t.toString()}function kT(e){let t=Mf(e);return!!t&&GL.has(t)}function $d(e,t){let n=Mf(e);if(n){if(GL.add(n),t?.trim())_T.set(n,t)}return e}function HL(e,t){let n=Mf(e);if(n&&t?.trim())_T.set(n,t)}class Ws{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 on("hub_connection_closed",vT);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()||ET(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,r=this.openSocket(e,t,n),o;this.connectPromise=r.then(async(s)=>{if(o=s,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(Oi.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{s.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(s){if(this.connectPromise===i)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=jL(s,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw s}}async openSocket(e,t,n){let r=this.options.resolveConnectionHeaders,o;if(r){let d;try{o=await Promise.race([Promise.resolve().then(()=>r()),new Promise((l,c)=>{d=setTimeout(()=>{c(new on("hub_connect_timeout",`Timed out resolving hub connection headers after ${If}ms`))},If)})])}catch(l){let c=l instanceof on?l:new on("hub_connect_failed",l instanceof Error?l.message:String(l));if(n===this.connectGeneration)this.lastCloseError=c;throw c}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new on("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let i=o?new jZ(e.toString(),{headers:{...o}}):new(qZ())(e.toString(),t?[`${KZ}${t}`]:void 0);this.socket=i;let s=!1,a=new Promise((d,l)=>{let c=!1,u=setTimeout(()=>{if(c)return;c=!0,s=!0;let h=new on("hub_connect_timeout",`Timed out connecting to hub after ${If}ms`);if(this.socket===i)this.lastCloseError=h,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}l(h)},If);i.addEventListener("open",()=>{if(c)return;c=!0,clearTimeout(u),d()}),i.addEventListener("error",(h)=>{if(c)return;c=!0,clearTimeout(u);let p=jL(h,e);if(this.socket===i)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;l(p)}),i.addEventListener("close",(h)=>{if(c)return;c=!0,clearTimeout(u);let p=s?this.lastCloseError:WL(h);if(this.socket===i){if(!s)this.lastCloseError=p,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}l(p)})});return i.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(KL(d)))}),i.addEventListener("close",(d)=>{if(this.socket!==i)return;if(!s)this.lastCloseError=WL(d),this.sawSocketClose=!0;this.registered=!1;for(let l of this.pendingReplies.values())l.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await a,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,r={listener:e,sessionId:n};return this.listeners.add(r),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(r))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,r){let o=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,r)}catch(s){if(!i||o>=1||!await this.recoverLocalHubTransport(s))throw s;o+=1}}async commandOnce(e,t,n,r,o=!0){if(o)await this.connect();r?.beforeDispatch?.();let i=UZ("hubreq_");r?.onDispatch?.(i);let s=WZ(e,r?.timeoutMs),a=new Promise((l,c)=>{let u=s===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;c(new Cf(e,"hub_command_timeout",`Hub command ${e} timed out after ${s}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.`))},s);this.pendingReplies.set(i,{resolve:(h)=>{if(u)clearTimeout(u);l(h)},reject:(h)=>{if(u)clearTimeout(u);c(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:s,payload:t}})}catch(l){throw this.pendingReplies.delete(i),l}let d=await a;if(!d.ok){if(d.error?.code===Sf){let l=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Od(l,d.error.message)}throw new Cf(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!kT(this.currentUrl)||!QZ(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await ST({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(YZ*2**this.reconnectAttempt,JZ),t=Math.round(e*(1-qL)+Math.random()*e*qL);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(!kT(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await ST({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 on("hub_connection_closed",vT);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 on("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),r=(this.subscriptionCounts.get(n)??0)+t;if(r<=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,r),t>0&&r===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??bT}subscriptionSessionIdFromKey(e){return e===bT?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 r of[bT,n]){if(!r||!this.subscriptionCounts.has(r))continue;let o=this.lastEventSequenceByKey.get(r)??0;if(t>o)this.lastEventSequenceByKey.set(r,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 Pf(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 or(e,t){let n=new Ws({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 TT(e,t){let n=Pf(e),r=await jo(n,{authToken:t?.authToken});if(!r)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=eo(),i=Fs(r,o);if(!i.compatible&&!Ld(r))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!BZ(r).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await or(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}async function eee(e){let t=Date.now()+VZ;while(Date.now()<t){if(!(await jo(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,XZ))}return!1}function tee(e,t){try{return Pf(e)===Pf(t)}catch{return!1}}function VL(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,r=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 s of i){let a=s&&typeof s==="object"?s.clientId:void 0;if(typeof a==="string"&&a.trim())r.add(a)}}return{activeSessionCount:n,participantClientCount:r.size}}function uze(e){return VL(e).activeSessionCount>0}async function Fd(e,t,n){let r=new Ws({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await r.command("session.list",{limit:500},void 0,{timeoutMs:GZ});return VL(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function XL(e,t,n){try{return(await Fd(e,t,n)).activeSessionCount===0}catch{return!1}}async function nee(e,t){let n=`${e.discoveryPath}.superseded`,r=await jt(n);if(!r?.url||!r.authToken)return;let o=await TT(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await XL(o.url,r.authToken,t))return;return $d(o.url,r.authToken)}async function ree(e={}){if(e.endpoint?.trim()){let o=await TT(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=xT(),n=await jt(t.discoveryPath);if(!n?.url)return await nee(t,e);let r=await TT(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return $d(r.url,n.authToken);if(r.status==="protocol_mismatch")await Wo(t.discoveryPath).catch(()=>{return});return}async function ST(e={}){let t=await ree(e);if(t&&await or(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Lu(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function Hs(e,t,n,r){zL();let o=new URL(e),i=t?.trim()||ET(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(r?.off)o.searchParams.set("off","1");return(await fetch(o,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function wT(e,t){zL();let n=new URL(e),r=t?.trim()||ET(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:r?{authorization:`Bearer ${r}`}:void 0})).ok}async function oee(e=xT()){let t=await jt(e.discoveryPath);if(!t?.url)return!1;try{if(await wT(t.url,t.authToken))return!0}catch{}return!1}async function hze(e){if(!kT(e.url))return;let t=xT(),n=await jt(t.discoveryPath);if(!n?.url||!tee(n.url,e.url))return;if(!await XL(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await oee())return;if(!await eee(n.url))return;return await Wo(t.discoveryPath).catch(()=>{return}),await ST({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveClineBuildEnv as iee}from"@cerebriline/shared";function see(e,t){if(e instanceof Error)return e;if(e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"&&e.message.trim())return Error(e.message.trim());let n=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return Error(n?`Failed to connect to hub at ${t} (${n} event before socket open).`:`Failed to connect to hub at ${t}.`)}var aee="cline-hub-auth.";function dee(e){return e.host!==void 0||e.port!==void 0||e.pathname!==void 0}function lee(e,t){let n=new URL(e),r=new URL(t);return n.search="",n.hash="",r.search="",r.hash="",n.toString()===r.toString()}function YL(){return iee()==="production"?to():Ar()}async function cee(e){let t=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),t)return t;let n=YL(),r=await jt(n.discoveryPath);if(r?.url&&lee(e.toString(),r.url))return r.authToken;return}async function uee(e={}){let t=Bs(e);if(!dee(e)){let n=YL(),r=await jt(n.discoveryPath);if(r?.url)return r.url}return qo(t.host,t.port,t.pathname)}async function JL(e){return await new Promise((t,n)=>{(async()=>{let r=new URL(e),o=await cee(r);r.hash="";let i=new WebSocket(r.toString(),o?[`${aee}${o}`]:void 0),s=new Map,a=0;i.addEventListener("open",()=>{t({send(d){let l=d.requestId??`hub-client-${++a}`;return new Promise((c,u)=>{s.set(l,{resolve:c,reject:u});let h={kind:"command",envelope:{...d,requestId:l}};i.send(JSON.stringify(h))})},close(){i.close()}})}),i.addEventListener("message",(d)=>{let l=JSON.parse(String(d.data));if(l.kind==="reply"&&l.envelope.requestId){let c=s.get(l.envelope.requestId);if(c)s.delete(l.envelope.requestId),c.resolve(l.envelope)}}),i.addEventListener("close",()=>{for(let d of s.values())d.reject(Error("Hub connection closed"));s.clear()}),i.addEventListener("error",(d)=>{n(see(d,e))})})().catch(n)})}async function wze(e){try{return(await JL(e)).close(),!0}catch{return!1}}async function bze(e,t){let n=await uee(e),r=await JL(n);try{return await r.send({version:t.version??"v1",clientId:t.clientId??"hub-client",...t})}finally{r.close()}}import{existsSync as hee}from"node:fs";import{isHubDaemonProcess as pee,resolveClineBuildEnv as mee}from"@cerebriline/shared";var fee=1e4,gee="CLINE_HUB_BUILD_WATCH_INTERVAL_MS";function yee(){let e=Number(process.env[gee]);return Number.isFinite(e)&&e>0?e:fee}async function wee(e,t){try{let n=await Fd(e.url,t);return{...e,activeSessionCount:n.activeSessionCount,participantClientCount:n.participantClientCount}}catch{return e}}function bee(){return mee()==="production"?to():Ar()}function vee(e){try{return hee(`${e}.lock`)}catch{return!1}}async function kee(){let e=bee();if(vee(e.discoveryPath))return;let t=await jt(e.discoveryPath).catch(()=>{return});if(!t?.url)return;let n=await jo(t.url).catch(()=>{return});if(!n?.url)return;let r=eo(),o=Fs(n,r);if(o.compatible)return;let i=(a)=>({url:n.url,reason:a,hubBuildId:n.buildId,hubCoreVersion:n.coreVersion,expectedBuildId:r});if(o.reason==="unsupported_protocol")return i("unsupported_protocol");let s=Mu();if(s.coreVersion&&n.coreVersion&&s.coreVersion===n.coreVersion)return;if(Pu(s,n)>0)return await wee(i("outdated_hub"),t.authToken);return i("build_mismatch")}function Eze(e){if(pee()||process.env.CLINE_HUB_PORT?.trim())return()=>{};let t=e.intervalMs??yee(),n,r,o=!1,i=setInterval(()=>{if(o)return;o=!0,kee().then((s)=>{if(!s){n=void 0,r=void 0;return}let a=`${s.reason}:${s.hubBuildId??""}`;if(a===n)return;if(s.reason==="outdated_hub"&&r!==a){r=a;return}r=void 0,n=a,e.onMismatch(s)}).catch(()=>{return}).finally(()=>{o=!1})},t);return i.unref?.(),()=>{clearInterval(i)}}function AT(e){return e?JSON.parse(JSON.stringify(e)):{}}function Of(e){let t=e?.session&&typeof e.session==="object"?e.session:void 0;if(!t)return;let n=t.metadata&&typeof t.metadata==="object"?AT(t.metadata):void 0;return{sessionId:typeof t.sessionId==="string"?t.sessionId:"",parentSessionId:typeof n?.parentSessionId==="string"?n.parentSessionId:void 0,status:typeof t.status==="string"?t.status:void 0,messagesPath:typeof n?.messagesPath==="string"?n.messagesPath:void 0,metadata:n}}function QL(e,t){return e.error?.message??`hub command failed: ${t}`}function Tee(e){let t=AT(e);if(typeof t.error==="string"&&t.error.trim())return{...t,error:t.error.trim()};let n=t.result&&typeof t.result==="object"?t.result:void 0;if(typeof n?.text==="string"&&n.text.trim())return{...t,error:n.text.trim()};let r=n?.error&&typeof n.error==="object"?n.error:void 0;if(typeof r?.message==="string"&&r.message.trim())return{...t,error:r.message.trim()};return t}function ZL(e){let t=e?.sessionId;return typeof t==="string"&&t.trim()?t.trim():void 0}function See(e){let t=e?.checkpoint;if(!t||typeof t!=="object"||Array.isArray(t))throw Error("hub checkpoint restore returned no checkpoint");let n=t;if(typeof n.ref!=="string"||typeof n.createdAt!=="number"||typeof n.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return n}function xee(e){let t=AT(e.payload);if(e.event==="schedule.execution_completed")return{sessionId:e.sessionId?.trim()||ZL(t)||"",eventType:"schedule.execution.completed",payload:t};if(e.event==="schedule.execution_failed")return{sessionId:e.sessionId?.trim()||ZL(t)||"",eventType:"schedule.execution.failed",payload:t};let n=e.sessionId?.trim();if(!n)return;switch(e.event){case"iteration.started":return{sessionId:n,eventType:"runtime.chat.iteration_start",payload:t};case"iteration.finished":return{sessionId:n,eventType:"runtime.chat.iteration_end",payload:t};case"assistant.delta":return{sessionId:n,eventType:"runtime.chat.text_delta",payload:t};case"assistant.media":return{sessionId:n,eventType:"runtime.chat.media",payload:t};case"usage.updated":return{sessionId:n,eventType:"runtime.chat.usage",payload:t};case"session.notice":return{sessionId:n,eventType:"runtime.chat.notice",payload:t};case"tool.started":return{sessionId:n,eventType:"runtime.chat.tool_call_start",payload:t};case"tool.updated":return{sessionId:n,eventType:"runtime.chat.tool_call_update",payload:t};case"tool.finished":return{sessionId:n,eventType:"runtime.chat.tool_call_end",payload:t};case"approval.requested":return{sessionId:n,eventType:"approval.requested",payload:t};case"run.aborted":return{sessionId:n,eventType:"runtime.chat.aborted",payload:t};case"run.failed":return{sessionId:n,eventType:"runtime.chat.failed",payload:Tee(e.payload)};case"run.completed":return{sessionId:n,eventType:"runtime.chat.completed",payload:t};default:return}}class _ee{client;constructor(e){this.client=new Ws({url:e.address,authToken:e.authToken,clientId:e.clientId,clientType:e.clientType??"hub-session-client",displayName:e.displayName??"hub session client",workspaceRoot:e.workspaceRoot,cwd:e.cwd,metadata:e.metadata})}async connect(){await this.client.connect()}async taskCommand(e,t){return await this.client.connect(),(await this.client.command(e,t)).payload??{}}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(e){await this.client.connect();let t=await this.client.command("session.create",{workspaceRoot:e.workspaceRoot,cwd:e.cwd,sessionConfig:{providerId:e.provider,modelId:e.model,apiKey:e.apiKey,cwd:e.cwd??e.workspaceRoot,workspaceRoot:e.workspaceRoot,systemPrompt:e.systemPrompt??"",mode:e.mode??"act",rules:e.rules,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,enableTools:e.enableTools,enableSpawnAgent:e.enableSpawn!==!1,enableAgentTeams:e.enableTeams===!0,disableMcpSettingsTools:e.disableMcpSettingsTools,agentPluginPaths:e.agentPluginPaths,missionLogIntervalSteps:e.missionStepInterval,missionLogIntervalMs:e.missionTimeIntervalMs},metadata:{source:e.source??"cli",provider:e.provider,model:e.model,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,prompt:void 0,interactive:e.interactive!==!1},runtimeOptions:{mode:e.mode,systemPrompt:e.systemPrompt,maxIterations:e.maxIterations,timeoutSeconds:e.timeoutSeconds,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,autoApproveTools:e.autoApproveTools,toolExecutors:e.toolExecutors,configExtensions:e.configExtensions},modelSelection:{provider:e.provider,model:e.model,apiKey:e.apiKey},toolPolicies:e.toolPolicies}),n=Of(t.payload);if(!n?.sessionId)throw Error("hub session create returned no session id");return{sessionId:n.sessionId,startResult:{sessionId:n.sessionId,manifestPath:"",messagesPath:n.messagesPath??""}}}async sendRuntimeSession(e,t,n){return await this.client.connect(),{result:(await this.client.command("session.send_input",{prompt:t.prompt,mode:t.config.mode,attachments:t.attachments,delivery:t.delivery,timeoutSeconds:t.config.timeoutSeconds},e,n)).payload?.result}}async stopRuntimeSession(e){return await this.client.connect(),await this.client.command("session.detach",{sessionId:e},e),{applied:!0}}async abortRuntimeSession(e){return await this.client.connect(),await this.client.command("run.abort",{sessionId:e},e),{applied:!0}}async updateSession(e){return await this.client.connect(),await this.client.command("session.update",{sessionId:e.sessionId,metadata:e.metadata},e.sessionId),{updated:!0}}async getSession(e){await this.client.connect();let t;try{t=await this.client.command("session.get",void 0,e)}catch(n){if(xf(n))return;throw n}return Of(t.payload)}async readMessages(e){let t=e.trim();if(!t)return[];await this.client.connect();let n=await this.client.command("session.messages",{sessionId:t},t);if(!n.ok)throw Error(QL(n,"session.messages"));let r=n.payload?.messages;return Array.isArray(r)?r:[]}async restore(e){let t=e.sessionId.trim();if(!t)throw Error("sessionId is required");let n=e.restore?.messages!==!1;if(n&&!e.config)throw Error("config is required when restore.messages is true");await this.client.connect();let r=e.config,o=await this.client.command("session.restore",{sessionId:t,checkpointRunCount:e.checkpointRunCount,restore:e.restore,...r?{workspaceRoot:r.workspaceRoot,cwd:r.cwd,sessionConfig:{providerId:r.provider,modelId:r.model,apiKey:r.apiKey,cwd:r.cwd??r.workspaceRoot,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:r.mode??"act",rules:r.rules,maxIterations:r.maxIterations,enableTools:r.enableTools,enableSpawnAgent:r.enableSpawn!==!1,enableAgentTeams:r.enableTeams===!0,disableMcpSettingsTools:r.disableMcpSettingsTools,agentPluginPaths:r.agentPluginPaths,missionLogIntervalSteps:r.missionStepInterval,missionLogIntervalMs:r.missionTimeIntervalMs},metadata:{source:r.source??"cli",provider:r.provider,model:r.model,enableTools:r.enableTools,enableSpawn:r.enableSpawn,enableTeams:r.enableTeams,prompt:void 0,interactive:r.interactive!==!1},runtimeOptions:{mode:r.mode,systemPrompt:r.systemPrompt,maxIterations:r.maxIterations,enableTools:r.enableTools,enableSpawn:r.enableSpawn,enableTeams:r.enableTeams,autoApproveTools:r.autoApproveTools,configExtensions:r.configExtensions},modelSelection:{provider:r.provider,model:r.model,apiKey:r.apiKey},toolPolicies:r.toolPolicies}:{}},t);if(!o.ok)throw Error(QL(o,"session.restore"));let i=Of(o.payload);if(n&&!i?.sessionId)throw Error("hub checkpoint restore returned no session id");let s=Array.isArray(o.payload?.messages)?o.payload.messages:void 0,a=See(o.payload);return{sessionId:i?.sessionId,startResult:i?.sessionId?{sessionId:i.sessionId,manifestPath:"",messagesPath:i.messagesPath??""}:void 0,...s?{messages:s}:{},checkpoint:a}}async listSessions(e){await this.client.connect();let t=await this.client.command("session.list",{limit:e?.limit??200});return(Array.isArray(t.payload?.sessions)?t.payload?.sessions:[]).map((r)=>Of({session:r})).filter((r)=>Boolean(r?.sessionId))}async searchSessions(e){await this.client.connect();let t=await this.client.command("session.search",e);return Array.isArray(t.payload?.hits)?t.payload.hits:[]}async deleteSession(e,t=!0){return await this.client.connect(),(await this.client.command("session.delete",{sessionId:e,deleteCheckpointRefs:t})).payload?.deleted===!0}async respondToolApproval(e){await this.client.connect(),await this.client.command("approval.respond",{approvalId:e.approvalId,approved:e.approved,payload:e.reason?{reason:e.reason}:void 0,responderClientId:e.responderClientId})}streamEvents(e,t){let n=new Set((e.sessionIds??[]).map((o)=>o.trim()).filter(Boolean)),r=this.client.subscribe((o)=>{let i=xee(o);if(!i)return;if(n.size>0&&!n.has(i.sessionId))return;t.onEvent?.(i)});return this.client.connect().catch((o)=>{t.onError?.(o instanceof Error?o:Error(String(o)))}),r}streamTeamProgress(e,t){let n=this.client.subscribe((r)=>{if(r.event!=="team.progress"||!r.payload)return;t.onProjection?.(r.payload)});return this.client.connect().catch((r)=>{t.onError?.(r instanceof Error?r:Error(String(r)))}),n}async createSchedule(e){return await this.client.connect(),(await this.client.command("schedule.create",e)).payload?.schedule}async listSchedules(e){await this.client.connect();let t=await this.client.command("schedule.list");return Array.isArray(t.payload?.schedules)?t.payload?.schedules:[]}async getSchedule(e){return await this.client.connect(),(await this.client.command("schedule.get",{scheduleId:e})).payload?.schedule}async updateSchedule(e,t){return await this.client.connect(),(await this.client.command("schedule.update",{scheduleId:e,...t})).payload?.schedule}async pauseSchedule(e){return await this.client.connect(),(await this.client.command("schedule.disable",{scheduleId:e})).payload?.schedule}async resumeSchedule(e){return await this.client.connect(),(await this.client.command("schedule.enable",{scheduleId:e})).payload?.schedule}async deleteSchedule(e){return await this.client.connect(),(await this.client.command("schedule.delete",{scheduleId:e})).payload?.deleted===!0}async triggerScheduleNow(e){return await this.client.connect(),(await this.client.command("schedule.trigger",{scheduleId:e})).payload?.execution}async listScheduleExecutions(e,t){await this.client.connect();let n=await this.client.command("schedule.list_executions",{scheduleId:e,limit:t});return Array.isArray(n.payload?.executions)?n.payload?.executions:[]}async getScheduleStats(){return await this.client.connect(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.client.connect();let e=await this.client.command("schedule.active");return Array.isArray(e.payload?.executions)?e.payload?.executions:[]}async getUpcomingScheduledRuns(e){await this.client.connect();let t=await this.client.command("schedule.upcoming",{limit:e});return Array.isArray(t.payload?.upcoming)?t.payload?.upcoming:[]}async createTask(e){return(await this.taskCommand("task.create",e)).task}async listTasks(e={}){let t=await this.taskCommand("task.list",e);return Array.isArray(t.tasks)?t.tasks:[]}async getTask(e){return(await this.taskCommand("task.get",{taskId:e})).task}async updateTask(e){return(await this.taskCommand("task.update",e)).task}async approveTask(e,t){return(await this.taskCommand("task.approve",{taskId:e,expectedRevision:t})).task}async cancelTask(e,t,n){return(await this.taskCommand("task.cancel",{taskId:e,reason:n,expectedRevision:t})).task}async runTask(e,t){return await this.taskCommand("task.run",{taskId:e,expectedRevision:t})}async getTaskAutomation(){return(await this.taskCommand("task.automation.get",{})).policy}async setTaskAutomation(e){return(await this.taskCommand("task.automation.set",{policy:e})).policy}}class Eee{client;constructor(e){this.client=new Ws({url:e.address,authToken:e.authToken,clientId:e.clientId,clientType:e.clientType??"hub-ui-client",displayName:e.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(e){await this.client.command("ui.notify",e)}async sendShowWindow(e){await this.client.command("ui.show_window",e??{})}async listClients(){let e=await this.client.command("client.list");return Array.isArray(e.payload?.clients)?e.payload.clients:[]}async listSessions(e=200){let t=await this.client.command("session.list",{limit:e});return Array.isArray(t.payload?.sessions)?t.payload.sessions:[]}async searchSessions(e){let t=await this.client.command("session.search",e);return Array.isArray(t.payload?.hits)?t.payload.hits:[]}async toggleSetting(e){let t=await this.client.command("settings.toggle",e);if(!t.ok)throw Error(t.error?.message??"settings.toggle failed");return t.payload}subscribeUI(e){return this.client.subscribe((t)=>{switch(t.event){case"ui.notify":e.onNotify?.(t.payload);break;case"ui.show_window":e.onShowWindow?.(t.payload);break;case"hub.client.registered":e.onClientRegistered?.(t.payload??{});break;case"hub.client.disconnected":e.onClientDisconnected?.(t.payload??{});break;case"session.created":e.onSessionCreated?.(t.payload??{});break;case"session.updated":e.onSessionUpdated?.(t.payload??{});break;case"session.detached":e.onSessionDetached?.(t.payload??{});break}})}}import{normalizeProviderId as b1e}from"@cerebriline/llms";import{existsSync as RUe,readdirSync as IUe}from"node:fs";import{readFile as CUe}from"node:fs/promises";import{homedir as PUe}from"node:os";import{isAbsolute as cX,join as Ei,resolve as a0}from"node:path";import{onXollamaSideCall as MUe,releasePolykvSwarmsOf as sX}from"@cerebriline/llms";import{applyPromptTemplateToTools as OUe,captureSdkError as Tr,createSessionId as LUe,isLikelyAuthError as NUe,normalizeUserInput as DUe}from"@cerebriline/shared";import{setHomeDirIfUnset as $Ue}from"@cerebriline/shared/storage";import{decodeJwtPayload as kte,getClineEnvironmentConfig as kN}from"@cerebriline/shared";import{decodeJwtPayload as Oee,getClineEnvironmentConfig as Lee}from"@cerebriline/shared";import{createHash as Aee}from"node:crypto";var Ree;function Hn(e){if(typeof e!=="string"||e.length===0)return"unset";return Aee("sha256").update(e).digest("hex").slice(0,8)}function dt(e){try{Ree?.debug(e)}catch{}}function Iee(){let e;return{promise:new Promise((n)=>{e=n}),resolve:e}}async function js(e){let t=await import("node:http"),n=e.host??"127.0.0.1",r=e.timeoutMs??300000,o=e.successHtml??Cee,i=Iee(),s=!1,a=null,d=null,l=null,c=(p)=>{if(s)return;s=!0,i.resolve(p)},u=()=>{if(a)clearTimeout(a),a=null;let p=l;if(l=null,d)d.close(),d.closeAllConnections?.(),d=null;if(p!==null&&e.onClose)Promise.resolve(e.onClose({host:n,port:p})).catch(()=>{})},h=async()=>(a=setTimeout(()=>{u(),c(null)},r),i.promise);for(let p of e.ports){let m=t.createServer((g,y)=>{try{let w=new URL(g.url||"",`http://${n}:${p}`);if(w.pathname!==e.callbackPath){y.statusCode=404,y.end("Not found");return}let _={url:w,code:w.searchParams.get("code")??void 0,state:w.searchParams.get("state")??void 0,provider:w.searchParams.get("provider")??void 0,error:w.searchParams.get("error")??void 0};if(_.error){y.statusCode=400,y.end(`Authentication failed: ${_.error}`),u(),c(_);return}if(!_.code){y.statusCode=400,y.end("Missing authorization code");return}if(e.expectedState&&_.state!==e.expectedState){y.statusCode=400,y.end("State mismatch");return}y.statusCode=200,y.setHeader("Content-Type","text/html; charset=utf-8"),y.end(o),u(),c(_)}catch{y.statusCode=500,y.end("Internal error")}}),f=await new Promise((g)=>{let y=(w)=>{m.off("error",y),g({bound:!1,error:w})};m.once("error",y),m.listen(p,n,()=>{m.off("error",y),d=m,g({bound:!0})})});if(f.error){if(f.error.code==="EADDRINUSE")continue;throw u(),f.error}if(f.bound){l=p;let g=`http://${n}:${p}${e.callbackPath}`;if(e.onListening)await Promise.resolve(e.onListening({host:n,port:p,callbackUrl:g})).catch(()=>{});return{callbackUrl:g,waitForCallback:h,cancelWait:()=>{u(),c(null)},close:()=>{u(),c(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var Cee=`<!DOCTYPE html>
324
324
  <html lang="en">
package/dist/index.js CHANGED
@@ -2409,7 +2409,7 @@ ${JSON.stringify(r,null,2)}`}startClaimLeaseHeartbeat(e){let t=Math.max(1000,Mat
2409
2409
  `)[0]?.trim())}function Os(e){if(!e)return;let t={...e},n=hc(typeof t.title==="string"?t.title:void 0);if(n)t.title=n;else delete t.title;return Object.keys(t).length>0?t:void 0}function gw(e){let t=Os(e.metadata)??{},n=e.title!==void 0?hc(e.title):Z$(e.prompt);if(n)t.title=n;return Object.keys(t).length>0?t:void 0}function eF(e){let t=Zi(e.metadata),n={source:e.source,mode:t?.mode??"user",sessionId:e.sessionId,...e.parentSessionId?{parentThreadId:e.parentSessionId}:{},...e.agentId?{subagent:e.agentId}:{},...t?.version?{version:t.version}:{},...t?.trigger?{trigger:t.trigger}:{}};if(mc(e.sessionId))return{agent:"teammate",sessionId:e.sessionId,taskType:"team",origin:n};if(Fm(e.sessionId))return{agent:"subagent",sessionId:e.sessionId,taskType:"subagent_task",origin:n};return{agent:"lead",sessionId:e.sessionId,origin:n}}function tF(e){return{version:1,updated_at:e.updatedAt,agent:e.context.agent,sessionId:e.context.sessionId,...e.context.taskType?{taskType:e.context.taskType}:{},origin:e.context.origin,messages:hE(e.messages),...e.systemPrompt?{system_prompt:e.systemPrompt}:{}}}function AZ(e,t,n){N2e($2e(e),{recursive:!0}),D2e(e,`${JSON.stringify(tF({updatedAt:t,context:n,messages:[]}),null,2)}
2410
2410
  `,"utf8")}function RZ(e,t){return Rr.parse({version:1,session_id:e.sessionId,source:e.source,pid:e.pid,started_at:e.startedAt,ended_at:t?.endedAt??e.endedAt??void 0,exit_code:t?.exitCode??e.exitCode??void 0,status:t?.status??e.status,interactive:e.interactive,provider:e.provider,model:e.model,cwd:e.cwd,workspace_root:e.workspaceRoot,team_name:e.teamName??void 0,enable_tools:e.enableTools,enable_spawn:e.enableSpawn,enable_teams:e.enableTeams,prompt:e.prompt??void 0,metadata:t?.metadata??e.metadata??void 0,messages_path:e.messagesPath??void 0})}async function CZ(e,t,n){let r=0;while(!0){let o=await e();if(o===void 0)return{updated:!1};let i=await t(o);if(typeof i==="object"&&i!==null&&"updated"in i&&i.updated===!1){if(r+=1,r>=n)return i;continue}return i}}import{existsSync as nF}from"node:fs";import{readFile as W2e}from"node:fs/promises";import{join as j2e}from"node:path";class yw{listeners=new Set;subscribe(e,t){let n={listener:e,sessionId:t?.sessionId?.trim()||void 0};return this.listeners.add(n),()=>{this.listeners.delete(n)}}emit(e){let t=e.payload.sessionId?.trim();for(let n of this.listeners){if(n.sessionId&&n.sessionId!==t)continue;n.listener(e)}}get size(){return this.listeners.size}}function IZ(e,t,n){let r=e?.trim();if(r&&nF(r))return r;let o=n?.trim();if(o){let i=j2e(o,t,`${t}.messages.json`);if(nF(i))return i}return r||void 0}async function fc(e){let t=e?.trim();if(!t||!nF(t))return[];try{let n=(await W2e(t,"utf8")).trim();if(!n)return[];let r=JSON.parse(n);if(Array.isArray(r))return r;if(r&&typeof r==="object"&&!Array.isArray(r)){let o=r.messages;if(Array.isArray(o))return o}return[]}catch{return[]}}function rF(e){return e?{...e}:void 0}async function PZ(e,t){if(!(e.hookName==="tool_call"||!!e.parent_agent_id))return;await t.queueSpawnRequest(e);let r=await t.upsertSubagentSessionFromHook(e);if(!r)return;await t.appendSubagentHookAudit(r,e),await t.applySubagentStatus(r,e)}function ww(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function no(e){let t=ww(e);if(!t)return;return t.toLowerCase()==="unknown"?void 0:t}function gE(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function V2e(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return{...e}}function sF(e){let t=e??200;return Number.isFinite(t)?Math.max(0,Math.floor(t)):200}var oF=2000;function Y2e(e){if(e===0)return 0;return Math.min(Math.max(e*2,20),oF)}function X2e(e){return e.isSubagent!==!0&&!ww(e.parentSessionId)}function J2e(e){let t=e.match(/\d{13,}/g);if(!t||t.length===0)return 0;let n=0;for(let r of t){let o=Number.parseInt(r,10);if(Number.isFinite(o)&&o>n)n=o}return n}function aF(e){let t=mc(e.session_id)?.rootSessionId??Fm(e.session_id)?.rootSessionId;return{sessionId:e.session_id,source:e.source,pid:e.pid,startedAt:e.started_at,endedAt:e.ended_at??null,exitCode:e.exit_code??null,status:e.status,interactive:e.interactive,provider:e.provider,model:e.model,cwd:e.cwd,workspaceRoot:e.workspace_root,teamName:e.team_name,enableTools:e.enable_tools,enableSpawn:e.enable_spawn,enableTeams:e.enable_teams,isSubagent:t!==void 0,...t!==void 0?{parentSessionId:t}:{},prompt:e.prompt,metadata:e.metadata,messagesPath:e.messages_path,updatedAt:e.ended_at??e.started_at}}async function Q2e(e){let t=sF(e);if(t===0)return[];let n=NZ(),o=(await q2e(n,{withFileTypes:!0}).catch(()=>[])).filter((s)=>s.isDirectory()).map((s)=>({entry:s,recency:J2e(s.name.trim())})).sort((s,a)=>a.recency-s.recency||a.entry.name.localeCompare(s.entry.name));return(await Promise.all(o.map(async({entry:s})=>{let a=s.name.trim();if(!a)return;let d=LZ(n,a,`${a}.json`),l=await OZ(d,"utf8").catch(()=>{return});if(!l)return;let c;try{c=JSON.parse(l)}catch{return}let u=Rr.safeParse(c);if(!u.success)return;return aF(u.data)}))).filter((s)=>Boolean(s)).sort((s,a)=>a.startedAt.localeCompare(s.startedAt)).slice(0,t)}async function Z2e(e,t,n){let r=sF(t);if(r===0)return await e.listSessions(0),[];if(n.includeSubagents)return(await e.listSessions(r)).slice(0,r);let o=Y2e(r);for(;;){let i=await e.listSessions(o,{rootOnly:!0}),s=i.filter(X2e);if(s.length>=r||i.length<o||o>=oF)return s.slice(0,r);o=Math.min(o*2,oF)}}function eze(e){if(typeof e==="string")return e.trim();let t=[];for(let n of e){if(!n||typeof n!=="object")continue;let r=n;if(r.type!=="text")continue;let o=r.text?.trim();if(o)t.push(o)}return t.join(`
2411
2411
  `).trim()}function MZ(e){return e.replace(/\s+/g," ").trim()}function tze(e,t){if(e.length<=t)return e;return`${e.slice(0,Math.max(0,t-3)).trimEnd()}...`}function nze(e){for(let t of["user","assistant"])for(let n of e){if(n.role!==t)continue;let r=MZ(eze(n.content));if(!r)continue;let o=t==="user"?MZ(G2e(r)):r,i=K2e(o.split(`
2412
- `)[0]??o);return tze(i,50)}return}function rze(e){let t=0;for(let n of e)t+=gE(n.metrics?.cost)??0;return t}function oze(e){let t,n;for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(!t)t=no(o.modelInfo?.provider);if(!n)n=no(o.modelInfo?.id);if(t&&n)break}return{provider:t,model:n}}function ize(e){return no(e?.provider)??no(e?.provider&&typeof e.provider==="object"&&!Array.isArray(e.provider)?e.provider.id:void 0)}function sze(e){return no(e?.model)??no(e?.model&&typeof e.model==="object"&&!Array.isArray(e.model)?e.model.id:void 0)}function iF(e,t){let n=V2e(e.metadata),r=ww(t?.title)??ww(n?.title),o=gE(t?.totalCost)??gE(n?.totalCost),i=n||r!==void 0||o!==void 0?{...n??{},...r!==void 0?{title:r}:{},...o!==void 0?{totalCost:o}:{}}:void 0;return{...e,provider:no(t?.provider)??no(e.provider)??ize(n)??"",model:no(t?.model)??no(e.model)??sze(n)??"",metadata:i}}function aze(e){let t=e.content;if(!Array.isArray(t))return!1;return t.some((n)=>!!n&&typeof n==="object"&&n.type==="tool-call")}function dze(e,t){if(e.status!=="running"||e.interactive!==!0)return!1;let n=t.at(-1);return n?.role==="assistant"&&!aze(n)}async function lze(e,t){return await Promise.all(t.map(async(n)=>{if(n.status!=="running"||n.interactive!==!0)return n;let r=await e.readSessionMessages(n.sessionId);return dze(n,r)?{...n,status:"idle"}:n}))}async function cze(e,t){return await Promise.all(t.map(async(n)=>{let r=iF(n),o=Boolean(ww(r.metadata?.title)),i=Boolean(no(r.provider)),s=Boolean(no(r.model)),a=gE(r.metadata?.totalCost),d=a!==void 0&&a>0;if(o&&i&&s&&d)return r;let l=await e.readSessionMessages(n.sessionId);if(l.length===0)return r;let c=oze(l),u=rze(l);return iF(n,{title:o?void 0:nze(l),provider:i?void 0:c.provider,model:s?void 0:c.model,totalCost:d||u<=0?void 0:u})}))}async function dF(e,t={}){let n=sF(t.limit),r=t.includeSubagents===!0,o=await Z2e(e,n,{includeSubagents:r}),i=t.includeManifestFallback===!0&&o.length<n?await Q2e(Math.min(Math.max(n*2,100),500)):[],s=new Map;for(let l of[...o,...i.filter((c)=>r||!c.isSubagent)]){if(s.has(l.sessionId))continue;s.set(l.sessionId,l)}let a=i.length===0?o:Array.from(s.values()).sort((l,c)=>c.startedAt.localeCompare(l.startedAt)).slice(0,n),d=await Promise.all((await lze(e,a)).map(pze));if(t.hydrate===!1)return d.map((l)=>iF(l));return await cze(e,d)}var uze="stale_session_reconciler";async function pze(e){let t=e.metadata;if(t?.terminal_marker_source!==uze)return e;let n=e.endedAt??void 0;if(n&&n===t.terminal_marker_at&&e.messagesPath){let r=await z2e(e.messagesPath).then((o)=>o.mtime.toISOString()).catch(()=>{return});if(r&&r<n&&r>=e.startedAt)n=r}return n?{...e,endedAt:n,updatedAt:n}:e}async function mze(e){let t=e.trim();if(!t)return;let n=LZ(NZ(),t,`${t}.json`),r=await OZ(n,"utf8").catch(()=>{return});if(!r)return;try{let o=Rr.safeParse(JSON.parse(r));return o.success?o.data.messages_path:void 0}catch{return}}async function hze(e,t={}){let n=new Map;return await dF({listSessions:async(o,i)=>{let s=await e.listSessions(o,i);n.clear();for(let a of s)n.set(a.sessionId,a);return s.map(fw)},readSessionMessages:async(o)=>{let i=n.get(o)?.messagesPath??await mze(o);return await fc(i)}},t)}import{captureSdkError as Kae}from"@cerebriline/shared";import{createSessionId as AGe,ensureLoopbackProxyBypass as dee,isHubProtocolCompatible as RGe,resolveClineBuildEnv as CGe,resolveHubCommandTimeoutMs as IGe}from"@cerebriline/shared";import PGe from"ws";import{spawn as Vze}from"node:child_process";import{closeSync as Yze,mkdirSync as Xze,openSync as Jze,readFileSync as Qze,unlinkSync as Zze}from"node:fs";import{basename as eGe,dirname as tGe,join as nGe}from"node:path";import{fileURLToPath as rGe}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as oGe,isBunEmbeddedModulePath as iGe,isHubDaemonProcess as ZZ,resolveClineBuildEnv as eee,withResolvedClineBuildEnv as sGe}from"@cerebriline/shared";import{createHash as fze,randomBytes as HZ}from"node:crypto";import{existsSync as gze}from"node:fs";import{mkdir as cF,open as DZ,readFile as WZ,rename as yze,rm as yE,writeFile as wze}from"node:fs/promises";import{dirname as jZ,join as uF}from"node:path";import{ensureLoopbackProxyBypass as bze,isHubProtocolCompatible as vze}from"@cerebriline/shared";import{resolveClineDataDir as bw,resolveClineDir as tIt}from"@cerebriline/shared/storage";var kze="CLINE_HUB_DISCOVERY_PATH",Sze="CLINE_HUB_BUILD_ID",Tze="CLINE_HUB_BUILD_EPOCH_MS",xze=30000,_ze=15000,$Z=100;function Eze(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Aze(e){return fze("sha256").update(e).digest("hex").slice(0,12)}function Rze(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 qZ(){return HZ(32).toString("hex")}function FZ(e){return new Promise((t)=>setTimeout(t,e))}function Cze(e){return`${e}.lock`}async function Ize(e){try{let t=JSON.parse(await WZ(uF(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 lF(e){await yE(e,{recursive:!0,force:!0}).catch(()=>{return})}function Ri(){let e=process.env[Sze]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(Oa.version)}`}function pF(){let e=Number(process.env[Tze]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792707017870)?1792707017870:void 0}function gc(e,t=Ri()){let n=vze(e);if(!n.compatible)return n;let r=e.buildId?.trim();if(!r)return{compatible:!1,reason:"missing_build"};if(r!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function UZ(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function BZ(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((r)=>Number(r));if(n.length===0||n.some((r)=>!Number.isInteger(r)||r<0))return;return n}function Pze(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let r=e[n]??0,o=t[n]??0;if(r!==o)return r<o?-1:1}return 0}function vw(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=UZ(e.buildEpochMs),i=UZ(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let s=BZ(e.coreVersion),a=BZ(t.coreVersion);if(s&&a){let d=Pze(s,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function kw(){return{buildId:Ri(),buildEpochMs:pF(),coreVersion:String(Oa.version)}}function Um(e,t){let n=t?.self??kw(),r=gc(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return vw(n,e)<=0}function yc(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Aze(e)}`,n=process.env[kze]?.trim()||uF(bw(),"locks","hub","owners",`${Eze(t)}.json`);return{ownerId:t,discoveryPath:n}}function rIt(e=`hub-${Date.now().toString(36)}`){return yc(e)}async function yn(e){try{let t=JSON.parse(await WZ(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function wE(e,t,n){await mF(e,async()=>{let r=jZ(e);await cF(r,{recursive:!0});let o=`${e}.${process.pid}.${HZ(6).toString("hex")}.tmp`,i;try{i=await DZ(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
2412
+ `)[0]??o);return tze(i,50)}return}function rze(e){let t=0;for(let n of e)t+=gE(n.metrics?.cost)??0;return t}function oze(e){let t,n;for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(!t)t=no(o.modelInfo?.provider);if(!n)n=no(o.modelInfo?.id);if(t&&n)break}return{provider:t,model:n}}function ize(e){return no(e?.provider)??no(e?.provider&&typeof e.provider==="object"&&!Array.isArray(e.provider)?e.provider.id:void 0)}function sze(e){return no(e?.model)??no(e?.model&&typeof e.model==="object"&&!Array.isArray(e.model)?e.model.id:void 0)}function iF(e,t){let n=V2e(e.metadata),r=ww(t?.title)??ww(n?.title),o=gE(t?.totalCost)??gE(n?.totalCost),i=n||r!==void 0||o!==void 0?{...n??{},...r!==void 0?{title:r}:{},...o!==void 0?{totalCost:o}:{}}:void 0;return{...e,provider:no(t?.provider)??no(e.provider)??ize(n)??"",model:no(t?.model)??no(e.model)??sze(n)??"",metadata:i}}function aze(e){let t=e.content;if(!Array.isArray(t))return!1;return t.some((n)=>!!n&&typeof n==="object"&&n.type==="tool-call")}function dze(e,t){if(e.status!=="running"||e.interactive!==!0)return!1;let n=t.at(-1);return n?.role==="assistant"&&!aze(n)}async function lze(e,t){return await Promise.all(t.map(async(n)=>{if(n.status!=="running"||n.interactive!==!0)return n;let r=await e.readSessionMessages(n.sessionId);return dze(n,r)?{...n,status:"idle"}:n}))}async function cze(e,t){return await Promise.all(t.map(async(n)=>{let r=iF(n),o=Boolean(ww(r.metadata?.title)),i=Boolean(no(r.provider)),s=Boolean(no(r.model)),a=gE(r.metadata?.totalCost),d=a!==void 0&&a>0;if(o&&i&&s&&d)return r;let l=await e.readSessionMessages(n.sessionId);if(l.length===0)return r;let c=oze(l),u=rze(l);return iF(n,{title:o?void 0:nze(l),provider:i?void 0:c.provider,model:s?void 0:c.model,totalCost:d||u<=0?void 0:u})}))}async function dF(e,t={}){let n=sF(t.limit),r=t.includeSubagents===!0,o=await Z2e(e,n,{includeSubagents:r}),i=t.includeManifestFallback===!0&&o.length<n?await Q2e(Math.min(Math.max(n*2,100),500)):[],s=new Map;for(let l of[...o,...i.filter((c)=>r||!c.isSubagent)]){if(s.has(l.sessionId))continue;s.set(l.sessionId,l)}let a=i.length===0?o:Array.from(s.values()).sort((l,c)=>c.startedAt.localeCompare(l.startedAt)).slice(0,n),d=await Promise.all((await lze(e,a)).map(pze));if(t.hydrate===!1)return d.map((l)=>iF(l));return await cze(e,d)}var uze="stale_session_reconciler";async function pze(e){let t=e.metadata;if(t?.terminal_marker_source!==uze)return e;let n=e.endedAt??void 0;if(n&&n===t.terminal_marker_at&&e.messagesPath){let r=await z2e(e.messagesPath).then((o)=>o.mtime.toISOString()).catch(()=>{return});if(r&&r<n&&r>=e.startedAt)n=r}return n?{...e,endedAt:n,updatedAt:n}:e}async function mze(e){let t=e.trim();if(!t)return;let n=LZ(NZ(),t,`${t}.json`),r=await OZ(n,"utf8").catch(()=>{return});if(!r)return;try{let o=Rr.safeParse(JSON.parse(r));return o.success?o.data.messages_path:void 0}catch{return}}async function hze(e,t={}){let n=new Map;return await dF({listSessions:async(o,i)=>{let s=await e.listSessions(o,i);n.clear();for(let a of s)n.set(a.sessionId,a);return s.map(fw)},readSessionMessages:async(o)=>{let i=n.get(o)?.messagesPath??await mze(o);return await fc(i)}},t)}import{captureSdkError as Kae}from"@cerebriline/shared";import{createSessionId as AGe,ensureLoopbackProxyBypass as dee,isHubProtocolCompatible as RGe,resolveClineBuildEnv as CGe,resolveHubCommandTimeoutMs as IGe}from"@cerebriline/shared";import PGe from"ws";import{spawn as Vze}from"node:child_process";import{closeSync as Yze,mkdirSync as Xze,openSync as Jze,readFileSync as Qze,unlinkSync as Zze}from"node:fs";import{basename as eGe,dirname as tGe,join as nGe}from"node:path";import{fileURLToPath as rGe}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as oGe,isBunEmbeddedModulePath as iGe,isHubDaemonProcess as ZZ,resolveClineBuildEnv as eee,withResolvedClineBuildEnv as sGe}from"@cerebriline/shared";import{createHash as fze,randomBytes as HZ}from"node:crypto";import{existsSync as gze}from"node:fs";import{mkdir as cF,open as DZ,readFile as WZ,rename as yze,rm as yE,writeFile as wze}from"node:fs/promises";import{dirname as jZ,join as uF}from"node:path";import{ensureLoopbackProxyBypass as bze,isHubProtocolCompatible as vze}from"@cerebriline/shared";import{resolveClineDataDir as bw,resolveClineDir as tIt}from"@cerebriline/shared/storage";var kze="CLINE_HUB_DISCOVERY_PATH",Sze="CLINE_HUB_BUILD_ID",Tze="CLINE_HUB_BUILD_EPOCH_MS",xze=30000,_ze=15000,$Z=100;function Eze(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Aze(e){return fze("sha256").update(e).digest("hex").slice(0,12)}function Rze(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 qZ(){return HZ(32).toString("hex")}function FZ(e){return new Promise((t)=>setTimeout(t,e))}function Cze(e){return`${e}.lock`}async function Ize(e){try{let t=JSON.parse(await WZ(uF(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 lF(e){await yE(e,{recursive:!0,force:!0}).catch(()=>{return})}function Ri(){let e=process.env[Sze]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(Oa.version)}`}function pF(){let e=Number(process.env[Tze]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792737149862)?1792737149862:void 0}function gc(e,t=Ri()){let n=vze(e);if(!n.compatible)return n;let r=e.buildId?.trim();if(!r)return{compatible:!1,reason:"missing_build"};if(r!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function UZ(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function BZ(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((r)=>Number(r));if(n.length===0||n.some((r)=>!Number.isInteger(r)||r<0))return;return n}function Pze(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let r=e[n]??0,o=t[n]??0;if(r!==o)return r<o?-1:1}return 0}function vw(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=UZ(e.buildEpochMs),i=UZ(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let s=BZ(e.coreVersion),a=BZ(t.coreVersion);if(s&&a){let d=Pze(s,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function kw(){return{buildId:Ri(),buildEpochMs:pF(),coreVersion:String(Oa.version)}}function Um(e,t){let n=t?.self??kw(),r=gc(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return vw(n,e)<=0}function yc(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Aze(e)}`,n=process.env[kze]?.trim()||uF(bw(),"locks","hub","owners",`${Eze(t)}.json`);return{ownerId:t,discoveryPath:n}}function rIt(e=`hub-${Date.now().toString(36)}`){return yc(e)}async function yn(e){try{let t=JSON.parse(await WZ(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function wE(e,t,n){await mF(e,async()=>{let r=jZ(e);await cF(r,{recursive:!0});let o=`${e}.${process.pid}.${HZ(6).toString("hex")}.tmp`,i;try{i=await DZ(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
2413
2413
  `,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,n?.beforePublish?.(),await yze(o,e);let s;try{s=await DZ(r,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await yE(o,{force:!0}).catch(()=>{return}),s}})}async function Ls(e){await mF(e,async()=>{await yE(e,{force:!0}).catch(()=>{return})})}async function zZ(e,t){return await mF(e,async()=>{if((await yn(e))?.hubId!==t)return!1;return await yE(e,{force:!0}),!0})}async function GZ(e,t,n){let r=Cze(e);await cF(jZ(r),{recursive:!0});let o=Date.now()+_ze;while(!0){try{await cF(r,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await Ize(r);if(!a){if(Date.now()>=o){await lF(r);continue}await FZ($Z);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!Rze(a.pid)||d>xze){await lF(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await FZ($Z);continue}try{return await wze(uF(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
2414
2414
  `,"utf8"),await n()}finally{await lF(r)}}}function mF(e,t){return GZ(`${e}.mutation`,"discovery mutation",t)}function bE(e,t){return GZ(e,"startup",t)}async function Ns(e,t){bze();try{let n=await fetch(t?.authToken?Mze(e):KZ(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 Ds(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function KZ(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function Mze(e){let t=new URL(KZ(e));return t.pathname="/status",t.toString()}function oIt(e){return gze(e)}import{CLINE_HUB_DEV_PORT as Oze,CLINE_HUB_PORT as Lze,resolveClineBuildEnv as Nze}from"@cerebriline/shared";var Dze="CLINE_HUB_HOST",$ze="CLINE_HUB_PORT",Fze="CLINE_HUB_PATHNAME",Uze="127.0.0.1",Bze=Lze,Hze="/hub";function VZ(e){return Nze(e)==="development"?Oze:Bze}function Wze(e={}){return(e.env??process.env)[Dze]?.trim()||Uze}function vE(e={}){let n=(e.env??process.env)[$ze]?.trim();if(!n)return VZ(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return VZ(e);return r}function jze(e={}){return(e.env??process.env)[Fze]?.trim()||Hze}function wc(e={},t={}){return{host:e.host??Wze(t),port:e.port??vE(t),pathname:e.pathname??jze(t)}}import{join as qze}from"node:path";var zze="shared:cline",Gze="CLINE_HUB_DISCOVERY_PATH",Kze="hub-production";function uIt(e){let t=nd(e.trim());return yc(`workspace:${t||e.trim()}`)}function No(e=zze){return yc(`${e}@${Ri()}`)}function Ci(){return{ownerId:Kze,discoveryPath:process.env[Gze]?.trim()||qze(bw(),"locks","hub","production.json")}}var YZ=15000,aGe=200,XZ=3000,dGe=100,lGe=[100,250,500,1000,2000],cGe="--cline-hub-daemon",uGe=3,pGe=60000,gF=new Map,SIt={resetRetireAttempts(){gF.clear()},resolveDaemonEntryArgs:nee};function mGe(e,t=Date.now()){let n=gF.get(e);if(!n||t-n.windowStartedAt>pGe)return gF.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=uGe}function hGe(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function fGe(){try{let e=nGe(bw(),"logs","hub-daemon.log");return Xze(tGe(e),{recursive:!0}),{fd:Jze(e,"a"),logPath:e}}catch{return}}function tee(){return eee()==="production"?Ci():No()}function Sw(e){return Um(e)}function gGe(e){try{let t=JSON.parse(Qze(`${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 hF(e){try{Zze(`${e}.superseded`)}catch{}}function JZ(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Bm(e,t){try{return await Ns(e,{authToken:t})}catch{return}}async function QZ(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Bm(e))?.url)return!0;await new Promise((o)=>setTimeout(o,dGe))}return!1}async function Hm(e,t){if(!mGe(e.url))return!1;await bc(e.url,e.authToken,"retired by newer install").catch(()=>!1),await xw(e.url,e.authToken).catch(()=>!1);let n=await QZ(e.url,XZ);if(!n&&e.pid&&yGe(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await QZ(e.url,XZ)}if(n)await Ls(t).catch(()=>{return});return n}function yGe(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function yF(e){try{return(await jm(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function fF(e,t){if(Sw(e))return"reusable";let n=await bc(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await yF(e)){if(n)await bc(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Hm(e,t);if(!r&&n)await bc(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function wGe(e){if(eee()!=="production")return;let t=No();if(t.discoveryPath===e.discoveryPath)return;let n=await yn(t.discoveryPath);if(n?.url)await Hm(n,t.discoveryPath);else await Ls(t.discoveryPath).catch(()=>{return})}function bGe(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return rGe(new URL(`./entry.${e}`,import.meta.url))}function nee(e,t){if(iGe(e))return[cGe];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function vGe(e,t){let n=bGe(),r=process.execPath?.trim();if(!r)throw Error("unable to resolve runtime executable for hub daemon");let o=eGe(r).toLowerCase().includes("bun"),i=nee(n,o);return{launcher:r,args:[...i,"--cwd",e,...hGe(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...sGe(process.env),CLINE_NO_INTERACTIVE:"1",[oGe]:"1"}}}function kGe(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 SGe(e,t={}){if(ZZ())return;let n=vGe(e,t),r=fGe();try{Vze(n.launcher,n.args,{detached:!0,stdio:r?["ignore",r.fd,r.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(r)Yze(r.fd)}}async function TGe(e,t={}){for(let n=0;;n++)try{SGe(e,t);return}catch(r){let o=lGe[n];if(!kGe(r)||o===void 0)throw r;await new Promise((i)=>setTimeout(i,o))}}function ree(e,t={}){if(ZZ())return;Tw(e,t).catch(()=>{})}async function xGe(e,t,n={}){let r=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=wc(n),i=Ds(o.host,o.port,o.pathname),s=(h)=>{if(!r)Wm(h.url,h.authToken);else oee(h.url,h.authToken);return h};await wGe(e).catch(()=>{return});let a=await yn(e.discoveryPath),d=a?.url?void 0:gGe(e.discoveryPath),l=!1;if(a?.url){let h=a.authToken;if(!h)l=!0,await Hm(a,e.discoveryPath);else{let f=await Bm(a.url,h);if(f?.url&&Sw(f)&&await ro(f.url,{authToken:h}))return hF(e.discoveryPath),s({url:f.url,authToken:h});if(f?.url){if(await fF({...f,authToken:h},e.discoveryPath)==="deferred_busy"&&await ro(f.url,{authToken:h}))return s({url:f.url,authToken:h})}else await Ls(e.discoveryPath).catch(()=>{return})}}let c=await Bm(i);if(c?.url){let h=JZ(c,a??d,i);if(Sw(c)){let y=[c.authToken,a?.authToken,d?.authToken].filter((b)=>typeof b==="string"&&b.trim().length>0);for(let b of y){if(!await ro(c.url,{authToken:b}))continue;let k={hubId:c.hubId??`repaired-${c.port}`,protocolVersion:c.protocolVersion,minClientProtocolVersion:c.minClientProtocolVersion,maxClientProtocolVersion:c.maxClientProtocolVersion,capabilities:c.capabilities,coreVersion:c.coreVersion,buildId:c.buildId,authToken:b,host:c.host,port:c.port,url:c.url,pid:c.pid??a?.pid??d?.pid,startedAt:c.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await wE(e.discoveryPath,k)}catch{}return hF(e.discoveryPath),s({url:c.url,authToken:b})}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 f=await fF(h,e.discoveryPath);if(f==="deferred_busy"){for(let y of[h.authToken,a?.authToken].filter((g)=>typeof g==="string"&&g.trim().length>0))if(await ro(c.url,{authToken:y}))return s({url:c.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(f==="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 p=n.allowPortFallback===!0&&o.port!==0?{...o,port:0}:o;await TGe(t,{...p,manageConnectors:n.manageConnectors});let m=Date.now()+YZ;while(Date.now()<m){let h=await yn(e.discoveryPath);if(h?.url&&h.authToken){let y=await Bm(h.url,h.authToken);if(y?.url&&Sw(y)&&await ro(y.url,{authToken:h.authToken}))return hF(e.discoveryPath),s({url:y.url,authToken:h.authToken})}let f=await Bm(i);if(f?.url&&!Sw(f)){let y=JZ(f,h??d,i),g=await fF(y,e.discoveryPath);if(g==="deferred_busy"&&h?.authToken&&await ro(f.url,{authToken:h.authToken}))return s({url:f.url,authToken:h.authToken});if(g==="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,aGe))}throw Error(`Timed out after ${YZ}ms waiting for detached hub startup.`)}async function Tw(e,t={}){let n=tee();return await bE(n.discoveryPath,async()=>xGe(n,e,t))}var _Ge=5000,EGe=500;async function TIt(e={}){let t=tee(),n=e.workspaceRoot??process.cwd(),r=await yn(t.discoveryPath),o=r?.url?await Bm(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await Tw(n)};let i={...o,authToken:o.authToken??r?.authToken,pid:o.pid??r?.pid};if(gc(o).compatible)return{outcome:"already_current",url:o.url,authToken:i.authToken};if(vw(kw(),o)<=0)return{outcome:"hub_not_older",url:o.url,authToken:i.authToken};if(!await bc(i.url,i.authToken,e.reason??"hub upgrade requested").catch(()=>!1))throw Error(`The running Cline Hub at ${i.url} did not accept a drain request, so it was not replaced. It is replaced automatically once idle when a Cline client next starts, or run 'cline doctor fix' to stop it now.`);let a=async()=>{await bc(i.url,i.authToken,"hub upgrade aborted",{off:!0}).catch(()=>!1)},d=Date.now()+(e.waitForIdleMs??_Ge),l;for(;;){try{if(l=(await jm(i.url,i.authToken)).activeSessionCount,l===0)break}catch{}if(Date.now()>=d)break;await new Promise((p)=>setTimeout(p,EGe))}if(l!==0&&e.force!==!0)return await a(),{outcome:"still_busy",url:i.url,authToken:i.authToken,...l!==void 0?{activeSessionCount:l}:{}};if(!await Hm(i,t.discoveryPath))throw await a(),Error(`The running Cline Hub at ${i.url} could not be stopped. Run 'cline doctor fix' to stop stale hub daemons, then try again.`);return{outcome:"replaced",...await Tw(n),activeSessionCount:l??0}}function SF(){return CGe()==="production"?Ci():No()}function MGe(){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 lee(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 lee(e.data);return String(e)}function OGe(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 iee(e){let t=e,n=OGe(t.reason);return new Nn("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:bF,{closeCode:t.code,closeReason:n||void 0})}function see(e,t){if(e instanceof Nn)return e;if(e instanceof Error)return new Nn("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new Nn("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 Nn("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new Nn("hub_connect_failed",r?`Failed to connect to hub at ${t.toString()} (${r} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var wF="*",kE=8000,LGe="cline-hub-auth.",TF=new Map,cee=new Set,NGe=3000,DGe=3000,$Ge=100,bF="Hub connection closed",FGe=250,UGe=5000,aee=0.5;class Nn extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function BGe(e){return e instanceof Nn}class SE extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function uee(e,t){return e instanceof SE&&e.code==="hub_command_timeout"&&(t===void 0||e.command===t)}function xF(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let r=TE(e.toString());return r?TF.get(r):void 0}function HGe(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 TE(e){if(!HGe(e))return;let t=new URL(qm(e));return t.search="",t.hash="",t.toString()}function vF(e){let t=TE(e);return!!t&&cee.has(t)}function Wm(e,t){let n=TE(e);if(n){if(cee.add(n),t?.trim())TF.set(n,t)}return e}function oee(e,t){let n=TE(e);if(n&&t?.trim())TF.set(n,t)}class $s{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 Nn("hub_connection_closed",bF);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()||xF(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,r=this.openSocket(e,t,n),o;this.connectPromise=r.then(async(s)=>{if(o=s,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(Oa.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{s.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(s){if(this.connectPromise===i)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=see(s,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw s}}async openSocket(e,t,n){let r=this.options.resolveConnectionHeaders,o;if(r){let d;try{o=await Promise.race([Promise.resolve().then(()=>r()),new Promise((l,c)=>{d=setTimeout(()=>{c(new Nn("hub_connect_timeout",`Timed out resolving hub connection headers after ${kE}ms`))},kE)})])}catch(l){let c=l instanceof Nn?l:new Nn("hub_connect_failed",l instanceof Error?l.message:String(l));if(n===this.connectGeneration)this.lastCloseError=c;throw c}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new Nn("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let i=o?new PGe(e.toString(),{headers:{...o}}):new(MGe())(e.toString(),t?[`${LGe}${t}`]:void 0);this.socket=i;let s=!1,a=new Promise((d,l)=>{let c=!1,u=setTimeout(()=>{if(c)return;c=!0,s=!0;let p=new Nn("hub_connect_timeout",`Timed out connecting to hub after ${kE}ms`);if(this.socket===i)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}l(p)},kE);i.addEventListener("open",()=>{if(c)return;c=!0,clearTimeout(u),d()}),i.addEventListener("error",(p)=>{if(c)return;c=!0,clearTimeout(u);let m=see(p,e);if(this.socket===i)this.lastCloseError=m,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;l(m)}),i.addEventListener("close",(p)=>{if(c)return;c=!0,clearTimeout(u);let m=s?this.lastCloseError:iee(p);if(this.socket===i){if(!s)this.lastCloseError=m,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}l(m)})});return i.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(lee(d)))}),i.addEventListener("close",(d)=>{if(this.socket!==i)return;if(!s)this.lastCloseError=iee(d),this.sawSocketClose=!0;this.registered=!1;for(let l of this.pendingReplies.values())l.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await a,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,r={listener:e,sessionId:n};return this.listeners.add(r),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(r))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,r){let o=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,r)}catch(s){if(!i||o>=1||!await this.recoverLocalHubTransport(s))throw s;o+=1}}async commandOnce(e,t,n,r,o=!0){if(o)await this.connect();r?.beforeDispatch?.();let i=AGe("hubreq_");r?.onDispatch?.(i);let s=IGe(e,r?.timeoutMs),a=new Promise((l,c)=>{let u=s===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;c(new SE(e,"hub_command_timeout",`Hub command ${e} timed out after ${s}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.`))},s);this.pendingReplies.set(i,{resolve:(p)=>{if(u)clearTimeout(u);l(p)},reject:(p)=>{if(u)clearTimeout(u);c(p)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:s,payload:t}})}catch(l){throw this.pendingReplies.delete(i),l}let d=await a;if(!d.ok){if(d.error?.code===ow){let l=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new dc(l,d.error.message)}throw new SE(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!vF(this.currentUrl)||!BGe(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await _w({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(FGe*2**this.reconnectAttempt,UGe),t=Math.round(e*(1-aee)+Math.random()*e*aee);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(!vF(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await _w({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 Nn("hub_connection_closed",bF);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 Nn("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),r=(this.subscriptionCounts.get(n)??0)+t;if(r<=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,r),t>0&&r===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??wF}subscriptionSessionIdFromKey(e){return e===wF?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 r of[wF,n]){if(!r||!this.subscriptionCounts.has(r))continue;let o=this.lastEventSequenceByKey.get(r)??0;if(t>o)this.lastEventSequenceByKey.set(r,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 qm(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 ro(e,t){let n=new $s({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 kF(e,t){let n=qm(e),r=await Ns(n,{authToken:t?.authToken});if(!r)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=Ri(),i=gc(r,o);if(!i.compatible&&!Um(r))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!RGe(r).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await ro(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}async function WGe(e){let t=Date.now()+DGe;while(Date.now()<t){if(!(await Ns(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,$Ge))}return!1}function jGe(e,t){try{return qm(e)===qm(t)}catch{return!1}}function pee(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,r=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 s of i){let a=s&&typeof s==="object"?s.clientId:void 0;if(typeof a==="string"&&a.trim())r.add(a)}}return{activeSessionCount:n,participantClientCount:r.size}}function MIt(e){return pee(e).activeSessionCount>0}async function jm(e,t,n){let r=new $s({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await r.command("session.list",{limit:500},void 0,{timeoutMs:NGe});return pee(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function mee(e,t,n){try{return(await jm(e,t,n)).activeSessionCount===0}catch{return!1}}async function qGe(e,t){let n=`${e.discoveryPath}.superseded`,r=await yn(n);if(!r?.url||!r.authToken)return;let o=await kF(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await mee(o.url,r.authToken,t))return;return Wm(o.url,r.authToken)}async function _F(e={}){if(e.endpoint?.trim()){let o=await kF(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=SF(),n=await yn(t.discoveryPath);if(!n?.url)return await qGe(t,e);let r=await kF(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return Wm(r.url,n.authToken);if(r.status==="protocol_mismatch")await Ls(t.discoveryPath).catch(()=>{return});return}async function _w(e={}){let t=await _F(e);if(t&&await ro(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Tw(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function bc(e,t,n,r){dee();let o=new URL(e),i=t?.trim()||xF(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(r?.off)o.searchParams.set("off","1");return(await fetch(o,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function xw(e,t){dee();let n=new URL(e),r=t?.trim()||xF(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:r?{authorization:`Bearer ${r}`}:void 0})).ok}async function zGe(e=SF()){let t=await yn(e.discoveryPath);if(!t?.url)return!1;try{if(await xw(t.url,t.authToken))return!0}catch{}return!1}async function hee(e){if(!vF(e.url))return;let t=SF(),n=await yn(t.discoveryPath);if(!n?.url||!jGe(n.url,e.url))return;if(!await mee(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await zGe())return;if(!await WGe(n.url))return;return await Ls(t.discoveryPath).catch(()=>{return}),await _w({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveProviderRequestHeaders as ZGe}from"@cerebriline/llms";import{captureSdkError as CF,createSessionId as vee,HUB_CHECKPOINT_CAPABILITY as eKe,HUB_COMPACTION_CAPABILITY as tKe,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as nKe,HUB_HOOK_CAPABILITY_PREFIX as rKe,HUB_MISTAKE_LIMIT_CAPABILITY as oKe,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as iKe,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as sKe,isGeneratedMedia as aKe,isHubToolExecutorName as dKe}from"@cerebriline/shared";Hr();import{createHash as GGe}from"node:crypto";import{formatDisplayUserInput as fee}from"@cerebriline/shared";import{z as Ii}from"zod";function KGe(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let t=e;if(t.role!=="user"&&t.role!=="assistant")return!1;return typeof t.content==="string"||Array.isArray(t.content)}var VGe=Ii.custom(KGe),xE=Ii.object({version:Ii.literal(1),updated_at:Ii.string().datetime(),conversation_id:Ii.string().min(1).optional(),source_message_count:Ii.number().int().nonnegative(),source_prefix_hash:Ii.string().min(1).optional(),source_last_message_key:Ii.string().min(1).optional(),messages:Ii.array(VGe),system_prompt:Ii.string().optional()});function EF(e){return e.filter((t)=>t.metadata?.displayOnly!==!0)}function AF(e){return JSON.parse(JSON.stringify(e))}function gee(e){if(e.role!=="user")return e;if(typeof e.content==="string")return{...e,content:fee(e.content)};return{...e,content:e.content.map((t)=>t.type==="text"?{...t,text:fee(t.text)}:t)}}function yee(e){if(e.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function YGe(e){let t=gee(e);return yee(t.role),[["role",t.role],["content",t.content],["agent",t.agent??null],["sessionId",t.sessionId??null],["metadata",t.metadata??null],["modelInfo",t.modelInfo??null],["metrics",t.metrics??null]]}function wee(e){if(!e)return"";let t=gee(e);if(typeof t.id==="string"&&t.id.trim())return`id:${t.id.trim()}`;if(yee(t.role),typeof t.ts==="number"&&Number.isFinite(t.ts))return`ts:${t.role}:${t.ts}`;return`content:${t.role}:${JSON.stringify(t.content)}`}function bee(e,t=e.length){let n=GGe("sha256");n.update(`cline-session-compaction-source-v2
2415
2415
  `),n.update(`${t}
@@ -1,4 +1,4 @@
1
- import{homedir as $n}from"node:os";import{claimHubDaemonProcess as jn}from"@cerebriline/shared";import{setHomeDirIfUnset as Gn}from"@cerebriline/shared/storage";import{createSessionId as gn,ensureLoopbackProxyBypass as Ue,isHubProtocolCompatible as bn,resolveClineBuildEnv as yn,resolveHubCommandTimeoutMs as wn}from"@cerebriline/shared";import vn from"ws";var P={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var ie="session_not_found";class F 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"}}import{spawn as Ot}from"node:child_process";import{closeSync as Lt,mkdirSync as Ut,openSync as Mt,readFileSync as Bt,unlinkSync as Nt}from"node:fs";import{basename as Vt,dirname as Ft,join as Wt}from"node:path";import{fileURLToPath as $t}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as jt,isBunEmbeddedModulePath as Gt,isHubDaemonProcess as qt,resolveClineBuildEnv as Ee,withResolvedClineBuildEnv as Kt}from"@cerebriline/shared";import{createHash as Xe,randomBytes as Ze}from"node:crypto";import{mkdir as j,open as se,readFile as le,rename as Qe,rm as I,writeFile as et}from"node:fs/promises";import{dirname as pe,join as G}from"node:path";import{ensureLoopbackProxyBypass as tt,isHubProtocolCompatible as nt}from"@cerebriline/shared";import{resolveClineDataDir as H,resolveClineDir as eo}from"@cerebriline/shared/storage";var ot="CLINE_HUB_DISCOVERY_PATH",rt="CLINE_HUB_BUILD_ID",it="CLINE_HUB_BUILD_EPOCH_MS",st=30000,at=15000,ae=100;function ct(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ut(e){return Xe("sha256").update(e).digest("hex").slice(0,12)}function dt(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 ce(e){return new Promise((t)=>setTimeout(t,e))}function lt(e){return`${e}.lock`}async function pt(e){try{let t=JSON.parse(await le(G(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 W(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[rt]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(P.version)}`}function ft(){let e=Number(process.env[it]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792707017870)?1792707017870:void 0}function x(e,t=k()){let n=nt(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ue(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function de(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function mt(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function fe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ue(e.buildEpochMs),i=ue(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let s=de(e.coreVersion),u=de(t.coreVersion);if(s&&u){let c=mt(s,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function me(){return{buildId:k(),buildEpochMs:ft(),coreVersion:String(P.version)}}function D(e,t){let n=t?.self??me(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return fe(n,e)<=0}function he(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${ut(e)}`,n=process.env[ot]?.trim()||G(H(),"locks","hub","owners",`${ct(t)}.json`);return{ownerId:t,discoveryPath:n}}async function b(e){try{let t=JSON.parse(await le(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function ge(e,t,n){await q(e,async()=>{let o=pe(e);await j(o,{recursive:!0});let r=`${e}.${process.pid}.${Ze(6).toString("hex")}.tmp`,i;try{i=await se(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
1
+ import{homedir as $n}from"node:os";import{claimHubDaemonProcess as jn}from"@cerebriline/shared";import{setHomeDirIfUnset as Gn}from"@cerebriline/shared/storage";import{createSessionId as gn,ensureLoopbackProxyBypass as Ue,isHubProtocolCompatible as bn,resolveClineBuildEnv as yn,resolveHubCommandTimeoutMs as wn}from"@cerebriline/shared";import vn from"ws";var P={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var ie="session_not_found";class F 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"}}import{spawn as Ot}from"node:child_process";import{closeSync as Lt,mkdirSync as Ut,openSync as Mt,readFileSync as Bt,unlinkSync as Nt}from"node:fs";import{basename as Vt,dirname as Ft,join as Wt}from"node:path";import{fileURLToPath as $t}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as jt,isBunEmbeddedModulePath as Gt,isHubDaemonProcess as qt,resolveClineBuildEnv as Ee,withResolvedClineBuildEnv as Kt}from"@cerebriline/shared";import{createHash as Xe,randomBytes as Ze}from"node:crypto";import{mkdir as j,open as se,readFile as le,rename as Qe,rm as I,writeFile as et}from"node:fs/promises";import{dirname as pe,join as G}from"node:path";import{ensureLoopbackProxyBypass as tt,isHubProtocolCompatible as nt}from"@cerebriline/shared";import{resolveClineDataDir as H,resolveClineDir as eo}from"@cerebriline/shared/storage";var ot="CLINE_HUB_DISCOVERY_PATH",rt="CLINE_HUB_BUILD_ID",it="CLINE_HUB_BUILD_EPOCH_MS",st=30000,at=15000,ae=100;function ct(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ut(e){return Xe("sha256").update(e).digest("hex").slice(0,12)}function dt(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 ce(e){return new Promise((t)=>setTimeout(t,e))}function lt(e){return`${e}.lock`}async function pt(e){try{let t=JSON.parse(await le(G(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 W(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[rt]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(P.version)}`}function ft(){let e=Number(process.env[it]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792737149862)?1792737149862:void 0}function x(e,t=k()){let n=nt(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ue(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function de(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function mt(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function fe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ue(e.buildEpochMs),i=ue(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let s=de(e.coreVersion),u=de(t.coreVersion);if(s&&u){let c=mt(s,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function me(){return{buildId:k(),buildEpochMs:ft(),coreVersion:String(P.version)}}function D(e,t){let n=t?.self??me(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return fe(n,e)<=0}function he(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${ut(e)}`,n=process.env[ot]?.trim()||G(H(),"locks","hub","owners",`${ct(t)}.json`);return{ownerId:t,discoveryPath:n}}async function b(e){try{let t=JSON.parse(await le(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function ge(e,t,n){await q(e,async()=>{let o=pe(e);await j(o,{recursive:!0});let r=`${e}.${process.pid}.${Ze(6).toString("hex")}.tmp`,i;try{i=await se(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
2
2
  `,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,n?.beforePublish?.(),await Qe(r,e);let s;try{s=await se(o,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await I(r,{force:!0}).catch(()=>{return}),s}})}async function C(e){await q(e,async()=>{await I(e,{force:!0}).catch(()=>{return})})}async function be(e,t){return await q(e,async()=>{if((await b(e))?.hubId!==t)return!1;return await I(e,{force:!0}),!0})}async function ye(e,t,n){let o=lt(e);await j(pe(o),{recursive:!0});let r=Date.now()+at;while(!0){try{await j(o,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let u=await pt(o);if(!u){if(Date.now()>=r){await W(o);continue}await ce(ae);continue}let c=Date.now()-Date.parse(u.acquiredAt);if(!dt(u.pid)||c>st){await W(o);continue}if(Date.now()>=r)throw Error(`Timed out waiting for hub ${t} lock ${o}`);await ce(ae);continue}try{return await et(G(o,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
3
  `,"utf8"),await n()}finally{await W(o)}}}function q(e,t){return ye(`${e}.mutation`,"discovery mutation",t)}function we(e,t){return ye(e,"startup",t)}async function A(e,t){tt();try{let n=await fetch(t?.authToken?ht(e):Se(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let o=await n.json();if(typeof o.protocolVersion!=="string"||typeof o.host!=="string"||typeof o.port!=="number"||typeof o.url!=="string")return;return{protocolVersion:o.protocolVersion,minClientProtocolVersion:typeof o.minClientProtocolVersion==="string"?o.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof o.maxClientProtocolVersion==="string"?o.maxClientProtocolVersion:void 0,capabilities:Array.isArray(o.capabilities)?o.capabilities.filter((r)=>typeof r==="string"):void 0,coreVersion:typeof o.coreVersion==="string"?o.coreVersion:void 0,buildId:typeof o.buildId==="string"?o.buildId:void 0,buildEpochMs:typeof o.buildEpochMs==="number"?o.buildEpochMs:void 0,host:o.host,port:o.port,url:o.url,hubId:typeof o.hubId==="string"?o.hubId:void 0,authToken:typeof o.authToken==="string"?o.authToken:void 0,pid:typeof o.pid==="number"?o.pid:void 0,startedAt:typeof o.startedAt==="string"?o.startedAt:void 0,updatedAt:typeof o.updatedAt==="string"?o.updatedAt:void 0}}catch{return}}function ve(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Se(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function ht(e){let t=new URL(Se(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as gt,CLINE_HUB_PORT as bt,resolveClineBuildEnv as yt}from"@cerebriline/shared";var wt="CLINE_HUB_HOST",vt="CLINE_HUB_PORT",St="CLINE_HUB_PATHNAME",kt="127.0.0.1",Ct=bt,Pt="/hub";function ke(e){return yt(e)==="development"?gt:Ct}function Ht(e={}){return(e.env??process.env)[wt]?.trim()||kt}function _t(e={}){let n=(e.env??process.env)[vt]?.trim();if(!n)return ke(e);let o=Number.parseInt(n,10);if(!Number.isInteger(o)||o<1||o>65535)return ke(e);return o}function Rt(e={}){return(e.env??process.env)[St]?.trim()||Pt}function Ce(e={},t={}){return{host:e.host??Ht(t),port:e.port??_t(t),pathname:e.pathname??Rt(t)}}import{join as It}from"node:path";import{execFile as Tt}from"node:child_process";import{promisify as Et}from"node:util";import{processWorkspaceInfo as co}from"@cerebriline/shared";import lo from"simple-git";var po=Et(Tt);var xt="shared:cline",Dt="CLINE_HUB_DISCOVERY_PATH",At="hub-production";function _(e=xt){return he(`${e}@${k()}`)}function O(){return{ownerId:At,discoveryPath:process.env[Dt]?.trim()||It(H(),"locks","hub","production.json")}}var Pe=15000,Jt=200,He=3000,zt=100,Yt=[100,250,500,1000,2000],Xt="--cline-hub-daemon",Zt=3,Qt=60000,_e=new Map;function en(e,t=Date.now()){let n=_e.get(e);if(!n||t-n.windowStartedAt>Qt)return _e.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Zt}function tn(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function nn(){try{let e=Wt(H(),"logs","hub-daemon.log");return Ut(Ft(e),{recursive:!0}),{fd:Mt(e,"a"),logPath:e}}catch{return}}function on(){return Ee()==="production"?O():_()}function R(e){return D(e)}function rn(e){try{let t=JSON.parse(Bt(`${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 K(e){try{Nt(`${e}.superseded`)}catch{}}function Re(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function T(e,t){try{return await A(e,{authToken:t})}catch{return}}async function Te(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await T(e))?.url)return!0;await new Promise((r)=>setTimeout(r,zt))}return!1}async function z(e,t){if(!en(e.url))return!1;await E(e.url,e.authToken,"retired by newer install").catch(()=>!1),await M(e.url,e.authToken).catch(()=>!1);let n=await Te(e.url,He);if(!n&&e.pid&&sn(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Te(e.url,He)}if(n)await C(t).catch(()=>{return});return n}function sn(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function an(e){try{return(await Y(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function J(e,t){if(R(e))return"reusable";let n=await E(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await an(e)){if(n)await E(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let o=await z(e,t);if(!o&&n)await E(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return o?"retired":"failed"}async function cn(e){if(Ee()!=="production")return;let t=_();if(t.discoveryPath===e.discoveryPath)return;let n=await b(t.discoveryPath);if(n?.url)await z(n,t.discoveryPath);else await C(t.discoveryPath).catch(()=>{return})}function un(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return $t(new URL(`./entry.${e}`,import.meta.url))}function dn(e,t){if(Gt(e))return[Xt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function ln(e,t){let n=un(),o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let r=Vt(o).toLowerCase().includes("bun"),i=dn(n,r);return{launcher:o,args:[...i,"--cwd",e,...tn(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...Kt(process.env),CLINE_NO_INTERACTIVE:"1",[jt]:"1"}}}function pn(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 fn(e,t={}){if(qt())return;let n=ln(e,t),o=nn();try{Ot(n.launcher,n.args,{detached:!0,stdio:o?["ignore",o.fd,o.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(o)Lt(o.fd)}}async function mn(e,t={}){for(let n=0;;n++)try{fn(e,t);return}catch(o){let r=Yt[n];if(!pn(o)||r===void 0)throw o;await new Promise((i)=>setTimeout(i,r))}}async function hn(e,t,n={}){let o=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),r=Ce(n),i=ve(r.host,r.port,r.pathname),s=(l)=>{if(!o)U(l.url,l.authToken);else Ie(l.url,l.authToken);return l};await cn(e).catch(()=>{return});let u=await b(e.discoveryPath),c=u?.url?void 0:rn(e.discoveryPath),d=!1;if(u?.url){let l=u.authToken;if(!l)d=!0,await z(u,e.discoveryPath);else{let p=await T(u.url,l);if(p?.url&&R(p)&&await y(p.url,{authToken:l}))return K(e.discoveryPath),s({url:p.url,authToken:l});if(p?.url){if(await J({...p,authToken:l},e.discoveryPath)==="deferred_busy"&&await y(p.url,{authToken:l}))return s({url:p.url,authToken:l})}else await C(e.discoveryPath).catch(()=>{return})}}let a=await T(i);if(a?.url){let l=Re(a,u??c,i);if(R(a)){let h=[a.authToken,u?.authToken,c?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0);for(let S of h){if(!await y(a.url,{authToken:S}))continue;let ze={hubId:a.hubId??`repaired-${a.port}`,protocolVersion:a.protocolVersion,minClientProtocolVersion:a.minClientProtocolVersion,maxClientProtocolVersion:a.maxClientProtocolVersion,capabilities:a.capabilities,coreVersion:a.coreVersion,buildId:a.buildId,authToken:S,host:a.host,port:a.port,url:a.url,pid:a.pid??u?.pid??c?.pid,startedAt:a.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await ge(e.discoveryPath,ze)}catch{}return K(e.discoveryPath),s({url:a.url,authToken:S})}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.${d?" 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 p=await J(l,e.discoveryPath);if(p==="deferred_busy"){for(let h of[l.authToken,u?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0))if(await y(a.url,{authToken:h}))return s({url:a.url,authToken:h});if(n.allowPortFallback!==!0&&r.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(p==="failed"&&n.allowPortFallback!==!0&&r.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 g=n.allowPortFallback===!0&&r.port!==0?{...r,port:0}:r;await mn(t,{...g,manageConnectors:n.manageConnectors});let w=Date.now()+Pe;while(Date.now()<w){let l=await b(e.discoveryPath);if(l?.url&&l.authToken){let h=await T(l.url,l.authToken);if(h?.url&&R(h)&&await y(h.url,{authToken:l.authToken}))return K(e.discoveryPath),s({url:h.url,authToken:l.authToken})}let p=await T(i);if(p?.url&&!R(p)){let h=Re(p,l??c,i),v=await J(h,e.discoveryPath);if(v==="deferred_busy"&&l?.authToken&&await y(p.url,{authToken:l.authToken}))return s({url:p.url,authToken:l.authToken});if(v==="failed"&&n.allowPortFallback!==!0&&r.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((h)=>setTimeout(h,Jt))}throw Error(`Timed out after ${Pe}ms waiting for detached hub startup.`)}async function L(e,t={}){let n=on();return await we(n.discoveryPath,async()=>hn(n,e,t))}function Sn(){return yn()==="production"?O():_()}function kn(){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 Me(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 Me(e.data);return String(e)}function Cn(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 xe(e){let t=e,n=Cn(t.reason);return new f("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Z,{closeCode:t.code,closeReason:n||void 0})}function De(e,t){if(e instanceof f)return e;if(e instanceof Error)return new f("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new f("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 f("hub_connect_failed",n);let o=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new f("hub_connect_failed",o?`Failed to connect to hub at ${t.toString()} (${o} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var X="*",B=8000,Pn="cline-hub-auth.",te=new Map,Be=new Set,Hn=3000;var Z="Hub connection closed",_n=250,Rn=5000,Ae=0.5;class f extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Tn(e){return e instanceof f}class Q extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function ne(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let o=N(e.toString());return o?te.get(o):void 0}function En(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 N(e){if(!En(e))return;let t=new URL(Ne(e));return t.search="",t.hash="",t.toString()}function Oe(e){let t=N(e);return!!t&&Be.has(t)}function U(e,t){let n=N(e);if(n){if(Be.add(n),t?.trim())te.set(n,t)}return e}function Ie(e,t){let n=N(e);if(n&&t?.trim())te.set(n,t)}class oe{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 f("hub_connection_closed",Z);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()||ne(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,o=this.openSocket(e,t,n),r;this.connectPromise=o.then(async(s)=>{if(r=s,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(P.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{s.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let u of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(u));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(s){if(this.connectPromise===i)this.connectPromise=void 0;if(r&&this.socket===r){this.lastCloseError=De(s,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{r.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw s}}async openSocket(e,t,n){let o=this.options.resolveConnectionHeaders,r;if(o){let c;try{r=await Promise.race([Promise.resolve().then(()=>o()),new Promise((d,a)=>{c=setTimeout(()=>{a(new f("hub_connect_timeout",`Timed out resolving hub connection headers after ${B}ms`))},B)})])}catch(d){let a=d instanceof f?d:new f("hub_connect_failed",d instanceof Error?d.message:String(d));if(n===this.connectGeneration)this.lastCloseError=a;throw a}finally{clearTimeout(c)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(r&&Object.keys(r).some((c)=>c.toLowerCase()==="sec-websocket-protocol")){let c=new f("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=c;throw c}let i=r?new vn(e.toString(),{headers:{...r}}):new(kn())(e.toString(),t?[`${Pn}${t}`]:void 0);this.socket=i;let s=!1,u=new Promise((c,d)=>{let a=!1,m=setTimeout(()=>{if(a)return;a=!0,s=!0;let g=new f("hub_connect_timeout",`Timed out connecting to hub after ${B}ms`);if(this.socket===i)this.lastCloseError=g,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}d(g)},B);i.addEventListener("open",()=>{if(a)return;a=!0,clearTimeout(m),c()}),i.addEventListener("error",(g)=>{if(a)return;a=!0,clearTimeout(m);let w=De(g,e);if(this.socket===i)this.lastCloseError=w,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;d(w)}),i.addEventListener("close",(g)=>{if(a)return;a=!0,clearTimeout(m);let w=s?this.lastCloseError:xe(g);if(this.socket===i){if(!s)this.lastCloseError=w,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}d(w)})});return i.addEventListener("message",(c)=>{this.handleFrame(JSON.parse(Me(c)))}),i.addEventListener("close",(c)=>{if(this.socket!==i)return;if(!s)this.lastCloseError=xe(c),this.sawSocketClose=!0;this.registered=!1;for(let d of this.pendingReplies.values())d.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await u,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,o={listener:e,sessionId:n};return this.listeners.add(o),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(o))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,o){let r=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,o)}catch(s){if(!i||r>=1||!await this.recoverLocalHubTransport(s))throw s;r+=1}}async commandOnce(e,t,n,o,r=!0){if(r)await this.connect();o?.beforeDispatch?.();let i=gn("hubreq_");o?.onDispatch?.(i);let s=wn(e,o?.timeoutMs),u=new Promise((d,a)=>{let m=s===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;a(new Q(e,"hub_command_timeout",`Hub command ${e} timed out after ${s}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.`))},s);this.pendingReplies.set(i,{resolve:(g)=>{if(m)clearTimeout(m);d(g)},reject:(g)=>{if(m)clearTimeout(m);a(g)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:s,payload:t}})}catch(d){throw this.pendingReplies.delete(i),d}let c=await u;if(!c.ok){if(c.error?.code===ie){let d=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new F(d,c.error.message)}throw new Q(e,c.error?.code,c.error?.message??`Hub command ${e} failed`)}return c}async recoverLocalHubTransport(e){if(!Oe(this.currentUrl)||!Tn(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Le({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(_n*2**this.reconnectAttempt,Rn),t=Math.round(e*(1-Ae)+Math.random()*e*Ae);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(!Oe(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Le({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 f("hub_connection_closed",Z);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 f("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),o=(this.subscriptionCounts.get(n)??0)+t;if(o<=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,o),t>0&&o===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??X}subscriptionSessionIdFromKey(e){return e===X?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 o of[X,n]){if(!o||!this.subscriptionCounts.has(o))continue;let r=this.lastEventSequenceByKey.get(o)??0;if(t>r)this.lastEventSequenceByKey.set(o,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 Ne(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 y(e,t){let n=new oe({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 ee(e,t){let n=Ne(e),o=await A(n,{authToken:t?.authToken});if(!o)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let r=k(),i=x(o,r);if(!i.compatible&&!D(o))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!bn(o).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await y(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function In(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,o=new Set;for(let r of t){if(!r||typeof r!=="object")continue;let i=r.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let s of i){let u=s&&typeof s==="object"?s.clientId:void 0;if(typeof u==="string"&&u.trim())o.add(u)}}return{activeSessionCount:n,participantClientCount:o.size}}async function Y(e,t,n){let o=new oe({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let r=await o.command("session.list",{limit:500},void 0,{timeoutMs:Hn});return In(r.payload)}finally{await o.dispose().catch(()=>{return})}}async function xn(e,t,n){try{return(await Y(e,t,n)).activeSessionCount===0}catch{return!1}}async function Dn(e,t){let n=`${e.discoveryPath}.superseded`,o=await b(n);if(!o?.url||!o.authToken)return;let r=await ee(o.url,{authToken:o.authToken});if(r.status!=="compatible")return;if(await xn(r.url,o.authToken,t))return;return U(r.url,o.authToken)}async function An(e={}){if(e.endpoint?.trim()){let r=await ee(e.endpoint);return r.status==="compatible"?r.url:void 0}let t=Sn(),n=await b(t.discoveryPath);if(!n?.url)return await Dn(t,e);let o=await ee(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(o.status==="compatible")return U(o.url,n.authToken);if(o.status==="protocol_mismatch")await C(t.discoveryPath).catch(()=>{return});return}async function Le(e={}){let t=await An(e);if(t&&await y(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await L(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function E(e,t,n,o){Ue();let r=new URL(e),i=t?.trim()||ne(r);if(r.protocol==="ws:")r.protocol="http:";else if(r.protocol==="wss:")r.protocol="https:";if(r.pathname="/drain",r.hash="",n)r.searchParams.set("reason",n);if(o?.off)r.searchParams.set("off","1");return(await fetch(r,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function M(e,t){Ue();let n=new URL(e),o=t?.trim()||ne(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:o?{authorization:`Bearer ${o}`}:void 0})).ok}import{spawn as On}from"node:child_process";import{userInfo as Ln}from"node:os";import{basename as Un,delimiter as V}from"node:path";var re="__CLINE_SIDECAR_PATH_START__",Fe="__CLINE_SIDECAR_PATH_END__",We=5000,Mn=`/bin/sh -c 'printf "%s%s%s" "${re}" "$PATH" "${Fe}"'`,Ve="CLINE_SIDECAR_SKIP_SHELL_PATH";function $e(e){return e==="darwin"?"/bin/zsh":"/bin/bash"}function Bn(e,t){try{let n=Ln().shell?.trim();if(n)return n}catch{}return t.SHELL?.trim()||$e(e)}function Nn(e,t){let n=Un(e);if(n==="csh"||n==="tcsh")return{args:["-c",t],argv0:`-${n}`};return{args:["-i","-l","-c",t]}}function Vn(e){let t=e.indexOf(re);if(t===-1)return;let n=e.indexOf(Fe,t);if(n===-1)return;let o=e.slice(t+re.length,n).trim();return o.length>0?o:void 0}function Fn(e,t){let n=[...e.split(V),...t.split(V)].map((o)=>o.trim()).filter((o)=>o.length>0);return Array.from(new Set(n)).join(V)}function Wn(e,t=We){return new Promise((n)=>{let o=Nn(e,Mn),r=On(e,o.args,{argv0:o.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),i="",s=0,u=()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}},c=!1,d=(m)=>{if(c)return;c=!0,clearTimeout(a),r.stdout?.destroy(),u(),n(m)},a=setTimeout(()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}d(void 0)},t);r.stdout?.on("data",(m)=>{if(c)return;if(s+=m.length,s>65536){d(void 0);return}i+=m.toString("utf8")}),r.on("error",()=>d(void 0)),r.on("close",()=>d(Vn(i)))})}async function je(e){let t=e?.platform??process.platform,n=e?.env??process.env;if(t==="win32")return{status:"skipped",reason:"windows"};if(n[Ve]?.trim())return{status:"skipped",reason:Ve};let o=e?.userShell??Bn(t,n),r=e?.fallbackShell??$e(t),i=e?.timeoutMs??We,s=o===r?[[o,i]]:[[o,i],[r,i/2]];for(let[u,c]of s){let d=await Wn(u,c);if(!d)continue;let a=Fn(d,n.PATH??"");return n.PATH=a,{status:"applied",pathEntries:a.split(V).length,shell:u}}return{status:"failed",shell:o}}var Ge={readHubDiscovery:b,clearHubDiscoveryIfOwned:be,probeProcess:(e)=>{process.kill(e,0)},requestHubShutdown:M,ensureDetachedHubServer:L,claimHubDaemonProcess:jn,loadHubDaemon:()=>import("@cerebriline/core/hub/daemon-entry"),ensureLoginShellPath:je,setHomeDirIfUnset:Gn,homeDir:$n,cwd:()=>process.cwd(),env:process.env,writeOutput:(e)=>process.stdout.write(e)};function qe(e,t){let n=e.indexOf(t);return(n>=0?e[n+1]:void 0)?.trim()||void 0}function Ke(e,t){let n=qe(e,"--discovery-path");if(!n)throw Error("--discovery-path is required for remote Hub management");return t.env.CLINE_HUB_DISCOVERY_PATH=n,n}async function qn(e=process.argv,t=Ge){t.setHomeDirIfUnset(t.homeDir()),await t.ensureLoginShellPath();let n=qe(e,"--cwd")??t.cwd();Ke(e,t);let o=await t.ensureDetachedHubServer(n,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});t.writeOutput(`${JSON.stringify({...o,cwd:n,platform:process.platform,arch:process.arch})}
4
4
  `)}async function Je(e=process.argv,t=Ge){if(e.includes("--remote-hub-stop")){let n=Ke(e,t),o=await t.readHubDiscovery(n);if(o&&typeof o.pid==="number"&&Number.isInteger(o.pid)&&o.pid>0)try{t.probeProcess(o.pid)}catch(r){if(r?.code==="ESRCH")return await t.clearHubDiscoveryIfOwned(n,o.hubId),!0}if(o&&!await t.requestHubShutdown(o.url,o.authToken))throw Error("Remote Hub shutdown failed");return!0}if(e.includes("--remote-hub-ensure"))return await qn(e,t),!0;if(t.claimHubDaemonProcess())return await t.loadHubDaemon(),!0;return!1}(async()=>{if(!await Je())throw Error("A remote helper command is required")})().catch((e)=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
@@ -1,4 +1,4 @@
1
- import{homedir as Wn}from"node:os";import{claimHubDaemonProcess as $n}from"@cerebriline/shared";import{setHomeDirIfUnset as jn}from"@cerebriline/shared/storage";import{createSessionId as hn,ensureLoopbackProxyBypass as Ue,isHubProtocolCompatible as gn,resolveClineBuildEnv as bn,resolveHubCommandTimeoutMs as yn}from"@cerebriline/shared";import wn from"ws";var P={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var ie="session_not_found";class F 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"}}import{spawn as At}from"node:child_process";import{closeSync as Ot,mkdirSync as Lt,openSync as Ut,readFileSync as Mt,unlinkSync as Bt}from"node:fs";import{basename as Nt,dirname as Vt,join as Ft}from"node:path";import{fileURLToPath as Wt}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as $t,isBunEmbeddedModulePath as jt,isHubDaemonProcess as Gt,resolveClineBuildEnv as Ee,withResolvedClineBuildEnv as qt}from"@cerebriline/shared";import{createHash as Ye,randomBytes as Xe}from"node:crypto";import{mkdir as j,open as se,readFile as le,rename as Ze,rm as I,writeFile as Qe}from"node:fs/promises";import{dirname as pe,join as G}from"node:path";import{ensureLoopbackProxyBypass as et,isHubProtocolCompatible as tt}from"@cerebriline/shared";import{resolveClineDataDir as H,resolveClineDir as Qn}from"@cerebriline/shared/storage";var nt="CLINE_HUB_DISCOVERY_PATH",ot="CLINE_HUB_BUILD_ID",rt="CLINE_HUB_BUILD_EPOCH_MS",it=30000,st=15000,ae=100;function at(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ct(e){return Ye("sha256").update(e).digest("hex").slice(0,12)}function ut(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 ce(e){return new Promise((t)=>setTimeout(t,e))}function dt(e){return`${e}.lock`}async function lt(e){try{let t=JSON.parse(await le(G(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 W(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[ot]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(P.version)}`}function pt(){let e=Number(process.env[rt]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792707017870)?1792707017870:void 0}function x(e,t=k()){let n=tt(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ue(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function de(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function ft(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function fe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ue(e.buildEpochMs),i=ue(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let s=de(e.coreVersion),u=de(t.coreVersion);if(s&&u){let c=ft(s,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function me(){return{buildId:k(),buildEpochMs:pt(),coreVersion:String(P.version)}}function D(e,t){let n=t?.self??me(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return fe(n,e)<=0}function he(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${ct(e)}`,n=process.env[nt]?.trim()||G(H(),"locks","hub","owners",`${at(t)}.json`);return{ownerId:t,discoveryPath:n}}async function b(e){try{let t=JSON.parse(await le(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function ge(e,t,n){await q(e,async()=>{let o=pe(e);await j(o,{recursive:!0});let r=`${e}.${process.pid}.${Xe(6).toString("hex")}.tmp`,i;try{i=await se(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
1
+ import{homedir as Wn}from"node:os";import{claimHubDaemonProcess as $n}from"@cerebriline/shared";import{setHomeDirIfUnset as jn}from"@cerebriline/shared/storage";import{createSessionId as hn,ensureLoopbackProxyBypass as Ue,isHubProtocolCompatible as gn,resolveClineBuildEnv as bn,resolveHubCommandTimeoutMs as yn}from"@cerebriline/shared";import wn from"ws";var P={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@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","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.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/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var ie="session_not_found";class F 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"}}import{spawn as At}from"node:child_process";import{closeSync as Ot,mkdirSync as Lt,openSync as Ut,readFileSync as Mt,unlinkSync as Bt}from"node:fs";import{basename as Nt,dirname as Vt,join as Ft}from"node:path";import{fileURLToPath as Wt}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as $t,isBunEmbeddedModulePath as jt,isHubDaemonProcess as Gt,resolveClineBuildEnv as Ee,withResolvedClineBuildEnv as qt}from"@cerebriline/shared";import{createHash as Ye,randomBytes as Xe}from"node:crypto";import{mkdir as j,open as se,readFile as le,rename as Ze,rm as I,writeFile as Qe}from"node:fs/promises";import{dirname as pe,join as G}from"node:path";import{ensureLoopbackProxyBypass as et,isHubProtocolCompatible as tt}from"@cerebriline/shared";import{resolveClineDataDir as H,resolveClineDir as Qn}from"@cerebriline/shared/storage";var nt="CLINE_HUB_DISCOVERY_PATH",ot="CLINE_HUB_BUILD_ID",rt="CLINE_HUB_BUILD_EPOCH_MS",it=30000,st=15000,ae=100;function at(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ct(e){return Ye("sha256").update(e).digest("hex").slice(0,12)}function ut(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 ce(e){return new Promise((t)=>setTimeout(t,e))}function dt(e){return`${e}.lock`}async function lt(e){try{let t=JSON.parse(await le(G(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 W(e){await I(e,{recursive:!0,force:!0}).catch(()=>{return})}function k(){let e=process.env[ot]?.trim();if(e)return e;return"sdk-v1-6166d6cf6d2beb7cf553070843db7e6683db113044e66b110ebdef39dac18ba3".trim()||`source-${String(P.version)}`}function pt(){let e=Number(process.env[rt]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792737149862)?1792737149862:void 0}function x(e,t=k()){let n=tt(e);if(!n.compatible)return n;let o=e.buildId?.trim();if(!o)return{compatible:!1,reason:"missing_build"};if(o!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ue(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function de(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((o)=>Number(o));if(n.length===0||n.some((o)=>!Number.isInteger(o)||o<0))return;return n}function ft(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]??0,r=t[n]??0;if(o!==r)return o<r?-1:1}return 0}function fe(e,t){let n=e.buildId?.trim(),o=t.buildId?.trim();if(n&&o&&n===o)return 0;let r=ue(e.buildEpochMs),i=ue(t.buildEpochMs);if(r!==void 0&&i!==void 0&&r!==i)return r<i?-1:1;let s=de(e.coreVersion),u=de(t.coreVersion);if(s&&u){let c=ft(s,u);if(c!==0)return c}if(n&&o&&n!==o)return n<o?-1:1;return 0}function me(){return{buildId:k(),buildEpochMs:pt(),coreVersion:String(P.version)}}function D(e,t){let n=t?.self??me(),o=x(e,n.buildId??"");if(o.compatible)return!0;if(o.reason!=="build_mismatch"&&o.reason!=="missing_build")return!1;return fe(n,e)<=0}function he(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${ct(e)}`,n=process.env[nt]?.trim()||G(H(),"locks","hub","owners",`${at(t)}.json`);return{ownerId:t,discoveryPath:n}}async function b(e){try{let t=JSON.parse(await le(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function ge(e,t,n){await q(e,async()=>{let o=pe(e);await j(o,{recursive:!0});let r=`${e}.${process.pid}.${Xe(6).toString("hex")}.tmp`,i;try{i=await se(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
2
2
  `,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,n?.beforePublish?.(),await Ze(r,e);let s;try{s=await se(o,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await I(r,{force:!0}).catch(()=>{return}),s}})}async function C(e){await q(e,async()=>{await I(e,{force:!0}).catch(()=>{return})})}async function be(e,t){return await q(e,async()=>{if((await b(e))?.hubId!==t)return!1;return await I(e,{force:!0}),!0})}async function ye(e,t,n){let o=dt(e);await j(pe(o),{recursive:!0});let r=Date.now()+st;while(!0){try{await j(o,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let u=await lt(o);if(!u){if(Date.now()>=r){await W(o);continue}await ce(ae);continue}let c=Date.now()-Date.parse(u.acquiredAt);if(!ut(u.pid)||c>it){await W(o);continue}if(Date.now()>=r)throw Error(`Timed out waiting for hub ${t} lock ${o}`);await ce(ae);continue}try{return await Qe(G(o,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
3
3
  `,"utf8"),await n()}finally{await W(o)}}}function q(e,t){return ye(`${e}.mutation`,"discovery mutation",t)}function we(e,t){return ye(e,"startup",t)}async function A(e,t){et();try{let n=await fetch(t?.authToken?mt(e):Se(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let o=await n.json();if(typeof o.protocolVersion!=="string"||typeof o.host!=="string"||typeof o.port!=="number"||typeof o.url!=="string")return;return{protocolVersion:o.protocolVersion,minClientProtocolVersion:typeof o.minClientProtocolVersion==="string"?o.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof o.maxClientProtocolVersion==="string"?o.maxClientProtocolVersion:void 0,capabilities:Array.isArray(o.capabilities)?o.capabilities.filter((r)=>typeof r==="string"):void 0,coreVersion:typeof o.coreVersion==="string"?o.coreVersion:void 0,buildId:typeof o.buildId==="string"?o.buildId:void 0,buildEpochMs:typeof o.buildEpochMs==="number"?o.buildEpochMs:void 0,host:o.host,port:o.port,url:o.url,hubId:typeof o.hubId==="string"?o.hubId:void 0,authToken:typeof o.authToken==="string"?o.authToken:void 0,pid:typeof o.pid==="number"?o.pid:void 0,startedAt:typeof o.startedAt==="string"?o.startedAt:void 0,updatedAt:typeof o.updatedAt==="string"?o.updatedAt:void 0}}catch{return}}function ve(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function Se(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function mt(e){let t=new URL(Se(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as ht,CLINE_HUB_PORT as gt,resolveClineBuildEnv as bt}from"@cerebriline/shared";var yt="CLINE_HUB_HOST",wt="CLINE_HUB_PORT",vt="CLINE_HUB_PATHNAME",St="127.0.0.1",kt=gt,Ct="/hub";function ke(e){return bt(e)==="development"?ht:kt}function Pt(e={}){return(e.env??process.env)[yt]?.trim()||St}function Ht(e={}){let n=(e.env??process.env)[wt]?.trim();if(!n)return ke(e);let o=Number.parseInt(n,10);if(!Number.isInteger(o)||o<1||o>65535)return ke(e);return o}function _t(e={}){return(e.env??process.env)[vt]?.trim()||Ct}function Ce(e={},t={}){return{host:e.host??Pt(t),port:e.port??Ht(t),pathname:e.pathname??_t(t)}}import{join as Et}from"node:path";import{execFile as Rt}from"node:child_process";import{promisify as Tt}from"node:util";import{processWorkspaceInfo as ao}from"@cerebriline/shared";import uo from"simple-git";var lo=Tt(Rt);var It="shared:cline",xt="CLINE_HUB_DISCOVERY_PATH",Dt="hub-production";function _(e=It){return he(`${e}@${k()}`)}function O(){return{ownerId:Dt,discoveryPath:process.env[xt]?.trim()||Et(H(),"locks","hub","production.json")}}var Pe=15000,Kt=200,He=3000,Jt=100,zt=[100,250,500,1000,2000],Yt="--cline-hub-daemon",Xt=3,Zt=60000,_e=new Map;function Qt(e,t=Date.now()){let n=_e.get(e);if(!n||t-n.windowStartedAt>Zt)return _e.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Xt}function en(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function tn(){try{let e=Ft(H(),"logs","hub-daemon.log");return Lt(Vt(e),{recursive:!0}),{fd:Ut(e,"a"),logPath:e}}catch{return}}function nn(){return Ee()==="production"?O():_()}function R(e){return D(e)}function on(e){try{let t=JSON.parse(Mt(`${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 K(e){try{Bt(`${e}.superseded`)}catch{}}function Re(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function T(e,t){try{return await A(e,{authToken:t})}catch{return}}async function Te(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await T(e))?.url)return!0;await new Promise((r)=>setTimeout(r,Jt))}return!1}async function z(e,t){if(!Qt(e.url))return!1;await E(e.url,e.authToken,"retired by newer install").catch(()=>!1),await M(e.url,e.authToken).catch(()=>!1);let n=await Te(e.url,He);if(!n&&e.pid&&rn(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await Te(e.url,He)}if(n)await C(t).catch(()=>{return});return n}function rn(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function sn(e){try{return(await Y(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function J(e,t){if(R(e))return"reusable";let n=await E(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await sn(e)){if(n)await E(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let o=await z(e,t);if(!o&&n)await E(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return o?"retired":"failed"}async function an(e){if(Ee()!=="production")return;let t=_();if(t.discoveryPath===e.discoveryPath)return;let n=await b(t.discoveryPath);if(n?.url)await z(n,t.discoveryPath);else await C(t.discoveryPath).catch(()=>{return})}function cn(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return Wt(new URL(`./entry.${e}`,import.meta.url))}function un(e,t){if(jt(e))return[Yt];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function dn(e,t){let n=cn(),o=process.execPath?.trim();if(!o)throw Error("unable to resolve runtime executable for hub daemon");let r=Nt(o).toLowerCase().includes("bun"),i=un(n,r);return{launcher:o,args:[...i,"--cwd",e,...en(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...qt(process.env),CLINE_NO_INTERACTIVE:"1",[$t]:"1"}}}function ln(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 pn(e,t={}){if(Gt())return;let n=dn(e,t),o=tn();try{At(n.launcher,n.args,{detached:!0,stdio:o?["ignore",o.fd,o.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(o)Ot(o.fd)}}async function fn(e,t={}){for(let n=0;;n++)try{pn(e,t);return}catch(o){let r=zt[n];if(!ln(o)||r===void 0)throw o;await new Promise((i)=>setTimeout(i,r))}}async function mn(e,t,n={}){let o=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),r=Ce(n),i=ve(r.host,r.port,r.pathname),s=(l)=>{if(!o)U(l.url,l.authToken);else Ie(l.url,l.authToken);return l};await an(e).catch(()=>{return});let u=await b(e.discoveryPath),c=u?.url?void 0:on(e.discoveryPath),d=!1;if(u?.url){let l=u.authToken;if(!l)d=!0,await z(u,e.discoveryPath);else{let p=await T(u.url,l);if(p?.url&&R(p)&&await y(p.url,{authToken:l}))return K(e.discoveryPath),s({url:p.url,authToken:l});if(p?.url){if(await J({...p,authToken:l},e.discoveryPath)==="deferred_busy"&&await y(p.url,{authToken:l}))return s({url:p.url,authToken:l})}else await C(e.discoveryPath).catch(()=>{return})}}let a=await T(i);if(a?.url){let l=Re(a,u??c,i);if(R(a)){let h=[a.authToken,u?.authToken,c?.authToken].filter((S)=>typeof S==="string"&&S.trim().length>0);for(let S of h){if(!await y(a.url,{authToken:S}))continue;let Je={hubId:a.hubId??`repaired-${a.port}`,protocolVersion:a.protocolVersion,minClientProtocolVersion:a.minClientProtocolVersion,maxClientProtocolVersion:a.maxClientProtocolVersion,capabilities:a.capabilities,coreVersion:a.coreVersion,buildId:a.buildId,authToken:S,host:a.host,port:a.port,url:a.url,pid:a.pid??u?.pid??c?.pid,startedAt:a.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await ge(e.discoveryPath,Je)}catch{}return K(e.discoveryPath),s({url:a.url,authToken:S})}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.${d?" 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 p=await J(l,e.discoveryPath);if(p==="deferred_busy"){for(let h of[l.authToken,u?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0))if(await y(a.url,{authToken:h}))return s({url:a.url,authToken:h});if(n.allowPortFallback!==!0&&r.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(p==="failed"&&n.allowPortFallback!==!0&&r.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 g=n.allowPortFallback===!0&&r.port!==0?{...r,port:0}:r;await fn(t,{...g,manageConnectors:n.manageConnectors});let w=Date.now()+Pe;while(Date.now()<w){let l=await b(e.discoveryPath);if(l?.url&&l.authToken){let h=await T(l.url,l.authToken);if(h?.url&&R(h)&&await y(h.url,{authToken:l.authToken}))return K(e.discoveryPath),s({url:h.url,authToken:l.authToken})}let p=await T(i);if(p?.url&&!R(p)){let h=Re(p,l??c,i),v=await J(h,e.discoveryPath);if(v==="deferred_busy"&&l?.authToken&&await y(p.url,{authToken:l.authToken}))return s({url:p.url,authToken:l.authToken});if(v==="failed"&&n.allowPortFallback!==!0&&r.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((h)=>setTimeout(h,Kt))}throw Error(`Timed out after ${Pe}ms waiting for detached hub startup.`)}async function L(e,t={}){let n=nn();return await we(n.discoveryPath,async()=>mn(n,e,t))}function vn(){return bn()==="production"?O():_()}function Sn(){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 Me(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 Me(e.data);return String(e)}function kn(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 xe(e){let t=e,n=kn(t.reason);return new f("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Z,{closeCode:t.code,closeReason:n||void 0})}function De(e,t){if(e instanceof f)return e;if(e instanceof Error)return new f("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new f("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 f("hub_connect_failed",n);let o=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new f("hub_connect_failed",o?`Failed to connect to hub at ${t.toString()} (${o} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var X="*",B=8000,Cn="cline-hub-auth.",te=new Map,Be=new Set,Pn=3000;var Z="Hub connection closed",Hn=250,_n=5000,Ae=0.5;class f extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Rn(e){return e instanceof f}class Q extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function ne(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let o=N(e.toString());return o?te.get(o):void 0}function Tn(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 N(e){if(!Tn(e))return;let t=new URL(Ne(e));return t.search="",t.hash="",t.toString()}function Oe(e){let t=N(e);return!!t&&Be.has(t)}function U(e,t){let n=N(e);if(n){if(Be.add(n),t?.trim())te.set(n,t)}return e}function Ie(e,t){let n=N(e);if(n&&t?.trim())te.set(n,t)}class oe{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 f("hub_connection_closed",Z);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()||ne(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,o=this.openSocket(e,t,n),r;this.connectPromise=o.then(async(s)=>{if(r=s,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(P.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{s.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let u of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(u));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(s){if(this.connectPromise===i)this.connectPromise=void 0;if(r&&this.socket===r){this.lastCloseError=De(s,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{r.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw s}}async openSocket(e,t,n){let o=this.options.resolveConnectionHeaders,r;if(o){let c;try{r=await Promise.race([Promise.resolve().then(()=>o()),new Promise((d,a)=>{c=setTimeout(()=>{a(new f("hub_connect_timeout",`Timed out resolving hub connection headers after ${B}ms`))},B)})])}catch(d){let a=d instanceof f?d:new f("hub_connect_failed",d instanceof Error?d.message:String(d));if(n===this.connectGeneration)this.lastCloseError=a;throw a}finally{clearTimeout(c)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(r&&Object.keys(r).some((c)=>c.toLowerCase()==="sec-websocket-protocol")){let c=new f("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=c;throw c}let i=r?new wn(e.toString(),{headers:{...r}}):new(Sn())(e.toString(),t?[`${Cn}${t}`]:void 0);this.socket=i;let s=!1,u=new Promise((c,d)=>{let a=!1,m=setTimeout(()=>{if(a)return;a=!0,s=!0;let g=new f("hub_connect_timeout",`Timed out connecting to hub after ${B}ms`);if(this.socket===i)this.lastCloseError=g,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}d(g)},B);i.addEventListener("open",()=>{if(a)return;a=!0,clearTimeout(m),c()}),i.addEventListener("error",(g)=>{if(a)return;a=!0,clearTimeout(m);let w=De(g,e);if(this.socket===i)this.lastCloseError=w,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;d(w)}),i.addEventListener("close",(g)=>{if(a)return;a=!0,clearTimeout(m);let w=s?this.lastCloseError:xe(g);if(this.socket===i){if(!s)this.lastCloseError=w,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}d(w)})});return i.addEventListener("message",(c)=>{this.handleFrame(JSON.parse(Me(c)))}),i.addEventListener("close",(c)=>{if(this.socket!==i)return;if(!s)this.lastCloseError=xe(c),this.sawSocketClose=!0;this.registered=!1;for(let d of this.pendingReplies.values())d.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await u,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,o={listener:e,sessionId:n};return this.listeners.add(o),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(o))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,o){let r=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,o)}catch(s){if(!i||r>=1||!await this.recoverLocalHubTransport(s))throw s;r+=1}}async commandOnce(e,t,n,o,r=!0){if(r)await this.connect();o?.beforeDispatch?.();let i=hn("hubreq_");o?.onDispatch?.(i);let s=yn(e,o?.timeoutMs),u=new Promise((d,a)=>{let m=s===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;a(new Q(e,"hub_command_timeout",`Hub command ${e} timed out after ${s}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.`))},s);this.pendingReplies.set(i,{resolve:(g)=>{if(m)clearTimeout(m);d(g)},reject:(g)=>{if(m)clearTimeout(m);a(g)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:s,payload:t}})}catch(d){throw this.pendingReplies.delete(i),d}let c=await u;if(!c.ok){if(c.error?.code===ie){let d=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new F(d,c.error.message)}throw new Q(e,c.error?.code,c.error?.message??`Hub command ${e} failed`)}return c}async recoverLocalHubTransport(e){if(!Oe(this.currentUrl)||!Rn(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Le({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(Hn*2**this.reconnectAttempt,_n),t=Math.round(e*(1-Ae)+Math.random()*e*Ae);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(!Oe(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Le({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 f("hub_connection_closed",Z);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 f("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),o=(this.subscriptionCounts.get(n)??0)+t;if(o<=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,o),t>0&&o===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??X}subscriptionSessionIdFromKey(e){return e===X?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 o of[X,n]){if(!o||!this.subscriptionCounts.has(o))continue;let r=this.lastEventSequenceByKey.get(o)??0;if(t>r)this.lastEventSequenceByKey.set(o,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 Ne(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 y(e,t){let n=new oe({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 ee(e,t){let n=Ne(e),o=await A(n,{authToken:t?.authToken});if(!o)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let r=k(),i=x(o,r);if(!i.compatible&&!D(o))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!gn(o).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await y(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function En(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,o=new Set;for(let r of t){if(!r||typeof r!=="object")continue;let i=r.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let s of i){let u=s&&typeof s==="object"?s.clientId:void 0;if(typeof u==="string"&&u.trim())o.add(u)}}return{activeSessionCount:n,participantClientCount:o.size}}async function Y(e,t,n){let o=new oe({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let r=await o.command("session.list",{limit:500},void 0,{timeoutMs:Pn});return En(r.payload)}finally{await o.dispose().catch(()=>{return})}}async function In(e,t,n){try{return(await Y(e,t,n)).activeSessionCount===0}catch{return!1}}async function xn(e,t){let n=`${e.discoveryPath}.superseded`,o=await b(n);if(!o?.url||!o.authToken)return;let r=await ee(o.url,{authToken:o.authToken});if(r.status!=="compatible")return;if(await In(r.url,o.authToken,t))return;return U(r.url,o.authToken)}async function Dn(e={}){if(e.endpoint?.trim()){let r=await ee(e.endpoint);return r.status==="compatible"?r.url:void 0}let t=vn(),n=await b(t.discoveryPath);if(!n?.url)return await xn(t,e);let o=await ee(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(o.status==="compatible")return U(o.url,n.authToken);if(o.status==="protocol_mismatch")await C(t.discoveryPath).catch(()=>{return});return}async function Le(e={}){let t=await Dn(e);if(t&&await y(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await L(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function E(e,t,n,o){Ue();let r=new URL(e),i=t?.trim()||ne(r);if(r.protocol==="ws:")r.protocol="http:";else if(r.protocol==="wss:")r.protocol="https:";if(r.pathname="/drain",r.hash="",n)r.searchParams.set("reason",n);if(o?.off)r.searchParams.set("off","1");return(await fetch(r,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function M(e,t){Ue();let n=new URL(e),o=t?.trim()||ne(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:o?{authorization:`Bearer ${o}`}:void 0})).ok}import{spawn as An}from"node:child_process";import{userInfo as On}from"node:os";import{basename as Ln,delimiter as V}from"node:path";var re="__CLINE_SIDECAR_PATH_START__",Fe="__CLINE_SIDECAR_PATH_END__",We=5000,Un=`/bin/sh -c 'printf "%s%s%s" "${re}" "$PATH" "${Fe}"'`,Ve="CLINE_SIDECAR_SKIP_SHELL_PATH";function $e(e){return e==="darwin"?"/bin/zsh":"/bin/bash"}function Mn(e,t){try{let n=On().shell?.trim();if(n)return n}catch{}return t.SHELL?.trim()||$e(e)}function Bn(e,t){let n=Ln(e);if(n==="csh"||n==="tcsh")return{args:["-c",t],argv0:`-${n}`};return{args:["-i","-l","-c",t]}}function Nn(e){let t=e.indexOf(re);if(t===-1)return;let n=e.indexOf(Fe,t);if(n===-1)return;let o=e.slice(t+re.length,n).trim();return o.length>0?o:void 0}function Vn(e,t){let n=[...e.split(V),...t.split(V)].map((o)=>o.trim()).filter((o)=>o.length>0);return Array.from(new Set(n)).join(V)}function Fn(e,t=We){return new Promise((n)=>{let o=Bn(e,Un),r=An(e,o.args,{argv0:o.argv0,stdio:["ignore","pipe","ignore"],detached:!0}),i="",s=0,u=()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}},c=!1,d=(m)=>{if(c)return;c=!0,clearTimeout(a),r.stdout?.destroy(),u(),n(m)},a=setTimeout(()=>{try{if(r.pid)process.kill(-r.pid,"SIGKILL")}catch{r.kill("SIGKILL")}d(void 0)},t);r.stdout?.on("data",(m)=>{if(c)return;if(s+=m.length,s>65536){d(void 0);return}i+=m.toString("utf8")}),r.on("error",()=>d(void 0)),r.on("close",()=>d(Nn(i)))})}async function je(e){let t=e?.platform??process.platform,n=e?.env??process.env;if(t==="win32")return{status:"skipped",reason:"windows"};if(n[Ve]?.trim())return{status:"skipped",reason:Ve};let o=e?.userShell??Mn(t,n),r=e?.fallbackShell??$e(t),i=e?.timeoutMs??We,s=o===r?[[o,i]]:[[o,i],[r,i/2]];for(let[u,c]of s){let d=await Fn(u,c);if(!d)continue;let a=Vn(d,n.PATH??"");return n.PATH=a,{status:"applied",pathEntries:a.split(V).length,shell:u}}return{status:"failed",shell:o}}var Ge={readHubDiscovery:b,clearHubDiscoveryIfOwned:be,probeProcess:(e)=>{process.kill(e,0)},requestHubShutdown:M,ensureDetachedHubServer:L,claimHubDaemonProcess:$n,loadHubDaemon:()=>import("@cerebriline/core/hub/daemon-entry"),ensureLoginShellPath:je,setHomeDirIfUnset:jn,homeDir:Wn,cwd:()=>process.cwd(),env:process.env,writeOutput:(e)=>process.stdout.write(e)};function qe(e,t){let n=e.indexOf(t);return(n>=0?e[n+1]:void 0)?.trim()||void 0}function Ke(e,t){let n=qe(e,"--discovery-path");if(!n)throw Error("--discovery-path is required for remote Hub management");return t.env.CLINE_HUB_DISCOVERY_PATH=n,n}async function Gn(e=process.argv,t=Ge){t.setHomeDirIfUnset(t.homeDir()),await t.ensureLoginShellPath();let n=qe(e,"--cwd")??t.cwd();Ke(e,t);let o=await t.ensureDetachedHubServer(n,{host:"127.0.0.1",port:0,pathname:"/hub",allowPortFallback:!0,manageConnectors:!1});t.writeOutput(`${JSON.stringify({...o,cwd:n,platform:process.platform,arch:process.arch})}
4
4
  `)}async function Ko(e=process.argv,t=Ge){if(e.includes("--remote-hub-stop")){let n=Ke(e,t),o=await t.readHubDiscovery(n);if(o&&typeof o.pid==="number"&&Number.isInteger(o.pid)&&o.pid>0)try{t.probeProcess(o.pid)}catch(r){if(r?.code==="ESRCH")return await t.clearHubDiscoveryIfOwned(n,o.hubId),!0}if(o&&!await t.requestHubShutdown(o.url,o.authToken))throw Error("Remote Hub shutdown failed");return!0}if(e.includes("--remote-hub-ensure"))return await Gn(e,t),!0;if(t.claimHubDaemonProcess())return await t.loadHubDaemon(),!0;return!1}export{Ko as runRemoteHelperEntrypoint,Gn as runRemoteHubEnsure};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cerebriline/core",
3
3
  "description": "Cerebriline Core SDK for Node Runtime",
4
- "version": "4.100.257",
4
+ "version": "4.100.258",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/mann1x/cline.git",
@@ -80,9 +80,9 @@
80
80
  "ws": "^8.20.0",
81
81
  "yaml": "^2.8.2",
82
82
  "zod": "4.4.3",
83
- "@cerebriline/agents": "4.100.257",
84
- "@cerebriline/llms": "4.100.257",
85
- "@cerebriline/shared": "4.100.257"
83
+ "@cerebriline/agents": "4.100.258",
84
+ "@cerebriline/llms": "4.100.258",
85
+ "@cerebriline/shared": "4.100.258"
86
86
  },
87
87
  "peerDependencies": {
88
88
  "posthog-node": "^5.8.0"