@cerebriline/core 4.100.261 → 4.100.262
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cloud/index.js
CHANGED
|
@@ -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-4f79a6fdec43d7f0f51ddff8fe8e0bababd3d8fec0e58c3d0763205c6aec2b53".trim()||`source-${String(q.version)}`}function qn(){let e=Number(process.env[Hn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792771616117)?1792771616117: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-34a535a13d156348559d06088ca1d67cf0890077ffb8eae5f4f7dc502bff2722".trim()||`source-${String(q.version)}`}function qn(){let e=Number(process.env[Hn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792773013448)?1792773013448: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]
|
package/dist/hub/daemon/entry.js
CHANGED
|
@@ -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,ft()])}}function WDe(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 qDe(e){return e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act"}function CV(e={}){let t=async(r)=>r,n=new im({sessionService:new lm(new dm),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:Kt.CORE,mode:"automation",sessionMetadata:Jn(o?.sessionMetadata,{mode:"automation",trigger:r.source}),interactive:!1,config:{providerId:HDe(r.provider),modelId:r.model,apiKey:r.apiKey?.trim()||void 0,cwd:i,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:qDe(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:WDe(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 jDe,CLINE_HUB_PORT as zDe,resolveClineBuildEnv as GDe}from"@cerebriline/shared";var KDe="CLINE_HUB_HOST",VDe="CLINE_HUB_PORT",XDe="CLINE_HUB_PATHNAME",YDe="127.0.0.1",JDe=zDe,QDe="/hub";function PV(e){return GDe(e)==="development"?jDe:JDe}function ZDe(e={}){return(e.env??process.env)[KDe]?.trim()||YDe}function cP(e={}){let n=(e.env??process.env)[VDe]?.trim();if(!n)return PV(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return PV(e);return r}function e$e(e={}){return(e.env??process.env)[XDe]?.trim()||QDe}function uP(e={},t={}){return{host:e.host??ZDe(t),port:e.port??cP(t),pathname:e.pathname??e$e(t)}}import{chmodSync as t$e,existsSync as n$e,mkdirSync as r$e}from"node:fs";import{dirname as o$e}from"node:path";import{loadSqliteDb as i$e}from"@cerebriline/shared/db";var MV=3;class OV 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 cm(e){return e instanceof Error&&e.name==="HubLockHeldError"}function LV(e){return`${e}.instance.lock`}class $c{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{r$e(o$e(e),{recursive:!0}),t=n$e(e),n=i$e(e)}catch{return new $c(e,void 0)}try{n.exec("PRAGMA busy_timeout = 0;"),n.exec("BEGIN EXCLUSIVE;")}catch(r){if(n.close?.(),s$e(r))throw new OV(e);return new $c(e,void 0)}if(!t)try{t$e(e,384)}catch{}return new $c(e,n)}}function s$e(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 S$e}from"node:path";import{createHash as a$e,randomBytes as FV}from"node:crypto";import{mkdir as pP,open as NV,readFile as UV,rename as d$e,rm as mP,writeFile as l$e}from"node:fs/promises";import{dirname as BV,join as fP}from"node:path";import{ensureLoopbackProxyBypass as c$e,isHubProtocolCompatible as Qft}from"@cerebriline/shared";import{resolveClineDataDir as Cv,resolveClineDir as egt}from"@cerebriline/shared/storage";var u$e="CLINE_HUB_DISCOVERY_PATH",h$e="CLINE_HUB_BUILD_ID",p$e="CLINE_HUB_BUILD_EPOCH_MS",m$e=30000,f$e=15000,DV=100;function g$e(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function y$e(e){return a$e("sha256").update(e).digest("hex").slice(0,12)}function w$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 HV(){return FV(32).toString("hex")}function $V(e){return new Promise((t)=>setTimeout(t,e))}function b$e(e){return`${e}.lock`}async function v$e(e){try{let t=JSON.parse(await UV(fP(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 hP(e){await mP(e,{recursive:!0,force:!0}).catch(()=>{return})}function um(){let e=process.env[h$e]?.trim();if(e)return e;return"sdk-v1-
|
|
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,ft()])}}function WDe(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 qDe(e){return e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act"}function CV(e={}){let t=async(r)=>r,n=new im({sessionService:new lm(new dm),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:Kt.CORE,mode:"automation",sessionMetadata:Jn(o?.sessionMetadata,{mode:"automation",trigger:r.source}),interactive:!1,config:{providerId:HDe(r.provider),modelId:r.model,apiKey:r.apiKey?.trim()||void 0,cwd:i,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:qDe(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:WDe(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 jDe,CLINE_HUB_PORT as zDe,resolveClineBuildEnv as GDe}from"@cerebriline/shared";var KDe="CLINE_HUB_HOST",VDe="CLINE_HUB_PORT",XDe="CLINE_HUB_PATHNAME",YDe="127.0.0.1",JDe=zDe,QDe="/hub";function PV(e){return GDe(e)==="development"?jDe:JDe}function ZDe(e={}){return(e.env??process.env)[KDe]?.trim()||YDe}function cP(e={}){let n=(e.env??process.env)[VDe]?.trim();if(!n)return PV(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return PV(e);return r}function e$e(e={}){return(e.env??process.env)[XDe]?.trim()||QDe}function uP(e={},t={}){return{host:e.host??ZDe(t),port:e.port??cP(t),pathname:e.pathname??e$e(t)}}import{chmodSync as t$e,existsSync as n$e,mkdirSync as r$e}from"node:fs";import{dirname as o$e}from"node:path";import{loadSqliteDb as i$e}from"@cerebriline/shared/db";var MV=3;class OV 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 cm(e){return e instanceof Error&&e.name==="HubLockHeldError"}function LV(e){return`${e}.instance.lock`}class $c{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{r$e(o$e(e),{recursive:!0}),t=n$e(e),n=i$e(e)}catch{return new $c(e,void 0)}try{n.exec("PRAGMA busy_timeout = 0;"),n.exec("BEGIN EXCLUSIVE;")}catch(r){if(n.close?.(),s$e(r))throw new OV(e);return new $c(e,void 0)}if(!t)try{t$e(e,384)}catch{}return new $c(e,n)}}function s$e(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 S$e}from"node:path";import{createHash as a$e,randomBytes as FV}from"node:crypto";import{mkdir as pP,open as NV,readFile as UV,rename as d$e,rm as mP,writeFile as l$e}from"node:fs/promises";import{dirname as BV,join as fP}from"node:path";import{ensureLoopbackProxyBypass as c$e,isHubProtocolCompatible as Qft}from"@cerebriline/shared";import{resolveClineDataDir as Cv,resolveClineDir as egt}from"@cerebriline/shared/storage";var u$e="CLINE_HUB_DISCOVERY_PATH",h$e="CLINE_HUB_BUILD_ID",p$e="CLINE_HUB_BUILD_EPOCH_MS",m$e=30000,f$e=15000,DV=100;function g$e(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function y$e(e){return a$e("sha256").update(e).digest("hex").slice(0,12)}function w$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 HV(){return FV(32).toString("hex")}function $V(e){return new Promise((t)=>setTimeout(t,e))}function b$e(e){return`${e}.lock`}async function v$e(e){try{let t=JSON.parse(await UV(fP(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 hP(e){await mP(e,{recursive:!0,force:!0}).catch(()=>{return})}function um(){let e=process.env[h$e]?.trim();if(e)return e;return"sdk-v1-34a535a13d156348559d06088ca1d67cf0890077ffb8eae5f4f7dc502bff2722".trim()||`source-${String(Ql.version)}`}function WV(){let e=Number(process.env[p$e]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792773013448)?1792773013448:void 0}function Pv(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${y$e(e)}`,n=process.env[u$e]?.trim()||fP(Cv(),"locks","hub","owners",`${g$e(t)}.json`);return{ownerId:t,discoveryPath:n}}async function Mv(e){try{let t=JSON.parse(await UV(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 gP(e,t,n){await jV(e,async()=>{let r=BV(e);await pP(r,{recursive:!0});let o=`${e}.${process.pid}.${FV(6).toString("hex")}.tmp`,i;try{i=await NV(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 d$e(o,e);let s;try{s=await NV(r,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await mP(o,{force:!0}).catch(()=>{return}),s}})}async function qV(e,t){return await jV(e,async()=>{if((await Mv(e))?.hubId!==t)return!1;return await mP(e,{force:!0}),!0})}async function k$e(e,t,n){let r=b$e(e);await pP(BV(r),{recursive:!0});let o=Date.now()+f$e;while(!0){try{await pP(r,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await v$e(r);if(!a){if(Date.now()>=o){await hP(r);continue}await $V(DV);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!w$e(a.pid)||d>m$e){await hP(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await $V(DV);continue}try{return await l$e(fP(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
1536
1536
|
`,"utf8"),await n()}finally{await hP(r)}}}function jV(e,t){return k$e(`${e}.mutation`,"discovery mutation",t)}async function hm(e,t){c$e();try{let n=await fetch(t?.authToken?T$e(e):zV(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 Fc(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function zV(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function T$e(e){let t=new URL(zV(e));return t.pathname="/status",t.toString()}var x$e="shared:cline",_$e="CLINE_HUB_DISCOVERY_PATH",E$e="hub-production";function Ov(e=x$e){return Pv(`${e}@${um()}`)}function Lv(){return{ownerId:E$e,discoveryPath:process.env[_$e]?.trim()||S$e(Cv(),"locks","hub","production.json")}}function A$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 GV=120,yP="...";function wP(e){let t=e.trim();if(!t)return"";if(Buffer.byteLength(t,"utf8")<=GV)return t;let n=GV-Buffer.byteLength(yP,"utf8");if(n<=0)return yP;let r="";for(let o of t){if(Buffer.byteLength(r+o,"utf8")>n)break;r+=o}return`${r}${yP}`}async function KV(e){let t=e?.sessionId?.trim()||"unknown",n=typeof e?.metadata?.messagesPath==="string"?e.metadata.messagesPath:void 0,o=[...await Nc(n)].reverse().find((d)=>d.role==="assistant"),i=o?A$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:wP(i&&i.length>0?i:a.length>0?a:s),severity:"info"}}import{resolve as QBe}from"node:path";import{CLINE_DEFAULT_MODEL_ID as ZBe,captureSdkError as ek,createSessionId as E0,HUB_CLIENT_TOOL_APPROVAL_CAPABILITY as eHe}from"@cerebriline/shared";import{isChatWorkspacePath as tHe}from"@cerebriline/shared/storage";function pm(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function bP(e){let t=e?.trim();return t?t:void 0}function R$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 VV(e,t){return new Date(new Date(e).getTime()+Math.max(0,Math.floor(t))*1000).toISOString()}function XV(e,t){return new Date(new Date(e).getTime()-Math.max(0,Math.floor(t))*1000).toISOString()}function I$e(e,t){if(!e)return t;return new Date(e).getTime()>=new Date(t).getTime()?e:t}function C$e(e,t){let n=e.eventId.trim(),r=e.eventType.trim(),o=e.source.trim(),i=bP(e.subject),s=bP(e.dedupeKey)??`${r}:${o}:${i??n}`;return{eventId:n,eventType:r,source:o,subject:i,occurredAt:R$e(e.occurredAt,t),workspaceRoot:bP(e.workspaceRoot),payload:pm(e.payload)?e.payload:void 0,attributes:pm(e.attributes)?e.attributes:void 0,dedupeKey:s}}function vP(e,t){if(!t)return;let n=t.split("."),r=e;for(let o of n){if(!pm(r))return;r=r[o]}return r}function P$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=vP(n,t);if(r!==void 0)return r;if(e.attributes){let o=vP(e.attributes,t);if(o!==void 0)return o}if(e.payload)return vP(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(pm(t)){if(!pm(e))return!1;return Object.entries(t).every(([n,r])=>Nv(e[n],r))}return Object.is(e,t)}function M$e(e,t){if(!t||Object.keys(t).length===0)return!0;return Object.entries(t).every(([n,r])=>Nv(P$e(e,n),r))}class kP{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=C$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(!M$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=I$e(d.scheduledFor,VV(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:XV(n,i)}))return{reason:"dedupe_window"};let s=e.cooldownSeconds??0;if(s>0&&this.store.hasRecentEventRunForSpec({specId:e.specId,sinceIso:XV(n,s)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:e.specId,specRevision:e.revision,triggerKind:"event",triggerEventId:t.eventId,scheduledFor:o>0?VV(n,o):n}),reason:"dedupe_window"}}}class mm{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 q$e}from"node:path";import{buildClineSystemPrompt as j$e}from"@cerebriline/shared";import{nowIso as e5}from"@cerebriline/shared/db";import{mkdirSync as O$e,writeFileSync as L$e}from"node:fs";import{isAbsolute as N$e,join as JV}from"node:path";import{resolveCronReportsDir as D$e,resolveCronSpecsDir as $$e}from"@cerebriline/shared/storage";function us(e){if(/[:#\n]/.test(e)||e.includes('"'))return JSON.stringify(e);return e}function kr(e,t){if(t===void 0||t===null)return;return`${e}: ${us(t)}`}function QV(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,jt(),e,n).changes??0)===1}attachReportPathToRun(e,t){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(t,jt(),e)}}function ff(e){return e?new Date(e).getTime():void 0}function p7(e){let t=e.metadata?{...e.metadata}:void 0;if(t)delete t.__hubScheduleCreatedBy,delete t.__hubScheduleCwd,delete t.__hubRuntimeOptions;return t}function Su(e){let t=e.metadata;return{scheduleId:e.externalId,name:e.title,cronPattern:e.triggerKind==="one_off"?xu: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:ff(e.nextRunAt),lastRunAt:ff(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:p7(e)}}function m7(e){switch(e){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function Yk(e,t){return{executionId:e.runId,scheduleId:t,sessionId:e.sessionId,triggeredAt:new Date(e.scheduledFor??e.createdAt).getTime(),startedAt:ff(e.startedAt),endedAt:ff(e.completedAt),status:m7(e.status),errorMessage:e.error}}class gf{store;materializer;runner;started=!1;disposed=!1;constructor(e){this.store=new Tu({dbPath:e.dbPath}),this.materializer=new fu({store:this.store}),this.runner=new yu({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===xu?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 Su(this.store.createHubSchedule({...e,timezone:t}))}getSchedule(e){let t=this.store.getHubSchedule(e);return t?Su(t):void 0}listSchedules(e={}){return this.store.listHubSchedules(e).map((t)=>Su(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=Su(n),s=t.cronPattern??i.cronPattern;if(s.trim()===xu&&typeof t.timezone==="string"&&t.timezone.trim())throw Error("timezone is only supported for recurring schedules");if(this.validateScheduleTiming(s,s.trim()===xu?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?Su(a):void 0}validateScheduleTiming(e,t,n,r){if(e.trim()!==xu){xO(e),Gk(t);return}if(t?.trim())throw Error("timezone is only supported for recurring schedules");let o=n?.[h7];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 Yk(n,e)}triggerScheduleNowDetached(e){let t=this.store.enqueueHubScheduleRun(e,"manual");if(!t)return;return this.runner.tick().catch(()=>{return}),Yk(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 Yk(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 Qk,statSync as f7}from"node:fs";import{isAbsolute as NO,relative as g7,sep as DO}from"node:path";import{ONE_TIME_SCHEDULE_CRON_PATTERN as $O,ONE_TIME_SCHEDULE_RUN_AT_METADATA_KEY as FO}from"@cerebriline/shared";import{z as _t}from"zod";var y7=_t.enum(["create","update","list","get","pause","resume","delete","run_now"]),w7=_t.object({provider_id:_t.string().min(1),model_id:_t.string().min(1).optional()}),Cd=_t.object({operation:y7,schedule_id:_t.string().min(1).optional(),schedule_type:_t.enum(["once","recurring"]).optional(),name:_t.string().min(1).optional(),prompt:_t.string().min(1).optional(),run_at:_t.string().datetime({offset:!0}).optional(),cron_pattern:_t.string().min(1).optional(),timezone:_t.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:_t.boolean().optional(),mode:_t.enum(["act","plan","yolo"]).optional(),system_prompt:_t.string().nullable().optional(),max_iterations:_t.number().int().positive().nullable().optional(),timeout_seconds:_t.number().int().positive().nullable().optional(),max_parallel:_t.number().int().positive().max(32).optional(),tags:_t.array(_t.string().min(1)).optional(),model_selection:w7.optional(),limit:_t.number().int().positive().max(200).optional()});function Ad(e,t,n,r){if(!UO.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 UO=new Set(["create","update","pause","resume","delete","run_now"]);function Id(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function Zk(e,t){try{let n=Qk.native(e);if(!f7(n).isDirectory())throw Error("not a directory");return n}catch{throw Error(`${t} does not resolve to an existing safe path`)}}function b7(e,t){try{return Qk.native(e)===Qk.native(t)}catch{return!1}}function BO(e,t,n){let r=g7(e,t);if(r===".."||r.startsWith(`..${DO}`)||NO(r))throw Error(`${n} is outside the workspace scope`)}function HO(e,t,n){return Zk(NO(t)?t:`${e}${DO}${t}`,n)}function v7(e){let t=Zk(e.workspaceRoot,"workspaceRoot"),n=e.cwd?HO(t,e.cwd,"cwd"):t;return BO(t,n,"cwd"),{...e,workspaceRoot:t,cwd:n}}function Rd(e,t){if(!e)throw Error("schedule does not exist");if(!b7(e.workspaceRoot,t.workspaceRoot))throw Error("schedule is outside this session's workspace scope");let n=Zk(e.workspaceRoot,"schedule workspaceRoot");if(e.cwd){let r=HO(n,e.cwd,"schedule cwd");BO(n,r,"schedule cwd")}}function LO(e){if(!e)return;return{providerId:e.provider_id.trim(),modelId:e.model_id?.trim()||void 0}}function Jk(e){if(!e)return;return[...new Set(e.map((t)=>t.trim()).filter(Boolean))]}function WO(e){let t=Date.parse(Id(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 k7(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:$O,metadata:{[FO]:WO(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:Id(e.cron_pattern,"cron_pattern"),timezone:e.timezone?.trim()||void 0}}throw Error("schedule_type is required for create")}function T7(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:$O,timezone:null,metadata:{[FO]:WO(e.run_at)}}}if(e.schedule_type==="recurring"||e.cron_pattern)return{cronPattern:Id(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 _u(e){return Id(e.schedule_id,"schedule_id")}async function eT(e,t,n){let r=Cd.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=v7(i);if(UO.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:Id(o.name,"name"),...k7(o),prompt:Id(o.prompt,"prompt"),workspaceRoot:s.workspaceRoot,cwd:s.cwd,modelSelection:LO(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:Jk(o.tags)});return e.publish?.("schedule.created",{schedule:a},n.sessionId),Ad(e,o,n,!0),{ok:!0,operation:o.operation,schedule:a}}case"update":{let a=_u(o);Rd(e.schedules.getSchedule(a),s);let d=e.schedules.updateSchedule(a,{scheduleId:a,...T7(o),name:o.name?.trim()||void 0,prompt:o.prompt?.trim()||void 0,modelSelection:LO(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:Jk(o.tags)});if(!d)throw Error("schedule does not exist");return e.publish?.("schedule.updated",{schedule:d},n.sessionId),Ad(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"list":{let a=e.schedules.listSchedules({enabled:o.enabled,tags:Jk(o.tags),workspaceRoot:s.workspaceRoot,limit:o.limit??50}).filter((d)=>{try{return Rd(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(_u(o));return Rd(a,s),{ok:!0,operation:o.operation,schedule:a}}case"pause":case"resume":{let a=_u(o);Rd(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),Ad(e,o,n,!0),{ok:!0,operation:o.operation,schedule:d}}case"delete":{let a=_u(o);Rd(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),Ad(e,o,n,!0),{ok:!0,operation:o.operation,deleted:d}}case"run_now":{let a=_u(o);Rd(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),Ad(e,o,n,!0),{ok:!0,operation:o.operation,execution:d}}}}catch(i){return Ad(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 X7}from"@cerebriline/llms";import{markOtlpTraceRelayProvider as Y7}from"@cerebriline/shared";import{metrics as J7,trace as Q7}from"@opentelemetry/api";import{logs as Z7}from"@opentelemetry/api-logs";import{OTLPLogExporter as eQ}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as tQ}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as nQ}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as rQ}from"@opentelemetry/resources";import{BatchLogRecordProcessor as oQ,ConsoleLogRecordExporter as iQ,LoggerProvider as sQ}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as aQ,MeterProvider as dQ,PeriodicExportingMetricReader as sL}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as lQ,ConsoleSpanExporter as cQ,SimpleSpanProcessor as uQ}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as hQ}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as pQ,ATTR_SERVICE_VERSION as mQ}from"@opentelemetry/semantic-conventions";import{mkdirSync as S7,readFileSync as x7,statSync as _7,writeFileSync as E7}from"node:fs";import{dirname as A7}from"node:path";import{CONFIGURABLE_MODEL_TOOL_NAMES as jO}from"@cerebriline/shared";import{resolveGlobalSettingsPath as qO}from"@cerebriline/shared/storage";import{z as Dt}from"zod";var tT=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}),R7=Dt.enum(["basic","agentic"]).catch("agentic"),I7=Dt.partialRecord(Dt.enum(jO),Dt.object({enabled:Dt.boolean()}).strip()).optional(),C7=Dt.record(Dt.string(),Dt.object({enabled:Dt.boolean()}).strip()).optional().catch(void 0),P7=Dt.enum(["plan","act"]),nT=Dt.object({telemetryOptOut:Dt.boolean().default(!1).catch(!1),autoUpdateEnabled:Dt.boolean().default(!0).catch(!0),compactionStrategy:R7.optional(),compactionEnabled:Dt.boolean().optional().catch(void 0),planActMode:P7.optional().catch(void 0),toolAutoApprove:Dt.boolean().optional().catch(void 0),tuiTheme:Dt.string().optional().catch(void 0),disabledTools:tT.optional(),tools:I7,disabledPlugins:tT.optional(),disabledAgentPlugins:tT.optional(),bundledSkills:C7}).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 yf(){return nT.parse({})}var wf;function M7(){wf=void 0}function O7(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 L7(e){let t;try{t=x7(e,"utf8")}catch{return{value:yf(),loadFailed:!0}}try{let n=nT.safeParse(JSON.parse(t));return n.success?{value:n.data,loadFailed:!1}:{value:yf(),loadFailed:!0}}catch{return{value:yf(),loadFailed:!0}}}function zO(){let e=qO(),t=_7(e,{throwIfNoEntry:!1}),n=t?.mtimeMs??0,r=t?.size??0,o=wf;if(o&&o.path===e&&o.mtimeMs===n&&o.size===r)return o;let i=t?L7(e):{value:yf(),loadFailed:!1},s=O7(i.value);return wf={path:e,mtimeMs:n,size:r,value:s,loadFailed:i.loadFailed},wf}function fn(){return zO().value}function Ds(e,t={}){let n=qO(),r=fn();S7(A7(n),{recursive:!0});let o=nT.parse(e);if(!r.telemetryOptOut&&o.telemetryOptOut)UM(t.telemetry);E7(n,`${JSON.stringify(o,null,2)}
|
|
321
|
-
`,"utf8"),M7()}function KO(){return fn().telemetryOptOut}function $s(e){return new Set(e??fn().disabledTools??[])}function GO(e){return new Set(e??fn().disabledPlugins??[])}function Eu(e){return new Set(e??fn().disabledAgentPlugins??[])}function VO(e){return jO.includes(e)}function N7(){let e=zO();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function rT(e){return N7()[e]?.enabled===!0}function D7(e,t){let n=fn();Ds({...n,tools:{...n.tools,[e]:{enabled:t}}})}function XO(e){if(VO(e)){let o=rT(e);return D7(e,!o),o}let t=fn(),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 $7(e,t){let n=[...new Set(e.map((s)=>s.trim()).filter(Boolean))];if(n.length===0)return;let r=fn(),o=$s(r.disabledTools),i={...r.tools};for(let s of n){if(VO(s)){i[s]={enabled:!t};continue}if(t)o.add(s);else o.delete(s)}Ds({...r,disabledTools:[...o],tools:i})}function YO(e,t){return $7([e],t),t}function JO(e,t){let n=e.trim();if(!n)return;let r=fn(),o=GO(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Ds({...r,disabledPlugins:[...o]})}function QO(e,t){let n=e.trim();if(!n)return;let r=fn(),o=Eu(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Ds({...r,disabledAgentPlugins:[...o]})}function ZO(e,t){let n=GO(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 eL(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 F7,mkdirSync as U7,readFileSync as B7,writeFileSync as H7}from"node:fs";import{resolve as W7}from"node:path";import{resolveSessionDataDir as j7}from"@cerebriline/shared/storage";import{nanoid as q7}from"nanoid";import*as z7 from"node-machine-id";var K7="machine-id",tL,nL=!1;function rL(){if(!nL)tL=oL(),nL=!0;return tL??iL()}function Au(e){let t=e?.trim();if(t)return t;let n=oL();if(n)return n;return iL()}function G7(){let e=z7;return e.machineIdSync??e.default?.machineIdSync}function oL(){try{let e=G7();if(!e)return;return e().trim()||void 0}catch{return}}function iL(){let e=j7(),t=W7(e,K7);try{if(F7(t)){let r=B7(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${q7()}`;try{U7(e,{recursive:!0}),H7(t,n,"utf8")}catch{}return n}class oT{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(V7(d)){o[l]=d;continue}try{o[l]=JSON.stringify(d)}catch{o[l]=String(d)}}return o}}function V7(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class iT{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 bf{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new iT({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??rL(),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 aL{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 dL{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=rQ({[pQ]:e.serviceName??"cline",...e.serviceVersion?{[mQ]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)J7.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)Z7.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return Q7.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new oT({...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 bf({...e,adapters:[t],distinctId:Au(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=sT(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)=>bQ(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 dQ({resource:e,readers:o})}createTracerProvider(e){let t=sT(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=wQ(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 hQ({resource:e,spanProcessors:i?[new X7,...o]:o});if(i)Y7(s);return s}createLoggerProvider(e){let t=sT(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=yQ(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new oQ(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 sQ({resource:e,processors:n})}}function fQ(e){let t=new dL(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 lL(e){if(KO())return{telemetry:new aL(e)};if(e.enabled!==!0)return{telemetry:new bf({...e,distinctId:Au(e.distinctId)})};return fQ(e)}function gQ(e){let{telemetry:t,provider:n,emitProviderCreated:r}=lL(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 sT(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function yQ(e,t){if(e==="console")return new iQ;if(!t.endpoint)return null;let n=aT(t.endpoint,"/v1/logs");return new eQ({url:n,headers:t.headers})}function wQ(e,t){if(e==="console")return new uQ(new cQ);if(!t.endpoint)return null;let n=aT(t.endpoint,"/v1/traces");return new lQ(new nQ({url:n,headers:t.headers}))}function bQ(e,t){if(e==="console")return new sL({exporter:new aQ,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=aT(t.endpoint,"/v1/metrics");return new sL({exporter:new tQ({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function aT(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 xQ,zodToJsonSchema as _Q}from"@cerebriline/shared";import{z as Zr}from"zod";import{resolve as cL}from"node:path";import{z as Re}from"zod";var uL=Re.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),vQ=Re.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),hL=Re.union([Re.literal(0),Re.literal(1),Re.literal(2),Re.literal(3),Re.literal(4),Re.literal(5)]),kQ=Re.object({provider_id:Re.string().min(1),model_id:Re.string().min(1).optional()}),vf=Re.object({operation:Re.enum(["create","update","list","get"]),task_id:Re.string().min(1).optional(),expected_revision:Re.number().int().positive().optional(),type:uL.optional(),title:Re.string().min(1).optional(),description:Re.string().nullable().optional(),instructions:Re.string().min(1).optional(),scope:Re.enum(["workspace","global"]).optional(),workspace_root:Re.string().min(1).nullable().optional(),cwd:Re.string().min(1).nullable().optional(),resource_paths:Re.array(Re.string().min(1)).optional(),priority:hL.optional(),assignee:Re.string().min(1).nullable().optional(),model_selection:kQ.nullable().optional(),mode:Re.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Re.string().nullable().optional(),max_iterations:Re.number().int().positive().nullable().optional(),timeout_seconds:Re.number().int().positive().nullable().optional(),available_at:Re.string().datetime().optional(),expires_at:Re.string().datetime().optional(),automation_eligible:Re.boolean().optional(),statuses:Re.array(vQ).optional(),types:Re.array(uL).optional(),priorities:Re.array(hL).optional(),limit:Re.number().int().positive().max(500).optional()}),TQ=new Set(["create","update"]);function dT(e,t,n,r){if(!TQ.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 Pd(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function pL(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function fL(e,t){return cL(e)===cL(t)}function mL(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!fL(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 SQ(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||!fL(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function gL(e,t,n){let r=vf.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=SQ(o,s);switch(o.operation){case"create":{let d={type:Pd(o.type,"type"),title:Pd(o.title,"title"),description:o.description??void 0,instructions:Pd(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:pL(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:Pd(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 dT(e,o,n,!0),l}case"update":{let d=Pd(o.task_id,"task_id");if(mL(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:pL(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 dT(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(Pd(o.task_id,"task_id"));return mL(d,s),{ok:!0,operation:o.operation,task:d}}}}catch(s){return dT(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:s instanceof Error?s.message:String(s)}}}}var Ru="tasks",yL='# 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.',EQ="# 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.",AQ=vf.extend({kind:Zr.literal("todo")}).strict(),wL=Cd.extend({kind:Zr.literal("scheduled")}).strict(),bL=Zr.discriminatedUnion("kind",[AQ,wL]),RQ=Zr.discriminatedUnion("kind",[wL]),vL=["create","update","list","get","pause","resume","delete","run_now"],IQ=Zr.object({...Cd.shape,...vf.shape,kind:Zr.enum(["todo","scheduled"]),operation:Zr.enum(vL)}).strict(),CQ=Zr.object({...Cd.shape,kind:Zr.enum(["scheduled"]),operation:Zr.enum(vL)}).strict();function lT(e){let t=e.todo;return xQ({name:Ru,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:_Q(t?IQ:CQ),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?bL:RQ).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 gL(t,o.data,r)}}return{kind:"scheduled",...await eT(e.scheduled,o.data,r)}}})}function cT(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?EQ:yL,whenToolAvailable:Ru})}}}import{createSessionId as jZ,ensureLoopbackProxyBypass as GL,isHubProtocolCompatible as qZ,resolveClineBuildEnv as zZ,resolveHubCommandTimeoutMs as KZ}from"@cerebriline/shared";import GZ from"ws";var kf="0.0.92";var Oi={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:kf,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 Tf="session_not_found";class Md 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 Sf(e){return e instanceof Md||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as cZ}from"node:child_process";import{closeSync as uZ,mkdirSync as hZ,openSync as pZ,readFileSync as mZ,unlinkSync as fZ}from"node:fs";import{basename as gZ,dirname as yZ,join as wZ}from"node:path";import{fileURLToPath as bZ}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as vZ,isBunEmbeddedModulePath as kZ,isHubDaemonProcess as UL,resolveClineBuildEnv as BL,withResolvedClineBuildEnv as TZ}from"@cerebriline/shared";import{createHash as PQ,randomBytes as AL}from"node:crypto";import{existsSync as MQ}from"node:fs";import{mkdir as hT,open as TL,readFile as RL,rename as OQ,rm as xf,writeFile as LQ}from"node:fs/promises";import{dirname as IL,join as pT}from"node:path";import{ensureLoopbackProxyBypass as NQ,isHubProtocolCompatible as DQ}from"@cerebriline/shared";import{resolveClineDataDir as Iu,resolveClineDir as qqe}from"@cerebriline/shared/storage";var $Q="CLINE_HUB_DISCOVERY_PATH",FQ="CLINE_HUB_BUILD_ID",UQ="CLINE_HUB_BUILD_EPOCH_MS",BQ=30000,HQ=15000,SL=100;function WQ(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function jQ(e){return PQ("sha256").update(e).digest("hex").slice(0,12)}function qQ(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 CL(){return AL(32).toString("hex")}function xL(e){return new Promise((t)=>setTimeout(t,e))}function zQ(e){return`${e}.lock`}async function KQ(e){try{let t=JSON.parse(await RL(pT(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 uT(e){await xf(e,{recursive:!0,force:!0}).catch(()=>{return})}function eo(){let e=process.env[FQ]?.trim();if(e)return e;return"sdk-v1-4f79a6fdec43d7f0f51ddff8fe8e0bababd3d8fec0e58c3d0763205c6aec2b53".trim()||`source-${String(Oi.version)}`}function mT(){let e=Number(process.env[UQ]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792771616117)?1792771616117:void 0}function Fs(e,t=eo()){let n=DQ(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 _L(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function EL(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 GQ(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 Cu(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=_L(e.buildEpochMs),i=_L(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let s=EL(e.coreVersion),a=EL(t.coreVersion);if(s&&a){let d=GQ(s,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function Pu(){return{buildId:eo(),buildEpochMs:mT(),coreVersion:String(Oi.version)}}function Od(e,t){let n=t?.self??Pu(),r=Fs(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return Cu(n,e)<=0}function Us(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${jQ(e)}`,n=process.env[$Q]?.trim()||pT(Iu(),"locks","hub","owners",`${WQ(t)}.json`);return{ownerId:t,discoveryPath:n}}function Kqe(e=`hub-${Date.now().toString(36)}`){return Us(e)}async function qt(e){try{let t=JSON.parse(await RL(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 _f(e,t,n){await fT(e,async()=>{let r=IL(e);await hT(r,{recursive:!0});let o=`${e}.${process.pid}.${AL(6).toString("hex")}.tmp`,i;try{i=await TL(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
|
|
321
|
+
`,"utf8"),M7()}function KO(){return fn().telemetryOptOut}function $s(e){return new Set(e??fn().disabledTools??[])}function GO(e){return new Set(e??fn().disabledPlugins??[])}function Eu(e){return new Set(e??fn().disabledAgentPlugins??[])}function VO(e){return jO.includes(e)}function N7(){let e=zO();return{web_search:{enabled:!e.loadFailed},...e.value.tools}}function rT(e){return N7()[e]?.enabled===!0}function D7(e,t){let n=fn();Ds({...n,tools:{...n.tools,[e]:{enabled:t}}})}function XO(e){if(VO(e)){let o=rT(e);return D7(e,!o),o}let t=fn(),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 $7(e,t){let n=[...new Set(e.map((s)=>s.trim()).filter(Boolean))];if(n.length===0)return;let r=fn(),o=$s(r.disabledTools),i={...r.tools};for(let s of n){if(VO(s)){i[s]={enabled:!t};continue}if(t)o.add(s);else o.delete(s)}Ds({...r,disabledTools:[...o],tools:i})}function YO(e,t){return $7([e],t),t}function JO(e,t){let n=e.trim();if(!n)return;let r=fn(),o=GO(r.disabledPlugins);if(t)o.add(n);else o.delete(n);Ds({...r,disabledPlugins:[...o]})}function QO(e,t){let n=e.trim();if(!n)return;let r=fn(),o=Eu(r.disabledAgentPlugins);if(t)o.add(n);else o.delete(n);Ds({...r,disabledAgentPlugins:[...o]})}function ZO(e,t){let n=GO(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 eL(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 F7,mkdirSync as U7,readFileSync as B7,writeFileSync as H7}from"node:fs";import{resolve as W7}from"node:path";import{resolveSessionDataDir as j7}from"@cerebriline/shared/storage";import{nanoid as q7}from"nanoid";import*as z7 from"node-machine-id";var K7="machine-id",tL,nL=!1;function rL(){if(!nL)tL=oL(),nL=!0;return tL??iL()}function Au(e){let t=e?.trim();if(t)return t;let n=oL();if(n)return n;return iL()}function G7(){let e=z7;return e.machineIdSync??e.default?.machineIdSync}function oL(){try{let e=G7();if(!e)return;return e().trim()||void 0}catch{return}}function iL(){let e=j7(),t=W7(e,K7);try{if(F7(t)){let r=B7(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${q7()}`;try{U7(e,{recursive:!0}),H7(t,n,"utf8")}catch{}return n}class oT{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(V7(d)){o[l]=d;continue}try{o[l]=JSON.stringify(d)}catch{o[l]=String(d)}}return o}}function V7(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}class iT{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 bf{adapters;metadata;distinctId;deviceId;commonProperties;constructor(e={}){if(this.adapters=[...e.adapters??[]],e.logger)this.adapters.push(new iT({logger:e.logger}));this.metadata={...e.metadata??{}},this.distinctId=e.distinctId,this.deviceId=e.deviceId??rL(),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 aL{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 dL{meterProvider;loggerProvider;tracerProvider;options;constructor(e={}){this.options=e;let t=rQ({[pQ]:e.serviceName??"cline",...e.serviceVersion?{[mQ]:e.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(t),this.loggerProvider=this.createLoggerProvider(t),this.tracerProvider=this.createTracerProvider(t),this.meterProvider)J7.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)Z7.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(e="cline",t){return Q7.getTracer(e,t??this.options.serviceVersion)}createAdapter(e){return new oT({...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 bf({...e,adapters:[t],distinctId:Au(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=sT(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)=>bQ(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 dQ({resource:e,readers:o})}createTracerProvider(e){let t=sT(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=wQ(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 hQ({resource:e,spanProcessors:i?[new X7,...o]:o});if(i)Y7(s);return s}createLoggerProvider(e){let t=sT(this.options.logsExporter);if(t.length===0)return null;let n=t.map((r)=>{let o=yQ(r,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!o)return null;return new oQ(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 sQ({resource:e,processors:n})}}function fQ(e){let t=new dL(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 lL(e){if(KO())return{telemetry:new aL(e)};if(e.enabled!==!0)return{telemetry:new bf({...e,distinctId:Au(e.distinctId)})};return fQ(e)}function gQ(e){let{telemetry:t,provider:n,emitProviderCreated:r}=lL(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 sT(e){if(!e)return[];return(Array.isArray(e)?e:e.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function yQ(e,t){if(e==="console")return new iQ;if(!t.endpoint)return null;let n=aT(t.endpoint,"/v1/logs");return new eQ({url:n,headers:t.headers})}function wQ(e,t){if(e==="console")return new uQ(new cQ);if(!t.endpoint)return null;let n=aT(t.endpoint,"/v1/traces");return new lQ(new nQ({url:n,headers:t.headers}))}function bQ(e,t){if(e==="console")return new sL({exporter:new aQ,exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout});if(!t.endpoint)return null;let n=aT(t.endpoint,"/v1/metrics");return new sL({exporter:new tQ({url:n,headers:t.headers}),exportIntervalMillis:t.interval,exportTimeoutMillis:t.timeout})}function aT(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 xQ,zodToJsonSchema as _Q}from"@cerebriline/shared";import{z as Zr}from"zod";import{resolve as cL}from"node:path";import{z as Re}from"zod";var uL=Re.enum(["suggestion","follow-up","todo","handoff","idea","reminder"]),vQ=Re.enum(["pending_approval","approved","in_progress","completed","failed","cancelled","expired"]),hL=Re.union([Re.literal(0),Re.literal(1),Re.literal(2),Re.literal(3),Re.literal(4),Re.literal(5)]),kQ=Re.object({provider_id:Re.string().min(1),model_id:Re.string().min(1).optional()}),vf=Re.object({operation:Re.enum(["create","update","list","get"]),task_id:Re.string().min(1).optional(),expected_revision:Re.number().int().positive().optional(),type:uL.optional(),title:Re.string().min(1).optional(),description:Re.string().nullable().optional(),instructions:Re.string().min(1).optional(),scope:Re.enum(["workspace","global"]).optional(),workspace_root:Re.string().min(1).nullable().optional(),cwd:Re.string().min(1).nullable().optional(),resource_paths:Re.array(Re.string().min(1)).optional(),priority:hL.optional(),assignee:Re.string().min(1).nullable().optional(),model_selection:kQ.nullable().optional(),mode:Re.enum(["act","plan","yolo"]).nullable().optional(),system_prompt:Re.string().nullable().optional(),max_iterations:Re.number().int().positive().nullable().optional(),timeout_seconds:Re.number().int().positive().nullable().optional(),available_at:Re.string().datetime().optional(),expires_at:Re.string().datetime().optional(),automation_eligible:Re.boolean().optional(),statuses:Re.array(vQ).optional(),types:Re.array(uL).optional(),priorities:Re.array(hL).optional(),limit:Re.number().int().positive().max(500).optional()}),TQ=new Set(["create","update"]);function dT(e,t,n,r){if(!TQ.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 Pd(e,t){let n=e?.trim();if(!n)throw Error(`${t} is required for this operation`);return n}function pL(e){if(e===void 0||e===null)return e;return{providerId:e.provider_id,modelId:e.model_id}}function fL(e,t){return cL(e)===cL(t)}function mL(e,t){if(!e)throw Error("task does not exist");if(t.workspaceRoot){if(e.scope!=="workspace"||!e.workspaceRoot||!fL(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 SQ(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||!fL(e.workspace_root,t.workspaceRoot))throw Error(`this session can only manage ${n} tasks`)}return n}async function gL(e,t,n){let r=vf.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=SQ(o,s);switch(o.operation){case"create":{let d={type:Pd(o.type,"type"),title:Pd(o.title,"title"),description:o.description??void 0,instructions:Pd(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:pL(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:Pd(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 dT(e,o,n,!0),l}case"update":{let d=Pd(o.task_id,"task_id");if(mL(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:pL(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 dT(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(Pd(o.task_id,"task_id"));return mL(d,s),{ok:!0,operation:o.operation,task:d}}}}catch(s){return dT(e,o,n,!1),{ok:!1,operation:o.operation,error:{code:"task_operation_failed",message:s instanceof Error?s.message:String(s)}}}}var Ru="tasks",yL='# 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.',EQ="# 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.",AQ=vf.extend({kind:Zr.literal("todo")}).strict(),wL=Cd.extend({kind:Zr.literal("scheduled")}).strict(),bL=Zr.discriminatedUnion("kind",[AQ,wL]),RQ=Zr.discriminatedUnion("kind",[wL]),vL=["create","update","list","get","pause","resume","delete","run_now"],IQ=Zr.object({...Cd.shape,...vf.shape,kind:Zr.enum(["todo","scheduled"]),operation:Zr.enum(vL)}).strict(),CQ=Zr.object({...Cd.shape,kind:Zr.enum(["scheduled"]),operation:Zr.enum(vL)}).strict();function lT(e){let t=e.todo;return xQ({name:Ru,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:_Q(t?IQ:CQ),retryable:!1,maxRetries:0,execute:async(n,r)=>{let o=(t?bL:RQ).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 gL(t,o.data,r)}}return{kind:"scheduled",...await eT(e.scheduled,o.data,r)}}})}function cT(e){return{name:"hub-task-guidance",manifest:{capabilities:["rules"]},setup:(t)=>{t.registerRule({id:"hub:task-guidance",content:e?.todoEnabled===!1?EQ:yL,whenToolAvailable:Ru})}}}import{createSessionId as jZ,ensureLoopbackProxyBypass as GL,isHubProtocolCompatible as qZ,resolveClineBuildEnv as zZ,resolveHubCommandTimeoutMs as KZ}from"@cerebriline/shared";import GZ from"ws";var kf="0.0.92";var Oi={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:kf,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 Tf="session_not_found";class Md 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 Sf(e){return e instanceof Md||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as cZ}from"node:child_process";import{closeSync as uZ,mkdirSync as hZ,openSync as pZ,readFileSync as mZ,unlinkSync as fZ}from"node:fs";import{basename as gZ,dirname as yZ,join as wZ}from"node:path";import{fileURLToPath as bZ}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as vZ,isBunEmbeddedModulePath as kZ,isHubDaemonProcess as UL,resolveClineBuildEnv as BL,withResolvedClineBuildEnv as TZ}from"@cerebriline/shared";import{createHash as PQ,randomBytes as AL}from"node:crypto";import{existsSync as MQ}from"node:fs";import{mkdir as hT,open as TL,readFile as RL,rename as OQ,rm as xf,writeFile as LQ}from"node:fs/promises";import{dirname as IL,join as pT}from"node:path";import{ensureLoopbackProxyBypass as NQ,isHubProtocolCompatible as DQ}from"@cerebriline/shared";import{resolveClineDataDir as Iu,resolveClineDir as qqe}from"@cerebriline/shared/storage";var $Q="CLINE_HUB_DISCOVERY_PATH",FQ="CLINE_HUB_BUILD_ID",UQ="CLINE_HUB_BUILD_EPOCH_MS",BQ=30000,HQ=15000,SL=100;function WQ(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function jQ(e){return PQ("sha256").update(e).digest("hex").slice(0,12)}function qQ(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 CL(){return AL(32).toString("hex")}function xL(e){return new Promise((t)=>setTimeout(t,e))}function zQ(e){return`${e}.lock`}async function KQ(e){try{let t=JSON.parse(await RL(pT(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 uT(e){await xf(e,{recursive:!0,force:!0}).catch(()=>{return})}function eo(){let e=process.env[FQ]?.trim();if(e)return e;return"sdk-v1-34a535a13d156348559d06088ca1d67cf0890077ffb8eae5f4f7dc502bff2722".trim()||`source-${String(Oi.version)}`}function mT(){let e=Number(process.env[UQ]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792773013448)?1792773013448:void 0}function Fs(e,t=eo()){let n=DQ(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 _L(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function EL(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 GQ(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 Cu(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=_L(e.buildEpochMs),i=_L(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let s=EL(e.coreVersion),a=EL(t.coreVersion);if(s&&a){let d=GQ(s,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function Pu(){return{buildId:eo(),buildEpochMs:mT(),coreVersion:String(Oi.version)}}function Od(e,t){let n=t?.self??Pu(),r=Fs(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return Cu(n,e)<=0}function Us(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${jQ(e)}`,n=process.env[$Q]?.trim()||pT(Iu(),"locks","hub","owners",`${WQ(t)}.json`);return{ownerId:t,discoveryPath:n}}function Kqe(e=`hub-${Date.now().toString(36)}`){return Us(e)}async function qt(e){try{let t=JSON.parse(await RL(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 _f(e,t,n){await fT(e,async()=>{let r=IL(e);await hT(r,{recursive:!0});let o=`${e}.${process.pid}.${AL(6).toString("hex")}.tmp`,i;try{i=await TL(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 OQ(o,e);let s;try{s=await TL(r,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await xf(o,{force:!0}).catch(()=>{return}),s}})}async function Wo(e){await fT(e,async()=>{await xf(e,{force:!0}).catch(()=>{return})})}async function PL(e,t){return await fT(e,async()=>{if((await qt(e))?.hubId!==t)return!1;return await xf(e,{force:!0}),!0})}async function ML(e,t,n){let r=zQ(e);await hT(IL(r),{recursive:!0});let o=Date.now()+HQ;while(!0){try{await hT(r,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await KQ(r);if(!a){if(Date.now()>=o){await uT(r);continue}await xL(SL);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!qQ(a.pid)||d>BQ){await uT(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await xL(SL);continue}try{return await LQ(pT(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
323
323
|
`,"utf8"),await n()}finally{await uT(r)}}}function fT(e,t){return ML(`${e}.mutation`,"discovery mutation",t)}function Ef(e,t){return ML(e,"startup",t)}async function jo(e,t){NQ();try{let n=await fetch(t?.authToken?VQ(e):OL(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 OL(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function VQ(e){let t=new URL(OL(e));return t.pathname="/status",t.toString()}function Gqe(e){return MQ(e)}import{CLINE_HUB_DEV_PORT as XQ,CLINE_HUB_PORT as YQ,resolveClineBuildEnv as JQ}from"@cerebriline/shared";var QQ="CLINE_HUB_HOST",ZQ="CLINE_HUB_PORT",eZ="CLINE_HUB_PATHNAME",tZ="127.0.0.1",nZ=YQ,rZ="/hub";function LL(e){return JQ(e)==="development"?XQ:nZ}function oZ(e={}){return(e.env??process.env)[QQ]?.trim()||tZ}function Af(e={}){let n=(e.env??process.env)[ZQ]?.trim();if(!n)return LL(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return LL(e);return r}function iZ(e={}){return(e.env??process.env)[eZ]?.trim()||rZ}function Bs(e={},t={}){return{host:e.host??oZ(t),port:e.port??Af(t),pathname:e.pathname??iZ(t)}}import{join as sZ}from"node:path";var aZ="shared:cline",dZ="CLINE_HUB_DISCOVERY_PATH",lZ="hub-production";function eze(e){let t=Ms(e.trim());return Us(`workspace:${t||e.trim()}`)}function Ar(e=aZ){return Us(`${e}@${eo()}`)}function to(){return{ownerId:lZ,discoveryPath:process.env[dZ]?.trim()||sZ(Iu(),"locks","hub","production.json")}}var NL=15000,SZ=200,DL=3000,xZ=100,_Z=[100,250,500,1000,2000],EZ="--cline-hub-daemon",AZ=3,RZ=60000,wT=new Map,uze={resetRetireAttempts(){wT.clear()},resolveDaemonEntryArgs:WL};function IZ(e,t=Date.now()){let n=wT.get(e);if(!n||t-n.windowStartedAt>RZ)return wT.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=AZ}function CZ(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function PZ(){try{let e=wZ(Iu(),"logs","hub-daemon.log");return hZ(yZ(e),{recursive:!0}),{fd:pZ(e,"a"),logPath:e}}catch{return}}function HL(){return BL()==="production"?to():Ar()}function Mu(e){return Od(e)}function MZ(e){try{let t=JSON.parse(mZ(`${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 gT(e){try{fZ(`${e}.superseded`)}catch{}}function $L(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Ld(e,t){try{return await jo(e,{authToken:t})}catch{return}}async function FL(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Ld(e))?.url)return!0;await new Promise((o)=>setTimeout(o,xZ))}return!1}async function Nd(e,t){if(!IZ(e.url))return!1;await Hs(e.url,e.authToken,"retired by newer install").catch(()=>!1),await vT(e.url,e.authToken).catch(()=>!1);let n=await FL(e.url,DL);if(!n&&e.pid&&OZ(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await FL(e.url,DL)}if(n)await Wo(t).catch(()=>{return});return n}function OZ(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function bT(e){try{return(await $d(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function yT(e,t){if(Mu(e))return"reusable";let n=await Hs(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await bT(e)){if(n)await Hs(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Nd(e,t);if(!r&&n)await Hs(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function LZ(e){if(BL()!=="production")return;let t=Ar();if(t.discoveryPath===e.discoveryPath)return;let n=await qt(t.discoveryPath);if(n?.url)await Nd(n,t.discoveryPath);else await Wo(t.discoveryPath).catch(()=>{return})}function NZ(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return bZ(new URL(`./entry.${e}`,import.meta.url))}function WL(e,t){if(kZ(e))return[EZ];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function DZ(e,t){let n=NZ(),r=process.execPath?.trim();if(!r)throw Error("unable to resolve runtime executable for hub daemon");let o=gZ(r).toLowerCase().includes("bun"),i=WL(n,o);return{launcher:r,args:[...i,"--cwd",e,...CZ(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...TZ(process.env),CLINE_NO_INTERACTIVE:"1",[vZ]:"1"}}}function $Z(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 FZ(e,t={}){if(UL())return;let n=DZ(e,t),r=PZ();try{cZ(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)uZ(r.fd)}}async function UZ(e,t={}){for(let n=0;;n++)try{FZ(e,t);return}catch(r){let o=_Z[n];if(!$Z(r)||o===void 0)throw r;await new Promise((i)=>setTimeout(i,o))}}function hze(e,t={}){if(UL())return;Ou(e,t).catch(()=>{})}async function BZ(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)Dd(m.url,m.authToken);else jL(m.url,m.authToken);return m};await LZ(e).catch(()=>{return});let a=await qt(e.discoveryPath),d=a?.url?void 0:MZ(e.discoveryPath),l=!1;if(a?.url){let m=a.authToken;if(!m)l=!0,await Nd(a,e.discoveryPath);else{let f=await Ld(a.url,m);if(f?.url&&Mu(f)&&await ir(f.url,{authToken:m}))return gT(e.discoveryPath),s({url:f.url,authToken:m});if(f?.url){if(await yT({...f,authToken:m},e.discoveryPath)==="deferred_busy"&&await ir(f.url,{authToken:m}))return s({url:f.url,authToken:m})}else await Wo(e.discoveryPath).catch(()=>{return})}}let c=await Ld(i);if(c?.url){let m=$L(c,a??d,i);if(Mu(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 ir(c.url,{authToken:w}))continue;let x={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 _f(e.discoveryPath,x)}catch{}return gT(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 yT(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 ir(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 UZ(t,{...h,manageConnectors:n.manageConnectors});let p=Date.now()+NL;while(Date.now()<p){let m=await qt(e.discoveryPath);if(m?.url&&m.authToken){let g=await Ld(m.url,m.authToken);if(g?.url&&Mu(g)&&await ir(g.url,{authToken:m.authToken}))return gT(e.discoveryPath),s({url:g.url,authToken:m.authToken})}let f=await Ld(i);if(f?.url&&!Mu(f)){let g=$L(f,m??d,i),y=await yT(g,e.discoveryPath);if(y==="deferred_busy"&&m?.authToken&&await ir(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,SZ))}throw Error(`Timed out after ${NL}ms waiting for detached hub startup.`)}async function Ou(e,t={}){let n=HL();return await Ef(n.discoveryPath,async()=>BZ(n,e,t))}var HZ=5000,WZ=500;async function pze(e={}){let t=HL(),n=e.workspaceRoot??process.cwd(),r=await qt(t.discoveryPath),o=r?.url?await Ld(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await Ou(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(Cu(Pu(),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??HZ),l;for(;;){try{if(l=(await $d(i.url,i.authToken)).activeSessionCount,l===0)break}catch{}if(Date.now()>=d)break;await new Promise((h)=>setTimeout(h,WZ))}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 Nd(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 Ou(n),activeSessionCount:l??0}}function ET(){return zZ()==="production"?to():Ar()}function VZ(){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 VL(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 VL(e.data);return String(e)}function XZ(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 qL(e){let t=e,n=XZ(t.reason);return new dn("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:TT,{closeCode:t.code,closeReason:n||void 0})}function zL(e,t){if(e instanceof dn)return e;if(e instanceof Error)return new dn("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new dn("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 dn("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new dn("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 kT="*",Rf=8000,YZ="cline-hub-auth.",AT=new Map,XL=new Set,JZ=3000,QZ=3000,ZZ=100,TT="Hub connection closed",eee=250,tee=5000,KL=0.5;class dn extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function nee(e){return e instanceof dn}class If extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function Tze(e,t){return e instanceof If&&e.code==="hub_command_timeout"&&(t===void 0||e.command===t)}function RT(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let r=Pf(e.toString());return r?AT.get(r):void 0}function ree(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 Pf(e){if(!ree(e))return;let t=new URL(Cf(e));return t.search="",t.hash="",t.toString()}function ST(e){let t=Pf(e);return!!t&&XL.has(t)}function Dd(e,t){let n=Pf(e);if(n){if(XL.add(n),t?.trim())AT.set(n,t)}return e}function jL(e,t){let n=Pf(e);if(n&&t?.trim())AT.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 dn("hub_connection_closed",TT);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()||RT(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=zL(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 dn("hub_connect_timeout",`Timed out resolving hub connection headers after ${Rf}ms`))},Rf)})])}catch(l){let c=l instanceof dn?l:new dn("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 dn("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let i=o?new GZ(e.toString(),{headers:{...o}}):new(VZ())(e.toString(),t?[`${YZ}${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 dn("hub_connect_timeout",`Timed out connecting to hub after ${Rf}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)},Rf);i.addEventListener("open",()=>{if(c)return;c=!0,clearTimeout(u),d()}),i.addEventListener("error",(h)=>{if(c)return;c=!0,clearTimeout(u);let p=zL(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:qL(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(VL(d)))}),i.addEventListener("close",(d)=>{if(this.socket!==i)return;if(!s)this.lastCloseError=qL(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=jZ("hubreq_");r?.onDispatch?.(i);let s=KZ(e,r?.timeoutMs),a=new Promise((l,c)=>{let u=s===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;c(new If(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===Tf){let l=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Md(l,d.error.message)}throw new If(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!ST(this.currentUrl)||!nee(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await _T({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(eee*2**this.reconnectAttempt,tee),t=Math.round(e*(1-KL)+Math.random()*e*KL);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(!ST(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await _T({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 dn("hub_connection_closed",TT);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 dn("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??kT}subscriptionSessionIdFromKey(e){return e===kT?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[kT,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 Cf(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 ir(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 xT(e,t){let n=Cf(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&&!Od(r))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!qZ(r).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await ir(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}async function oee(e){let t=Date.now()+QZ;while(Date.now()<t){if(!(await jo(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,ZZ))}return!1}function iee(e,t){try{return Cf(e)===Cf(t)}catch{return!1}}function YL(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 Sze(e){return YL(e).activeSessionCount>0}async function $d(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:JZ});return YL(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function JL(e,t,n){try{return(await $d(e,t,n)).activeSessionCount===0}catch{return!1}}async function see(e,t){let n=`${e.discoveryPath}.superseded`,r=await qt(n);if(!r?.url||!r.authToken)return;let o=await xT(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await JL(o.url,r.authToken,t))return;return Dd(o.url,r.authToken)}async function aee(e={}){if(e.endpoint?.trim()){let o=await xT(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=ET(),n=await qt(t.discoveryPath);if(!n?.url)return await see(t,e);let r=await xT(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return Dd(r.url,n.authToken);if(r.status==="protocol_mismatch")await Wo(t.discoveryPath).catch(()=>{return});return}async function _T(e={}){let t=await aee(e);if(t&&await ir(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Ou(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function Hs(e,t,n,r){GL();let o=new URL(e),i=t?.trim()||RT(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 vT(e,t){GL();let n=new URL(e),r=t?.trim()||RT(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 dee(e=ET()){let t=await qt(e.discoveryPath);if(!t?.url)return!1;try{if(await vT(t.url,t.authToken))return!0}catch{}return!1}async function xze(e){if(!ST(e.url))return;let t=ET(),n=await qt(t.discoveryPath);if(!n?.url||!iee(n.url,e.url))return;if(!await JL(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await dee())return;if(!await oee(n.url))return;return await Wo(t.discoveryPath).catch(()=>{return}),await _T({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveClineBuildEnv as lee}from"@cerebriline/shared";function cee(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 uee="cline-hub-auth.";function hee(e){return e.host!==void 0||e.port!==void 0||e.pathname!==void 0}function pee(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 QL(){return lee()==="production"?to():Ar()}async function mee(e){let t=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),t)return t;let n=QL(),r=await qt(n.discoveryPath);if(r?.url&&pee(e.toString(),r.url))return r.authToken;return}async function fee(e={}){let t=Bs(e);if(!hee(e)){let n=QL(),r=await qt(n.discoveryPath);if(r?.url)return r.url}return qo(t.host,t.port,t.pathname)}async function ZL(e){return await new Promise((t,n)=>{(async()=>{let r=new URL(e),o=await mee(r);r.hash="";let i=new WebSocket(r.toString(),o?[`${uee}${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(cee(d,e))})})().catch(n)})}async function Cze(e){try{return(await ZL(e)).close(),!0}catch{return!1}}async function Pze(e,t){let n=await fee(e),r=await ZL(n);try{return await r.send({version:t.version??"v1",clientId:t.clientId??"hub-client",...t})}finally{r.close()}}import{existsSync as gee}from"node:fs";import{isHubDaemonProcess as yee,resolveClineBuildEnv as wee}from"@cerebriline/shared";var bee=1e4,vee="CLINE_HUB_BUILD_WATCH_INTERVAL_MS";function kee(){let e=Number(process.env[vee]);return Number.isFinite(e)&&e>0?e:bee}async function Tee(e,t){try{let n=await $d(e.url,t);return{...e,activeSessionCount:n.activeSessionCount,participantClientCount:n.participantClientCount}}catch{return e}}function See(){return wee()==="production"?to():Ar()}function xee(e){try{return gee(`${e}.lock`)}catch{return!1}}async function _ee(){let e=See();if(xee(e.discoveryPath))return;let t=await qt(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=Pu();if(s.coreVersion&&n.coreVersion&&s.coreVersion===n.coreVersion)return;if(Cu(s,n)>0)return await Tee(i("outdated_hub"),t.authToken);return i("build_mismatch")}function Fze(e){if(yee()||process.env.CLINE_HUB_PORT?.trim())return()=>{};let t=e.intervalMs??kee(),n,r,o=!1,i=setInterval(()=>{if(o)return;o=!0,_ee().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 IT(e){return e?JSON.parse(JSON.stringify(e)):{}}function Mf(e){let t=e?.session&&typeof e.session==="object"?e.session:void 0;if(!t)return;let n=t.metadata&&typeof t.metadata==="object"?IT(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 eN(e,t){return e.error?.message??`hub command failed: ${t}`}function Eee(e){let t=IT(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 tN(e){let t=e?.sessionId;return typeof t==="string"&&t.trim()?t.trim():void 0}function Aee(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 Ree(e){let t=IT(e.payload);if(e.event==="schedule.execution_completed")return{sessionId:e.sessionId?.trim()||tN(t)||"",eventType:"schedule.execution.completed",payload:t};if(e.event==="schedule.execution_failed")return{sessionId:e.sessionId?.trim()||tN(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:Eee(e.payload)};case"run.completed":return{sessionId:n,eventType:"runtime.chat.completed",payload:t};default:return}}class Iee{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=Mf(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(Sf(n))return;throw n}return Mf(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(eN(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(eN(o,"session.restore"));let i=Mf(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=Aee(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)=>Mf({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=Ree(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 Cee{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 P1e}from"@cerebriline/llms";import{existsSync as BUe,readdirSync as HUe}from"node:fs";import{readFile as WUe}from"node:fs/promises";import{homedir as jUe}from"node:os";import{isAbsolute as mX,join as Ei,resolve as l0}from"node:path";import{onXollamaSideCall as qUe,releasePolykvSwarmsOf as cX}from"@cerebriline/llms";import{applyPromptTemplateToTools as zUe,captureSdkError as Sr,createSessionId as KUe,isLikelyAuthError as GUe,normalizeUserInput as VUe}from"@cerebriline/shared";import{setHomeDirIfUnset as XUe}from"@cerebriline/shared/storage";import{decodeJwtPayload as _te,getClineEnvironmentConfig as SN}from"@cerebriline/shared";import{decodeJwtPayload as $ee,getClineEnvironmentConfig as Fee}from"@cerebriline/shared";import{createHash as Pee}from"node:crypto";var Mee;function jn(e){if(typeof e!=="string"||e.length===0)return"unset";return Pee("sha256").update(e).digest("hex").slice(0,8)}function ct(e){try{Mee?.debug(e)}catch{}}function Oee(){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??Lee,i=Oee(),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 x={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(x.error){y.statusCode=400,y.end(`Authentication failed: ${x.error}`),u(),c(x);return}if(!x.code){y.statusCode=400,y.end("Missing authorization code");return}if(e.expectedState&&x.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(x)}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 Lee=`<!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 fw(e){let t=Os(e.metadata)??{},n=e.title!==void 0?hc(e.title):nF(e.prompt);if(n)t.title=n;return Object.keys(t).length>0?t:void 0}function rF(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($m(e.sessionId))return{agent:"subagent",sessionId:e.sessionId,taskType:"subagent_task",origin:n};return{agent:"lead",sessionId:e.sessionId,origin:n}}function oF(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:mE(e.messages),...e.systemPrompt?{system_prompt:e.systemPrompt}:{}}}function NZ(e,t,n){Y2e(J2e(e),{recursive:!0}),X2e(e,`${JSON.stringify(oF({updatedAt:t,context:n,messages:[]}),null,2)}
|
|
2410
2410
|
`,"utf8")}function DZ(e,t){return Ir.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 $Z(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 iF}from"node:fs";import{readFile as nze}from"node:fs/promises";import{join as rze}from"node:path";class gw{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 FZ(e,t,n){let r=e?.trim();if(r&&iF(r))return r;let o=n?.trim();if(o){let i=rze(o,t,`${t}.messages.json`);if(iF(i))return i}return r||void 0}async function fc(e){let t=e?.trim();if(!t||!iF(t))return[];try{let n=(await nze(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 sF(e){return e?{...e}:void 0}async function UZ(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 yw(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function ro(e){let t=yw(e);if(!t)return;return t.toLowerCase()==="unknown"?void 0:t}function fE(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function dze(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return{...e}}function lF(e){let t=e??200;return Number.isFinite(t)?Math.max(0,Math.floor(t)):200}var aF=2000;function lze(e){if(e===0)return 0;return Math.min(Math.max(e*2,20),aF)}function cze(e){return e.isSubagent!==!0&&!yw(e.parentSessionId)}function uze(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 cF(e){let t=mc(e.session_id)?.rootSessionId??$m(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 pze(e){let t=lF(e);if(t===0)return[];let n=jZ(),o=(await oze(n,{withFileTypes:!0}).catch(()=>[])).filter((s)=>s.isDirectory()).map((s)=>({entry:s,recency:uze(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=WZ(n,a,`${a}.json`),l=await HZ(d,"utf8").catch(()=>{return});if(!l)return;let c;try{c=JSON.parse(l)}catch{return}let u=Ir.safeParse(c);if(!u.success)return;return cF(u.data)}))).filter((s)=>Boolean(s)).sort((s,a)=>a.startedAt.localeCompare(s.startedAt)).slice(0,t)}async function mze(e,t,n){let r=lF(t);if(r===0)return await e.listSessions(0),[];if(n.includeSubagents)return(await e.listSessions(r)).slice(0,r);let o=lze(r);for(;;){let i=await e.listSessions(o,{rootOnly:!0}),s=i.filter(cze);if(s.length>=r||i.length<o||o>=aF)return s.slice(0,r);o=Math.min(o*2,aF)}}function hze(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 BZ(e){return e.replace(/\s+/g," ").trim()}function fze(e,t){if(e.length<=t)return e;return`${e.slice(0,Math.max(0,t-3)).trimEnd()}...`}function gze(e){for(let t of["user","assistant"])for(let n of e){if(n.role!==t)continue;let r=BZ(hze(n.content));if(!r)continue;let o=t==="user"?BZ(sze(r)):r,i=aze(o.split(`
|
|
2412
|
-
`)[0]??o);return fze(i,50)}return}function yze(e){let t=0;for(let n of e)t+=fE(n.metrics?.cost)??0;return t}function wze(e){let t,n;for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(!t)t=ro(o.modelInfo?.provider);if(!n)n=ro(o.modelInfo?.id);if(t&&n)break}return{provider:t,model:n}}function bze(e){return ro(e?.provider)??ro(e?.provider&&typeof e.provider==="object"&&!Array.isArray(e.provider)?e.provider.id:void 0)}function vze(e){return ro(e?.model)??ro(e?.model&&typeof e.model==="object"&&!Array.isArray(e.model)?e.model.id:void 0)}function dF(e,t){let n=dze(e.metadata),r=yw(t?.title)??yw(n?.title),o=fE(t?.totalCost)??fE(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:ro(t?.provider)??ro(e.provider)??bze(n)??"",model:ro(t?.model)??ro(e.model)??vze(n)??"",metadata:i}}function kze(e){let t=e.content;if(!Array.isArray(t))return!1;return t.some((n)=>!!n&&typeof n==="object"&&n.type==="tool-call")}function Sze(e,t){if(e.status!=="running"||e.interactive!==!0)return!1;let n=t.at(-1);return n?.role==="assistant"&&!kze(n)}async function Tze(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 Sze(n,r)?{...n,status:"idle"}:n}))}async function xze(e,t){return await Promise.all(t.map(async(n)=>{let r=dF(n),o=Boolean(yw(r.metadata?.title)),i=Boolean(ro(r.provider)),s=Boolean(ro(r.model)),a=fE(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=wze(l),u=yze(l);return dF(n,{title:o?void 0:gze(l),provider:i?void 0:c.provider,model:s?void 0:c.model,totalCost:d||u<=0?void 0:u})}))}async function uF(e,t={}){let n=lF(t.limit),r=t.includeSubagents===!0,o=await mze(e,n,{includeSubagents:r}),i=t.includeManifestFallback===!0&&o.length<n?await pze(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 Tze(e,a)).map(Eze));if(t.hydrate===!1)return d.map((l)=>dF(l));return await xze(e,d)}var _ze="stale_session_reconciler";async function Eze(e){let t=e.metadata;if(t?.terminal_marker_source!==_ze)return e;let n=e.endedAt??void 0;if(n&&n===t.terminal_marker_at&&e.messagesPath){let r=await ize(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 Aze(e){let t=e.trim();if(!t)return;let n=WZ(jZ(),t,`${t}.json`),r=await HZ(n,"utf8").catch(()=>{return});if(!r)return;try{let o=Ir.safeParse(JSON.parse(r));return o.success?o.data.messages_path:void 0}catch{return}}async function Rze(e,t={}){let n=new Map;return await uF({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(hw)},readSessionMessages:async(o)=>{let i=n.get(o)?.messagesPath??await Aze(o);return await fc(i)}},t)}import{captureSdkError as nde}from"@cerebriline/shared";import{createSessionId as HGe,ensureLoopbackProxyBypass as gee,isHubProtocolCompatible as WGe,resolveClineBuildEnv as jGe,resolveHubCommandTimeoutMs as qGe}from"@cerebriline/shared";import zGe from"ws";import{spawn as dGe}from"node:child_process";import{closeSync as lGe,mkdirSync as cGe,openSync as uGe,readFileSync as pGe,unlinkSync as mGe}from"node:fs";import{basename as hGe,dirname as fGe,join as gGe}from"node:path";import{fileURLToPath as yGe}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as wGe,isBunEmbeddedModulePath as bGe,isHubDaemonProcess as aee,resolveClineBuildEnv as dee,withResolvedClineBuildEnv as vGe}from"@cerebriline/shared";import{createHash as Cze,randomBytes as YZ}from"node:crypto";import{existsSync as Ize}from"node:fs";import{mkdir as mF,open as qZ,readFile as XZ,rename as Pze,rm as gE,writeFile as Mze}from"node:fs/promises";import{dirname as JZ,join as hF}from"node:path";import{ensureLoopbackProxyBypass as Oze,isHubProtocolCompatible as Lze}from"@cerebriline/shared";import{resolveClineDataDir as ww,resolveClineDir as RIt}from"@cerebriline/shared/storage";var Nze="CLINE_HUB_DISCOVERY_PATH",Dze="CLINE_HUB_BUILD_ID",$ze="CLINE_HUB_BUILD_EPOCH_MS",Fze=30000,Uze=15000,zZ=100;function Bze(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Hze(e){return Cze("sha256").update(e).digest("hex").slice(0,12)}function Wze(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 YZ(32).toString("hex")}function GZ(e){return new Promise((t)=>setTimeout(t,e))}function jze(e){return`${e}.lock`}async function qze(e){try{let t=JSON.parse(await XZ(hF(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 pF(e){await gE(e,{recursive:!0,force:!0}).catch(()=>{return})}function Ri(){let e=process.env[Dze]?.trim();if(e)return e;return"sdk-v1-
|
|
2412
|
+
`)[0]??o);return fze(i,50)}return}function yze(e){let t=0;for(let n of e)t+=fE(n.metrics?.cost)??0;return t}function wze(e){let t,n;for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(!t)t=ro(o.modelInfo?.provider);if(!n)n=ro(o.modelInfo?.id);if(t&&n)break}return{provider:t,model:n}}function bze(e){return ro(e?.provider)??ro(e?.provider&&typeof e.provider==="object"&&!Array.isArray(e.provider)?e.provider.id:void 0)}function vze(e){return ro(e?.model)??ro(e?.model&&typeof e.model==="object"&&!Array.isArray(e.model)?e.model.id:void 0)}function dF(e,t){let n=dze(e.metadata),r=yw(t?.title)??yw(n?.title),o=fE(t?.totalCost)??fE(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:ro(t?.provider)??ro(e.provider)??bze(n)??"",model:ro(t?.model)??ro(e.model)??vze(n)??"",metadata:i}}function kze(e){let t=e.content;if(!Array.isArray(t))return!1;return t.some((n)=>!!n&&typeof n==="object"&&n.type==="tool-call")}function Sze(e,t){if(e.status!=="running"||e.interactive!==!0)return!1;let n=t.at(-1);return n?.role==="assistant"&&!kze(n)}async function Tze(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 Sze(n,r)?{...n,status:"idle"}:n}))}async function xze(e,t){return await Promise.all(t.map(async(n)=>{let r=dF(n),o=Boolean(yw(r.metadata?.title)),i=Boolean(ro(r.provider)),s=Boolean(ro(r.model)),a=fE(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=wze(l),u=yze(l);return dF(n,{title:o?void 0:gze(l),provider:i?void 0:c.provider,model:s?void 0:c.model,totalCost:d||u<=0?void 0:u})}))}async function uF(e,t={}){let n=lF(t.limit),r=t.includeSubagents===!0,o=await mze(e,n,{includeSubagents:r}),i=t.includeManifestFallback===!0&&o.length<n?await pze(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 Tze(e,a)).map(Eze));if(t.hydrate===!1)return d.map((l)=>dF(l));return await xze(e,d)}var _ze="stale_session_reconciler";async function Eze(e){let t=e.metadata;if(t?.terminal_marker_source!==_ze)return e;let n=e.endedAt??void 0;if(n&&n===t.terminal_marker_at&&e.messagesPath){let r=await ize(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 Aze(e){let t=e.trim();if(!t)return;let n=WZ(jZ(),t,`${t}.json`),r=await HZ(n,"utf8").catch(()=>{return});if(!r)return;try{let o=Ir.safeParse(JSON.parse(r));return o.success?o.data.messages_path:void 0}catch{return}}async function Rze(e,t={}){let n=new Map;return await uF({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(hw)},readSessionMessages:async(o)=>{let i=n.get(o)?.messagesPath??await Aze(o);return await fc(i)}},t)}import{captureSdkError as nde}from"@cerebriline/shared";import{createSessionId as HGe,ensureLoopbackProxyBypass as gee,isHubProtocolCompatible as WGe,resolveClineBuildEnv as jGe,resolveHubCommandTimeoutMs as qGe}from"@cerebriline/shared";import zGe from"ws";import{spawn as dGe}from"node:child_process";import{closeSync as lGe,mkdirSync as cGe,openSync as uGe,readFileSync as pGe,unlinkSync as mGe}from"node:fs";import{basename as hGe,dirname as fGe,join as gGe}from"node:path";import{fileURLToPath as yGe}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as wGe,isBunEmbeddedModulePath as bGe,isHubDaemonProcess as aee,resolveClineBuildEnv as dee,withResolvedClineBuildEnv as vGe}from"@cerebriline/shared";import{createHash as Cze,randomBytes as YZ}from"node:crypto";import{existsSync as Ize}from"node:fs";import{mkdir as mF,open as qZ,readFile as XZ,rename as Pze,rm as gE,writeFile as Mze}from"node:fs/promises";import{dirname as JZ,join as hF}from"node:path";import{ensureLoopbackProxyBypass as Oze,isHubProtocolCompatible as Lze}from"@cerebriline/shared";import{resolveClineDataDir as ww,resolveClineDir as RIt}from"@cerebriline/shared/storage";var Nze="CLINE_HUB_DISCOVERY_PATH",Dze="CLINE_HUB_BUILD_ID",$ze="CLINE_HUB_BUILD_EPOCH_MS",Fze=30000,Uze=15000,zZ=100;function Bze(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Hze(e){return Cze("sha256").update(e).digest("hex").slice(0,12)}function Wze(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 YZ(32).toString("hex")}function GZ(e){return new Promise((t)=>setTimeout(t,e))}function jze(e){return`${e}.lock`}async function qze(e){try{let t=JSON.parse(await XZ(hF(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 pF(e){await gE(e,{recursive:!0,force:!0}).catch(()=>{return})}function Ri(){let e=process.env[Dze]?.trim();if(e)return e;return"sdk-v1-34a535a13d156348559d06088ca1d67cf0890077ffb8eae5f4f7dc502bff2722".trim()||`source-${String(Oa.version)}`}function fF(){let e=Number(process.env[$ze]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792773013448)?1792773013448:void 0}function gc(e,t=Ri()){let n=Lze(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 KZ(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function VZ(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 zze(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 bw(e,t){let n=e.buildId?.trim(),r=t.buildId?.trim();if(n&&r&&n===r)return 0;let o=KZ(e.buildEpochMs),i=KZ(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let s=VZ(e.coreVersion),a=VZ(t.coreVersion);if(s&&a){let d=zze(s,a);if(d!==0)return d}if(n&&r&&n!==r)return n<r?-1:1;return 0}function vw(){return{buildId:Ri(),buildEpochMs:fF(),coreVersion:String(Oa.version)}}function Fm(e,t){let n=t?.self??vw(),r=gc(e,n.buildId??"");if(r.compatible)return!0;if(r.reason!=="build_mismatch"&&r.reason!=="missing_build")return!1;return bw(n,e)<=0}function yc(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Hze(e)}`,n=process.env[Nze]?.trim()||hF(ww(),"locks","hub","owners",`${Bze(t)}.json`);return{ownerId:t,discoveryPath:n}}function IIt(e=`hub-${Date.now().toString(36)}`){return yc(e)}async function wn(e){try{let t=JSON.parse(await XZ(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 yE(e,t,n){await gF(e,async()=>{let r=JZ(e);await mF(r,{recursive:!0});let o=`${e}.${process.pid}.${YZ(6).toString("hex")}.tmp`,i;try{i=await qZ(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 Pze(o,e);let s;try{s=await qZ(r,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await gE(o,{force:!0}).catch(()=>{return}),s}})}async function Ls(e){await gF(e,async()=>{await gE(e,{force:!0}).catch(()=>{return})})}async function ZZ(e,t){return await gF(e,async()=>{if((await wn(e))?.hubId!==t)return!1;return await gE(e,{force:!0}),!0})}async function eee(e,t,n){let r=jze(e);await mF(JZ(r),{recursive:!0});let o=Date.now()+Uze;while(!0){try{await mF(r,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await qze(r);if(!a){if(Date.now()>=o){await pF(r);continue}await GZ(zZ);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!Wze(a.pid)||d>Fze){await pF(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await GZ(zZ);continue}try{return await Mze(hF(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
2414
2414
|
`,"utf8"),await n()}finally{await pF(r)}}}function gF(e,t){return eee(`${e}.mutation`,"discovery mutation",t)}function wE(e,t){return eee(e,"startup",t)}async function Ns(e,t){Oze();try{let n=await fetch(t?.authToken?Gze(e):tee(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 tee(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function Gze(e){let t=new URL(tee(e));return t.pathname="/status",t.toString()}function PIt(e){return Ize(e)}import{CLINE_HUB_DEV_PORT as Kze,CLINE_HUB_PORT as Vze,resolveClineBuildEnv as Yze}from"@cerebriline/shared";var Xze="CLINE_HUB_HOST",Jze="CLINE_HUB_PORT",Qze="CLINE_HUB_PATHNAME",Zze="127.0.0.1",eGe=Vze,tGe="/hub";function nee(e){return Yze(e)==="development"?Kze:eGe}function nGe(e={}){return(e.env??process.env)[Xze]?.trim()||Zze}function bE(e={}){let n=(e.env??process.env)[Jze]?.trim();if(!n)return nee(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return nee(e);return r}function rGe(e={}){return(e.env??process.env)[Qze]?.trim()||tGe}function wc(e={},t={}){return{host:e.host??nGe(t),port:e.port??bE(t),pathname:e.pathname??rGe(t)}}import{join as oGe}from"node:path";var iGe="shared:cline",sGe="CLINE_HUB_DISCOVERY_PATH",aGe="hub-production";function FIt(e){let t=nd(e.trim());return yc(`workspace:${t||e.trim()}`)}function No(e=iGe){return yc(`${e}@${Ri()}`)}function Ci(){return{ownerId:aGe,discoveryPath:process.env[sGe]?.trim()||oGe(ww(),"locks","hub","production.json")}}var ree=15000,kGe=200,oee=3000,SGe=100,TGe=[100,250,500,1000,2000],xGe="--cline-hub-daemon",_Ge=3,EGe=60000,bF=new Map,YIt={resetRetireAttempts(){bF.clear()},resolveDaemonEntryArgs:cee};function AGe(e,t=Date.now()){let n=bF.get(e);if(!n||t-n.windowStartedAt>EGe)return bF.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=_Ge}function RGe(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function CGe(){try{let e=gGe(ww(),"logs","hub-daemon.log");return cGe(fGe(e),{recursive:!0}),{fd:uGe(e,"a"),logPath:e}}catch{return}}function lee(){return dee()==="production"?Ci():No()}function kw(e){return Fm(e)}function IGe(e){try{let t=JSON.parse(pGe(`${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 yF(e){try{mGe(`${e}.superseded`)}catch{}}function iee(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function Um(e,t){try{return await Ns(e,{authToken:t})}catch{return}}async function see(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await Um(e))?.url)return!0;await new Promise((o)=>setTimeout(o,SGe))}return!1}async function Bm(e,t){if(!AGe(e.url))return!1;await bc(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Tw(e.url,e.authToken).catch(()=>!1);let n=await see(e.url,oee);if(!n&&e.pid&&PGe(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await see(e.url,oee)}if(n)await Ls(t).catch(()=>{return});return n}function PGe(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function vF(e){try{return(await Wm(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function wF(e,t){if(kw(e))return"reusable";let n=await bc(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await vF(e)){if(n)await bc(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let r=await Bm(e,t);if(!r&&n)await bc(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return r?"retired":"failed"}async function MGe(e){if(dee()!=="production")return;let t=No();if(t.discoveryPath===e.discoveryPath)return;let n=await wn(t.discoveryPath);if(n?.url)await Bm(n,t.discoveryPath);else await Ls(t.discoveryPath).catch(()=>{return})}function OGe(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return yGe(new URL(`./entry.${e}`,import.meta.url))}function cee(e,t){if(bGe(e))return[xGe];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function LGe(e,t){let n=OGe(),r=process.execPath?.trim();if(!r)throw Error("unable to resolve runtime executable for hub daemon");let o=hGe(r).toLowerCase().includes("bun"),i=cee(n,o);return{launcher:r,args:[...i,"--cwd",e,...RGe(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...vGe(process.env),CLINE_NO_INTERACTIVE:"1",[wGe]:"1"}}}function NGe(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 DGe(e,t={}){if(aee())return;let n=LGe(e,t),r=CGe();try{dGe(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)lGe(r.fd)}}async function $Ge(e,t={}){for(let n=0;;n++)try{DGe(e,t);return}catch(r){let o=TGe[n];if(!NGe(r)||o===void 0)throw r;await new Promise((i)=>setTimeout(i,o))}}function uee(e,t={}){if(aee())return;Sw(e,t).catch(()=>{})}async function FGe(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)Hm(h.url,h.authToken);else pee(h.url,h.authToken);return h};await MGe(e).catch(()=>{return});let a=await wn(e.discoveryPath),d=a?.url?void 0:IGe(e.discoveryPath),l=!1;if(a?.url){let h=a.authToken;if(!h)l=!0,await Bm(a,e.discoveryPath);else{let f=await Um(a.url,h);if(f?.url&&kw(f)&&await oo(f.url,{authToken:h}))return yF(e.discoveryPath),s({url:f.url,authToken:h});if(f?.url){if(await wF({...f,authToken:h},e.discoveryPath)==="deferred_busy"&&await oo(f.url,{authToken:h}))return s({url:f.url,authToken:h})}else await Ls(e.discoveryPath).catch(()=>{return})}}let c=await Um(i);if(c?.url){let h=iee(c,a??d,i);if(kw(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 oo(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 yE(e.discoveryPath,k)}catch{}return yF(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 wF(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 oo(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 $Ge(t,{...p,manageConnectors:n.manageConnectors});let m=Date.now()+ree;while(Date.now()<m){let h=await wn(e.discoveryPath);if(h?.url&&h.authToken){let y=await Um(h.url,h.authToken);if(y?.url&&kw(y)&&await oo(y.url,{authToken:h.authToken}))return yF(e.discoveryPath),s({url:y.url,authToken:h.authToken})}let f=await Um(i);if(f?.url&&!kw(f)){let y=iee(f,h??d,i),g=await wF(y,e.discoveryPath);if(g==="deferred_busy"&&h?.authToken&&await oo(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,kGe))}throw Error(`Timed out after ${ree}ms waiting for detached hub startup.`)}async function Sw(e,t={}){let n=lee();return await wE(n.discoveryPath,async()=>FGe(n,e,t))}var UGe=5000,BGe=500;async function XIt(e={}){let t=lee(),n=e.workspaceRoot??process.cwd(),r=await wn(t.discoveryPath),o=r?.url?await Um(r.url,r.authToken):void 0;if(!o?.url)return{outcome:"started",...await Sw(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(bw(vw(),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??UGe),l;for(;;){try{if(l=(await Wm(i.url,i.authToken)).activeSessionCount,l===0)break}catch{}if(Date.now()>=d)break;await new Promise((p)=>setTimeout(p,BGe))}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 Bm(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 Sw(n),activeSessionCount:l??0}}function _F(){return jGe()==="production"?Ci():No()}function GGe(){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 yee(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 yee(e.data);return String(e)}function KGe(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 mee(e){let t=e,n=KGe(t.reason);return new Fn("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:SF,{closeCode:t.code,closeReason:n||void 0})}function hee(e,t){if(e instanceof Fn)return e;if(e instanceof Error)return new Fn("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new Fn("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 Fn("hub_connect_failed",n);let r=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new Fn("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 kF="*",vE=8000,VGe="cline-hub-auth.",EF=new Map,wee=new Set,YGe=3000,XGe=3000,JGe=100,SF="Hub connection closed",QGe=250,ZGe=5000,fee=0.5;class Fn extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function eKe(e){return e instanceof Fn}class kE extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function bee(e,t){return e instanceof kE&&e.code==="hub_command_timeout"&&(t===void 0||e.command===t)}function AF(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let r=SE(e.toString());return r?EF.get(r):void 0}function tKe(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 SE(e){if(!tKe(e))return;let t=new URL(jm(e));return t.search="",t.hash="",t.toString()}function TF(e){let t=SE(e);return!!t&&wee.has(t)}function Hm(e,t){let n=SE(e);if(n){if(wee.add(n),t?.trim())EF.set(n,t)}return e}function pee(e,t){let n=SE(e);if(n&&t?.trim())EF.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 Fn("hub_connection_closed",SF);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()||AF(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=hee(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 Fn("hub_connect_timeout",`Timed out resolving hub connection headers after ${vE}ms`))},vE)})])}catch(l){let c=l instanceof Fn?l:new Fn("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 Fn("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let i=o?new zGe(e.toString(),{headers:{...o}}):new(GGe())(e.toString(),t?[`${VGe}${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 Fn("hub_connect_timeout",`Timed out connecting to hub after ${vE}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)},vE);i.addEventListener("open",()=>{if(c)return;c=!0,clearTimeout(u),d()}),i.addEventListener("error",(p)=>{if(c)return;c=!0,clearTimeout(u);let m=hee(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:mee(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(yee(d)))}),i.addEventListener("close",(d)=>{if(this.socket!==i)return;if(!s)this.lastCloseError=mee(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=HGe("hubreq_");r?.onDispatch?.(i);let s=qGe(e,r?.timeoutMs),a=new Promise((l,c)=>{let u=s===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;c(new kE(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===rw){let l=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new dc(l,d.error.message)}throw new kE(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!TF(this.currentUrl)||!eKe(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await xw({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(QGe*2**this.reconnectAttempt,ZGe),t=Math.round(e*(1-fee)+Math.random()*e*fee);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(!TF(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await xw({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 Fn("hub_connection_closed",SF);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 Fn("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??kF}subscriptionSessionIdFromKey(e){return e===kF?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[kF,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 jm(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 oo(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 xF(e,t){let n=jm(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&&!Fm(r))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!WGe(r).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await oo(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}async function nKe(e){let t=Date.now()+XGe;while(Date.now()<t){if(!(await Ns(e).catch(()=>{return}))?.url)return!0;await new Promise((r)=>setTimeout(r,JGe))}return!1}function rKe(e,t){try{return jm(e)===jm(t)}catch{return!1}}function vee(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 iPt(e){return vee(e).activeSessionCount>0}async function Wm(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:YGe});return vee(o.payload)}finally{await r.dispose().catch(()=>{return})}}async function kee(e,t,n){try{return(await Wm(e,t,n)).activeSessionCount===0}catch{return!1}}async function oKe(e,t){let n=`${e.discoveryPath}.superseded`,r=await wn(n);if(!r?.url||!r.authToken)return;let o=await xF(r.url,{authToken:r.authToken});if(o.status!=="compatible")return;if(await kee(o.url,r.authToken,t))return;return Hm(o.url,r.authToken)}async function RF(e={}){if(e.endpoint?.trim()){let o=await xF(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=_F(),n=await wn(t.discoveryPath);if(!n?.url)return await oKe(t,e);let r=await xF(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(r.status==="compatible")return Hm(r.url,n.authToken);if(r.status==="protocol_mismatch")await Ls(t.discoveryPath).catch(()=>{return});return}async function xw(e={}){let t=await RF(e);if(t&&await oo(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Sw(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function bc(e,t,n,r){gee();let o=new URL(e),i=t?.trim()||AF(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 Tw(e,t){gee();let n=new URL(e),r=t?.trim()||AF(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 iKe(e=_F()){let t=await wn(e.discoveryPath);if(!t?.url)return!1;try{if(await Tw(t.url,t.authToken))return!0}catch{}return!1}async function See(e){if(!TF(e.url))return;let t=_F(),n=await wn(t.discoveryPath);if(!n?.url||!rKe(n.url,e.url))return;if(!await kee(n.url,n.authToken,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return;if(!await iKe())return;if(!await nKe(n.url))return;return await Ls(t.discoveryPath).catch(()=>{return}),await xw({workspaceRoot:e.workspaceRoot,cwd:e.cwd})}import{resolveProviderRequestHeaders as mKe}from"@cerebriline/llms";import{captureSdkError as MF,createSessionId as Ree,HUB_CHECKPOINT_CAPABILITY as hKe,HUB_COMPACTION_CAPABILITY as fKe,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as gKe,HUB_HOOK_CAPABILITY_PREFIX as yKe,HUB_MISTAKE_LIMIT_CAPABILITY as wKe,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as bKe,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as vKe,isGeneratedMedia as kKe,isHubToolExecutorName as SKe}from"@cerebriline/shared";Wr();import{createHash as sKe}from"node:crypto";import{formatDisplayUserInput as Tee}from"@cerebriline/shared";import{z as Ii}from"zod";function aKe(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 dKe=Ii.custom(aKe),TE=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(dKe),system_prompt:Ii.string().optional()});function CF(e){return e.filter((t)=>t.metadata?.displayOnly!==!0)}function IF(e){return JSON.parse(JSON.stringify(e))}function xee(e){if(e.role!=="user")return e;if(typeof e.content==="string")return{...e,content:Tee(e.content)};return{...e,content:e.content.map((t)=>t.type==="text"?{...t,text:Tee(t.text)}:t)}}function _ee(e){if(e.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function lKe(e){let t=xee(e);return _ee(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 Eee(e){if(!e)return"";let t=xee(e);if(typeof t.id==="string"&&t.id.trim())return`id:${t.id.trim()}`;if(_ee(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 Aee(e,t=e.length){let n=sKe("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-
|
|
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-34a535a13d156348559d06088ca1d67cf0890077ffb8eae5f4f7dc502bff2722".trim()||`source-${String(P.version)}`}function ft(){let e=Number(process.env[it]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792773013448)?1792773013448: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-
|
|
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-34a535a13d156348559d06088ca1d67cf0890077ffb8eae5f4f7dc502bff2722".trim()||`source-${String(P.version)}`}function pt(){let e=Number(process.env[rt]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1792773013448)?1792773013448: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.
|
|
4
|
+
"version": "4.100.262",
|
|
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.
|
|
84
|
-
"@cerebriline/llms": "4.100.
|
|
85
|
-
"@cerebriline/shared": "4.100.
|
|
83
|
+
"@cerebriline/agents": "4.100.262",
|
|
84
|
+
"@cerebriline/llms": "4.100.262",
|
|
85
|
+
"@cerebriline/shared": "4.100.262"
|
|
86
86
|
},
|
|
87
87
|
"peerDependencies": {
|
|
88
88
|
"posthog-node": "^5.8.0"
|