@cline/core 0.0.38-nightly.1778113663 → 0.0.38
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/hub/daemon/entry.js +1 -1
- package/dist/hub/index.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +4 -4
package/dist/hub/daemon/entry.js
CHANGED
|
@@ -469,7 +469,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
469
469
|
updated_at = ?
|
|
470
470
|
WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,Yf(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,Yf(),f)}}class n8{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new i8({dbPath:f.dbPath});let $=f.specs;this.reconciler=new VH({store:this.store,specs:$}),this.materializer=new c8({store:this.store}),this.eventIngress=new e5({store:this.store,logger:f.logger}),this.runner=new d8({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:f.workspaceRoot,specs:$,logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency}),this.watcher=new YH({reconciler:this.reconciler,debounceMs:f.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=f.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs(f){return this.store.listSpecs(f)}getSpec(f){return this.store.getSpec(f)}listRuns(f){return this.store.listRuns(f)}getRun(f){return this.store.getRun(f)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns(f=20){return this.store.listRuns({status:"queued",limit:f})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent(f){return this.eventIngress.ingestEvent(f)}listEventLogs(f){return this.store.listEventLogs(f)}getEventLog(f){return this.store.getEventLog(f)}}var mj={};N(mj,{manifestToSessionRecord:()=>RJ,listSessionHistoryFromBackend:()=>KH,listSessionHistory:()=>FJ,hydrateSessionHistory:()=>kj});import{readdir as NU,readFile as Cj}from"node:fs/promises";import{join as Ej}from"node:path";import{formatDisplayUserInput as qU,normalizeUserInput as bU}from"@cline/shared";import{resolveSessionDataDir as Sj}from"@cline/shared/storage";import{existsSync as LU}from"node:fs";import{readFile as zU}from"node:fs/promises";import{formatDisplayUserInput as Oj}from"@cline/shared";class a8{listeners=new Set;subscribe(f,$){let J={listener:f,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit(f){let $=f.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$)continue;J.listener(f)}}get size(){return this.listeners.size}}async function x$(f){let $=f?.trim();if(!$||!LU($))return[];try{let J=(await zU($,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return Nj(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let H=W.messages;if(Array.isArray(H))return Nj(H)}return[]}catch{return[]}}function OU(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:Oj(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:Oj($.text)}})}}function Nj(f){return f.map(OU)}function qj(f){return f?{...f}:void 0}async function bj(f,$){if(!(f.hookName==="tool_call"||!!f.parent_agent_id))return;await $.queueSpawnRequest(f);let W=await $.upsertSubagentSessionFromHook(f);if(!W)return;await $.appendSubagentHookAudit(W,f),await $.applySubagentStatus(W,f)}function BJ(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function Cf(f){let $=BJ(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function AJ(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function wU(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function yH(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function CU(f){let $=f.match(/\d{13,}/g);if(!$||$.length===0)return 0;let J=0;for(let W of $){let H=Number.parseInt(W,10);if(Number.isFinite(H)&&H>J)J=H}return J}function RJ(f){return{sessionId:f.session_id,source:f.source,pid:f.pid,startedAt:f.started_at,endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspace_root,teamName:f.team_name,enableTools:f.enable_tools,enableSpawn:f.enable_spawn,enableTeams:f.enable_teams,isSubagent:!1,prompt:f.prompt,metadata:f.metadata,messagesPath:f.messages_path,updatedAt:f.ended_at??f.started_at}}async function EU(f){let $=yH(f);if($===0)return[];let J=Sj(),H=(await NU(J,{withFileTypes:!0}).catch(()=>[])).filter((Z)=>Z.isDirectory()).map((Z)=>({entry:Z,recency:CU(Z.name.trim())})).sort((Z,j)=>j.recency-Z.recency||j.entry.name.localeCompare(Z.entry.name));return(await Promise.all(H.map(async({entry:Z})=>{let j=Z.name.trim();if(!j)return;let P=Ej(J,j,`${j}.json`),X=await Cj(P,"utf8").catch(()=>{return});if(!X)return;let V;try{V=JSON.parse(X)}catch{return}let Y=Uf.safeParse(V);if(!Y.success)return;return RJ(Y.data)}))).filter((Z)=>Boolean(Z)).sort((Z,j)=>j.startedAt.localeCompare(Z.startedAt)).slice(0,$)}async function SU(f,$){let J=yH($);if(J===0)return await f.listSessions(0),[];return(await f.listSessions(J)).slice(0,J)}function kU(f){if(typeof f==="string")return f.trim();let $=[];for(let J of f){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let H=W.text?.trim();if(H)$.push(H)}return $.join(`
|
|
471
471
|
`).trim()}function wj(f){return f.replace(/\s+/g," ").trim()}function mU(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function IU(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let W=wj(kU(J.content));if(!W)continue;let H=$==="user"?wj(qU(W)):W,Q=bU(H.split(`
|
|
472
|
-
`)[0]??H);return mU(Q,50)}return}function xU(f){let $=0;for(let J of f)$+=AJ(J.metrics?.cost)??0;return $}function gU(f){let $,J;for(let W=f.length-1;W>=0;W-=1){let H=f[W];if(!$)$=Cf(H.modelInfo?.provider);if(!J)J=Cf(H.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function vU(f){return Cf(f?.provider)??Cf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function uU(f){return Cf(f?.model)??Cf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function FH(f,$){let J=wU(f.metadata),W=BJ($?.title)??BJ(J?.title),H=AJ($?.totalCost)??AJ(J?.totalCost),Q=J||W!==void 0||H!==void 0?{...J??{},...W!==void 0?{title:W}:{},...H!==void 0?{totalCost:H}:{}}:void 0;return{...f,provider:Cf($?.provider)??Cf(f.provider)??vU(J)??"",model:Cf($?.model)??Cf(f.model)??uU(J)??"",metadata:Q}}async function kj(f,$){return await Promise.all($.map(async(J)=>{let W=FH(J),H=Boolean(BJ(W.metadata?.title)),Q=Boolean(Cf(W.provider)),Z=Boolean(Cf(W.model)),j=AJ(W.metadata?.totalCost),P=j!==void 0&&j>0;if(H&&Q&&Z&&P)return W;let X=await f.readSessionMessages(J.sessionId);if(X.length===0)return W;let V=gU(X),Y=xU(X);return FH(J,{title:H?void 0:IU(X),provider:Q?void 0:V.provider,model:Z?void 0:V.model,totalCost:P||Y<=0?void 0:Y})}))}async function FJ(f,$={}){let J=yH($.limit),W=await SU(f,J),H=$.includeManifestFallback===!0&&W.length<J?await EU(Math.min(Math.max(J*2,100),500)):[],Q=new Map;for(let j of[...W,...H]){if(Q.has(j.sessionId))continue;Q.set(j.sessionId,j)}let Z=H.length===0?W:Array.from(Q.values()).sort((j,P)=>P.startedAt.localeCompare(j.startedAt)).slice(0,J);if($.hydrate===!1)return Z.map((j)=>FH(j));return await kj(f,Z)}async function cU(f){let $=f.trim();if(!$)return;let J=Ej(Sj(),$,`${$}.json`),W=await Cj(J,"utf8").catch(()=>{return});if(!W)return;try{let H=Uf.safeParse(JSON.parse(W));return H.success?H.data.messages_path:void 0}catch{return}}async function KH(f,$={}){let J=new Map;return await FJ({listSessions:async(H)=>{let Q=await f.listSessions(H);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(r2)},readSessionMessages:async(H)=>{let Q=J.get(H)?.messagesPath??await cU(H);return await x$(Q)}},$)}var IP={};N(IP,{resolveSessionBackend:()=>sH,createRuntimeHost:()=>a1});import{createSessionId as bG,resolveHubCommandTimeoutMs as wG}from"@cline/shared";import{spawn as VG}from"node:child_process";import{closeSync as YG,mkdirSync as BG,openSync as AG}from"node:fs";import{basename as RG,dirname as FG,join as yG}from"node:path";import{fileURLToPath as KG}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as UG,isHubDaemonProcess as tj,withResolvedClineBuildEnv as GG}from"@cline/shared";import{createHash as dU,randomBytes as rU}from"node:crypto";import{existsSync as lU}from"node:fs";import{chmod as pU,mkdir as UH,readFile as cj,rm as GH,writeFile as dj}from"node:fs/promises";import{dirname as rj,join as TH}from"node:path";import{resolveClineDataDir as t8,resolveClineDir as lj}from"@cline/shared/storage";var xj="0.0.38
|
|
472
|
+
`)[0]??H);return mU(Q,50)}return}function xU(f){let $=0;for(let J of f)$+=AJ(J.metrics?.cost)??0;return $}function gU(f){let $,J;for(let W=f.length-1;W>=0;W-=1){let H=f[W];if(!$)$=Cf(H.modelInfo?.provider);if(!J)J=Cf(H.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function vU(f){return Cf(f?.provider)??Cf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function uU(f){return Cf(f?.model)??Cf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function FH(f,$){let J=wU(f.metadata),W=BJ($?.title)??BJ(J?.title),H=AJ($?.totalCost)??AJ(J?.totalCost),Q=J||W!==void 0||H!==void 0?{...J??{},...W!==void 0?{title:W}:{},...H!==void 0?{totalCost:H}:{}}:void 0;return{...f,provider:Cf($?.provider)??Cf(f.provider)??vU(J)??"",model:Cf($?.model)??Cf(f.model)??uU(J)??"",metadata:Q}}async function kj(f,$){return await Promise.all($.map(async(J)=>{let W=FH(J),H=Boolean(BJ(W.metadata?.title)),Q=Boolean(Cf(W.provider)),Z=Boolean(Cf(W.model)),j=AJ(W.metadata?.totalCost),P=j!==void 0&&j>0;if(H&&Q&&Z&&P)return W;let X=await f.readSessionMessages(J.sessionId);if(X.length===0)return W;let V=gU(X),Y=xU(X);return FH(J,{title:H?void 0:IU(X),provider:Q?void 0:V.provider,model:Z?void 0:V.model,totalCost:P||Y<=0?void 0:Y})}))}async function FJ(f,$={}){let J=yH($.limit),W=await SU(f,J),H=$.includeManifestFallback===!0&&W.length<J?await EU(Math.min(Math.max(J*2,100),500)):[],Q=new Map;for(let j of[...W,...H]){if(Q.has(j.sessionId))continue;Q.set(j.sessionId,j)}let Z=H.length===0?W:Array.from(Q.values()).sort((j,P)=>P.startedAt.localeCompare(j.startedAt)).slice(0,J);if($.hydrate===!1)return Z.map((j)=>FH(j));return await kj(f,Z)}async function cU(f){let $=f.trim();if(!$)return;let J=Ej(Sj(),$,`${$}.json`),W=await Cj(J,"utf8").catch(()=>{return});if(!W)return;try{let H=Uf.safeParse(JSON.parse(W));return H.success?H.data.messages_path:void 0}catch{return}}async function KH(f,$={}){let J=new Map;return await FJ({listSessions:async(H)=>{let Q=await f.listSessions(H);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(r2)},readSessionMessages:async(H)=>{let Q=J.get(H)?.messagesPath??await cU(H);return await x$(Q)}},$)}var IP={};N(IP,{resolveSessionBackend:()=>sH,createRuntimeHost:()=>a1});import{createSessionId as bG,resolveHubCommandTimeoutMs as wG}from"@cline/shared";import{spawn as VG}from"node:child_process";import{closeSync as YG,mkdirSync as BG,openSync as AG}from"node:fs";import{basename as RG,dirname as FG,join as yG}from"node:path";import{fileURLToPath as KG}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as UG,isHubDaemonProcess as tj,withResolvedClineBuildEnv as GG}from"@cline/shared";import{createHash as dU,randomBytes as rU}from"node:crypto";import{existsSync as lU}from"node:fs";import{chmod as pU,mkdir as UH,readFile as cj,rm as GH,writeFile as dj}from"node:fs/promises";import{dirname as rj,join as TH}from"node:path";import{resolveClineDataDir as t8,resolveClineDir as lj}from"@cline/shared/storage";var xj="0.0.38";var gj={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:xj,repository:{type:"git",url:"https://github.com/cline/sdk",directory:"packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{development:"./src/index.ts",types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{development:"./src/hub/index.ts",types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{development:"./src/hub/daemon/entry.ts",types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{development:"./src/services/telemetry/index.ts",types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"rm -rf dist && bun run ./bun.mts && bun tsc -p tsconfig.build.json",clean:"rm -rf dist node_modules",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:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@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",jiti:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var iU="CLINE_HUB_DISCOVERY_PATH",nU="CLINE_HUB_BUILD_ID",vj=30000,aU=15000,tU=100;function sU(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function oU(f){return dU("sha256").update(f).digest("hex").slice(0,12)}function eU(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function yJ(){return rU(32).toString("hex")}function fG(f){return new Promise(($)=>setTimeout($,f))}function $G(f){return`${f}.lock`}async function JG(f){try{let $=JSON.parse(await cj(TH(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function uj(f){await GH(f,{recursive:!0,force:!0}).catch(()=>{return})}function J$(){return process.env[nU]?.trim()||String(gj.version)}function M0(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${oU(f)}`,J=process.env[iU]?.trim()||TH(t8(),"locks","hub","owners",`${sU($)}.json`);return{ownerId:$,discoveryPath:J}}function pj(f=`hub-${Date.now().toString(36)}`){return M0(f)}async function Zf(f){try{let $=JSON.parse(await cj(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function KJ(f,$){await UH(rj(f),{recursive:!0}),await GH(f,{force:!0}).catch(()=>{return}),await dj(f,`${JSON.stringify($,null,2)}
|
|
473
473
|
`,{encoding:"utf8",mode:384}),await pU(f,384)}async function Ef(f){await GH(f,{force:!0}).catch(()=>{return})}async function UJ(f,$){let J=$G(f);await UH(rj(J),{recursive:!0});let W=Date.now()+aU;while(!0)try{await UH(J,{recursive:!1}),await dj(TH(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
474
474
|
`,"utf8");try{return await $()}finally{await uj(J)}}catch(H){if((H instanceof Error&&"code"in H?String(H.code):"")!=="EEXIST")throw H;let Z=await JG(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):vj+1;if(!Z||!eU(Z.pid)||j>vj){await uj(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await fG(tU)}}async function Bf(f){try{let $=await fetch(hH(f));if(!$.ok)return;return await $.json()}catch{return}}function lf(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function hH(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function ij(f){return lU(f)}import{CLINE_HUB_DEV_PORT as WG,CLINE_HUB_PORT as HG,resolveClineBuildEnv as QG}from"@cline/shared";var ZG="CLINE_HUB_HOST",jG="CLINE_HUB_PORT",PG="CLINE_HUB_PATHNAME",DH="127.0.0.1",MH=HG,_H="/hub";function nj(f){return QG(f)==="development"?WG:MH}function LH(f={}){return(f.env??process.env)[ZG]?.trim()||DH}function v1(f={}){let J=(f.env??process.env)[jG]?.trim();if(!J)return nj(f);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return nj(f);return W}function zH(f={}){return(f.env??process.env)[PG]?.trim()||_H}function Sf(f={},$={}){return{host:f.host??LH($),port:f.port??v1($),pathname:f.pathname??zH($)}}var XG="shared:cline";function aj(f){let $=D0(f.trim());return M0(`workspace:${$||f.trim()}`)}function Qf(f=XG){return M0(f)}var TG=8000,hG=200,DG=3000,MG=100,_G="--cline-hub-daemon";function LG(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function zG(){try{let f=yG(t8(),"logs","hub-daemon.log");return BG(FG(f),{recursive:!0}),{fd:AG(f,"a"),logPath:f}}catch{return}}function s8(f){let $=f.buildId?.trim();return!!$&&$===J$()}async function OG(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Bf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,MG))}return!1}async function o8(f,$){if(s8(f))return;if(await e8(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await OG(f.url,DG),await Ef($).catch(()=>{return})}function NG(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return KG(new URL(`./entry.${f}`,import.meta.url))}function qG(f,$){let J=NG(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let H=RG(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=H&&J.toLowerCase().endsWith(".ts"),j=Q?[_G]:[...Z?["--conditions=development"]:[],J];return{launcher:W,args:[...j,"--cwd",f,...LG($)],cwd:f,env:{...GG(process.env),CLINE_NO_INTERACTIVE:"1",[UG]:"1"}}}function u1(f,$={}){if(tj())return;let J=qG(f,$),W=zG();try{VG(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)YG(W.fd)}}function GJ(f,$={}){if(tj())return;let J=Qf(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=Sf($),Q=lf(H.host,H.port,H.pathname);Zf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let V=await Bf(Z.url);if(V?.url&&s8(V)&&await f0(V.url,{authToken:Z.authToken}))return;if(V?.url)await o8({...V,authToken:Z.authToken},J.discoveryPath);else await Ef(J.discoveryPath).catch(()=>{return})}let j=await Bf(Q);if(j?.url)await o8(j,J.discoveryPath);let X=!W&&H.port!==0?{...H,port:0}:H;u1(f,X)}).catch(()=>{})}async function sj(f,$={}){let J=Qf(),W=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=Sf($),Z=lf(Q.host,Q.port,Q.pathname),j=(A)=>{if(!W)W$(A.url,A.authToken);return A},P=await Zf(J.discoveryPath);if(P?.url){let A=await Bf(P.url);if(A?.url&&s8(A)&&await f0(A.url,{authToken:P.authToken}))return j({url:A.url,authToken:P.authToken});if(A?.url)await o8({...A,authToken:P.authToken},J.discoveryPath);else await Ef(J.discoveryPath).catch(()=>{return})}let X=await Bf(Z);if(X?.url)await o8(X,J.discoveryPath);let Y=!H&&Q.port!==0?{...Q,port:0}:Q;u1(f,Y);let B=Date.now()+TG;while(Date.now()<B){let A=await Zf(J.discoveryPath);if(A?.url){let U=await Bf(A.url);if(U?.url&&s8(U)&&await f0(U.url,{authToken:A.authToken}))return j({url:U.url,authToken:A.authToken})}let R=await Bf(Z);if(R?.url&&!s8(R))await o8(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,hG))}throw Error("Timed out waiting for detached hub startup.")}function CG(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function JP(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return JP(f.data);return String(f)}function EG(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function oj(f){let $=f,J=EG($.reason);return new yf("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:OH,{closeCode:$.code,closeReason:J||void 0})}function SG(f,$){if(f instanceof yf)return f;if(f instanceof Error)return new yf("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new yf("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new yf("hub_connect_failed",J);let W=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new yf("hub_connect_failed",W?`Failed to connect to hub at ${$.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var kG=8000,mG=200,ej="*",fP=8000,IG="cline-hub-auth.",WP=new Map,HP=new Set,xG=3000,gG=3000,vG=100,OH="Hub connection closed",uG=250,cG=5000,$P=0.5;class yf extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function bH(f){return f instanceof yf}class c1 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function TJ(f,$){return f instanceof c1&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function QP(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=wH(f.toString());return J?WP.get(J):void 0}function dG(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function wH(f){if(!dG(f))return;let $=new URL(H$(f));return $.search="",$.hash="",$.toString()}function NH(f){let $=wH(f);return!!$&&HP.has($)}function W$(f,$){let J=wH(f);if(J){if(HP.add(J),$?.trim())WP.set(J,$)}return f}class pf{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new yf("hub_connection_closed",OH);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||QP(f);f.hash="";let W=new(CG())(f.toString(),$?[`${IG}${$}`]:void 0);this.socket=W;let H=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,P=setTimeout(()=>{if(j)return;j=!0,H=!0,this.lastCloseError=new yf("hub_connect_timeout",`Timed out connecting to hub after ${fP}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}Z(this.lastCloseError)},fP);W.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(P),Q()}),W.addEventListener("error",(X)=>{if(j)return;j=!0,clearTimeout(P),this.lastCloseError=SG(X,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),W.addEventListener("close",(X)=>{if(j)return;if(j=!0,clearTimeout(P),!H)this.lastCloseError=oj(X),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(JP(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!H)this.lastCloseError=oj(Q),this.sawSocketClose=!0;this.registered=!1;for(let Z of this.pendingReplies.values())Z.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,W={listener:f,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,W){let H=0,Q=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,W)}catch(Z){if(!Q||H>=1||!await this.recoverLocalHubTransport(Z))throw Z;H+=1}}async commandOnce(f,$,J,W){await this.connect();let H=bG("hubreq_"),Q=wG(f,W?.timeoutMs),Z=new Promise((P,X)=>{let V=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(H))return;X(new c1(f,"hub_command_timeout",`Hub command ${f} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${H}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(H,{resolve:(Y)=>{if(V)clearTimeout(V);P(Y)},reject:(Y)=>{if(V)clearTimeout(V);X(Y)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:H,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(P){throw this.pendingReplies.delete(H),P}let j=await Z;if(!j.ok)throw new c1(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!NH(this.currentUrl)||!bH(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await g$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,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 f=Math.min(uG*2**this.reconnectAttempt,cG),$=Math.round(f*(1-$P)+Math.random()*f*$P);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!NH(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await g$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new yf("hub_connection_closed",OH),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.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(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new yf("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),W=(this.subscriptionCounts.get(J)??0)+$;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,W),$>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??ej}subscriptionSessionIdFromKey(f){return f===ej?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function H$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function f0(f,$){let J=new pf({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function qH(f,$){let J=H$(f),W=await Bf(J);if(!W)return{status:"unreachable",url:J};let H=J$(),Q=W.buildId?.trim();if(!Q||Q!==H)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await f0(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function rG(f){let $=Date.now()+kG;while(Date.now()<$){let J=await Zf(f.discoveryPath);if(J?.url){let W=await qH(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return W$(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,mG))}return}async function lG(f){let $=Date.now()+gG;while(Date.now()<$){if(!(await Bf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,vG))}return!1}function pG(f,$){try{return H$(f)===H$($)}catch{return!1}}function iG(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function nG(f,$,J){let W=new pf({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let H=await W.command("session.list",{limit:500},void 0,{timeoutMs:xG});return!iG(H.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function f4(f={}){if(f.endpoint?.trim()){let H=await qH(f.endpoint);return H.status==="compatible"?H.url:void 0}let $=Qf(),J=await Zf($.discoveryPath);if(!J?.url)return;let W=await qH(J.url);if(W.status==="compatible")return W$(W.url,J.authToken);if(W.status==="build_mismatch")await Ef($.discoveryPath).catch(()=>{return});return}async function g$(f={}){let $=await f4(f);if($&&await f0($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Qf();return u1(f.workspaceRoot??process.cwd()),await rG(J)}async function e8(f,$){let J=new URL(f),W=$?.trim()||QP(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function CH(){let f=Qf(),$=await Zf(f.discoveryPath);if(!$?.url)return!1;try{if(await e8($.url,$.authToken))return!0}catch{}return!1}async function hJ(f){if(!NH(f.url))return;let $=Qf(),J=await Zf($.discoveryPath);if(!J?.url||!pG(J.url,f.url))return;if(!await nG(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await CH())return;if(!await lG(J.url))return;return await Ef($.discoveryPath).catch(()=>{return}),await g$({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}var FP={};N(FP,{HubRuntimeHost:()=>_0});import{createSessionId as jP,HUB_CHECKPOINT_CAPABILITY as oG,HUB_COMPACTION_CAPABILITY as eG,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as fT,HUB_HOOK_CAPABILITY_PREFIX as $T,HUB_MISTAKE_LIMIT_CAPABILITY as JT,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as WT,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as HT,isHubToolExecutorName as QT}from"@cline/shared";var ZP={};N(ZP,{createCoreSessionSnapshot:()=>$0,coreSessionSnapshotToRecord:()=>DJ});function aG(f){return f?JSON.parse(JSON.stringify(f)):void 0}function tG(f){return f?JSON.parse(JSON.stringify(f)):void 0}function sG(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,W=(Array.isArray($?.history)?$.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let j=typeof Z.ref==="string"?Z.ref.trim():"",P=Number(Z.createdAt),X=Number(Z.runCount);if(!j||!Number.isFinite(P)||!Number.isInteger(X))return[];return[{ref:j,createdAt:P,runCount:X,...Z.kind==="stash"||Z.kind==="commit"?{kind:Z.kind}:{}}]}),H=W.at(-1),Q=f?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...H?{latest:H}:{},history:W}}function $0(f){let{session:$}=f,J=aG($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:tG(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...(()=>{let W=sG(J);return W?{checkpoint:W}:{}})()}}function DJ(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function d1(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var ZT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function PP(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function XP(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function VP(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function v$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function YP(f,$){let J={manifest:[],handlers:new Map};for(let H of Object.keys($.toolExecutors??{}).filter(QT)){let Q=$.toolExecutors?.[H];if(typeof Q!=="function")continue;v$(J,{kind:"toolExecutor",executor:H,capabilityName:`${WT}${H}`},async({payload:Z,abortSignal:j})=>{let P=Array.isArray(Z.args)?[...Z.args]:[],X={...VP(Z.context),signal:j};return{result:await Q(...P,X)}})}for(let H of f?.extraTools??[])v$(J,{kind:"tool",name:H.name,description:H.description,inputSchema:d1(H.inputSchema)??{},...H.lifecycle?{lifecycle:d1(H.lifecycle)}:{},capabilityName:`${fT}${H.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let P={...VP(Q.context),signal:Z};return{result:await H.execute(Q.input,{...P,emitUpdate:(V)=>{j({update:V})}})}});let W=f?.hooks;if(W)for(let H of ZT){let Q=W[H];if(typeof Q!=="function")continue;v$(J,{kind:"hook",name:H,capabilityName:`${$T}${H}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let H=f.compaction.compact;v$(J,{kind:"compaction",capabilityName:eG,config:PP(f.compaction)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let H=f.checkpoint.createCheckpoint;v$(J,{kind:"checkpoint",capabilityName:oG,config:PP(f.checkpoint)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let H=f.onConsecutiveMistakeLimitReached;v$(J,{kind:"mistakeLimit",capabilityName:JT},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.userInstructionService){let H=f.userInstructionService;v$(J,{kind:"userInstructionService",capabilityName:HT},async()=>{return await H.start().catch(()=>{}),{snapshot:{records:{skill:H.listRecords("skill"),rule:H.listRecords("rule"),workflow:H.listRecords("workflow")},runtimeCommands:H.listRuntimeCommands()}}})}return J}function jT(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return"Capability request was cancelled."}function PT(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function XT(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function VT(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,W=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function YT(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,W=XT(J)?J:J==="failed"?"error":"completed",H=VT(f?.usage??$?.usage);return{type:"done",reason:W,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:H}}function EH(f,$){return f.error?.message??`hub command failed: ${$}`}function $4(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function RP(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:Pf.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:$4(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:$4(f.status)==="completed"?0:$4(f.status)==="failed"?1:void 0,status:$4(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function u$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function BT(f){let $=u$(f?.snapshot);if($)return DJ($);let J=f?.session;return J?RP(J):void 0}function BP(f,$,J){let W=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return Uf.parse({version:1,session_id:f,source:$.source??Pf.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:$4(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:W,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function AP(f,$){return Uf.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class _0{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new a8;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=Vf(f.capabilities)??{},this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new pf({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!TJ(f,"session.create"))return!1;let $=await hJ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=YP(f.localRuntime,$),W=f.config.sessionId?.trim()||jP(),H=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:d1({...f.config,sessionId:W}),metadata:{...f.sessionMetadata??{},source:f.source??Pf.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:d1(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(W,$,J.handlers);let Q;try{Q=await H()}catch(X){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(X)){this.registerPlannedSession(W,$,J.handlers);try{Q=await H()}catch(V){throw this.cleanupPlannedSession(W),V}}else throw X}let Z=u$(Q.payload?.snapshot),j=Q.payload?.session,P=(Z?.sessionId??j?.sessionId)?.trim();if(!P)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(P!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(P,$,J.handlers);return{sessionId:P,manifest:Z?AP(Z,f):BP(P,f,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let W=f.start,H=W?this.resolveCapabilities(W):void 0,Q=W?YP(W.localRuntime,H??{}):{manifest:[],handlers:new Map},Z=W?W.config.sessionId?.trim()||jP():void 0;if(Z&&H)this.sessionCapabilities.set(Z,H);if(Z&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Z,Q.handlers),this.ensureSessionSubscription(Z);let j;try{j=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??f.cwd,sessionConfig:d1({...W.config,sessionId:Z}),metadata:{...W.sessionMetadata??{},source:W.source??Pf.CORE,provider:W.config.providerId,model:W.config.modelId,enableTools:W.config.enableTools,enableSpawn:W.config.enableSpawnAgent,enableTeams:W.config.enableAgentTeams,teamName:W.config.teamName,prompt:W.prompt,interactive:W.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:d1(W.toolPolicies)}:{}},$)}catch(A){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw A}if(!j.ok){let A=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error(A)}let P=u$(j.payload?.snapshot),X=j.payload?.session,V=(P?.sessionId??X?.sessionId)?.trim();if(J&&!V){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error("Hub checkpoint restore returned no session id")}if(V&&Z&&V!==Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);if(V&&H)this.sessionCapabilities.set(V,H);if(V&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(V,Q.handlers);if(V)this.ensureSessionSubscription(V);let Y=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,B=j.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:P?AP(P,W??{}):BP(V,W??{},X),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:Y,checkpoint:B}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=u$($.payload?.snapshot);if(J?.usage)return{...J.usage};let W=$.payload?.session;return W?.usage?{...W.usage}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:typeof $==="string"?$:void 0},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $=await this.client.command("session.get",void 0,f);return BT($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((H)=>{let Q=u$(H);return Q?[DJ(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(RP)}async listSettings(f){let $=await this.client.command("settings.list",XP(f));if(!$.ok)throw Error(EH($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",XP(f));if(!$.ok)throw Error(EH($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(EH(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return Vf(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:YT(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f);return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f);return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=u$(f.payload?.snapshot),W=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",W=f.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=u$(f.payload?.snapshot),W=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:$,reason:J,ts:f.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof f.payload?.requestId==="string"?f.payload.requestId:"",H=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get($)?.get(H);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${H} in session ${$}.`},$).catch(()=>{});return}let Z=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(W,j);let P=(X)=>{this.client.command("capability.progress",{requestId:W,payload:X},$)};try{let X=await Q({payload:Z,abortSignal:j.signal,progress:P});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:X},$)}catch(X){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:X instanceof Error?X.message:String(X)},$)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(jT(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",H=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",Q=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!W||!H||!Q)return;let Z=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},j=PT(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(H),this.emitToolCallContentStart({sessionId:$,toolCallId:H,toolName:Q,toolInput:j});let P=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:H,toolName:Q,input:j,policy:Z})).catch((X)=>({approved:!1,reason:X instanceof Error?X.message:`Tool approval request failed: ${String(X)}`}));await this.client.command("approval.respond",{approvalId:W,approved:P.approved,reason:P.reason},$).catch(()=>{})}}var yP={};N(yP,{RemoteRuntimeHost:()=>r1});class r1 extends _0{constructor(f){super({url:H$(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}var KP={};N(KP,{SqliteSessionStore:()=>W0});import{existsSync as AT,mkdirSync as RT}from"node:fs";import{join as FT}from"node:path";import{asBool as J4,asOptionalString as J0,asString as L0,ensureSessionSchema as yT,loadSqliteDb as KT,nowIso as MJ,toBoolInt as W4}from"@cline/shared/db";import{resolveDbDataDir as UT}from"@cline/shared/storage";class W0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??UT()}init(){this.getRawDb()}ensureSessionsDir(){if(!AT(this.sessionsDirPath))RT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return FT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=KT(this.sessionDbPath());return yT(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=MJ();this.run(`INSERT OR REPLACE INTO sessions (
|
|
475
475
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
package/dist/hub/index.js
CHANGED
|
@@ -272,7 +272,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
272
272
|
error = ?,
|
|
273
273
|
scheduled_for = COALESCE(?, scheduled_for),
|
|
274
274
|
updated_at = ?
|
|
275
|
-
WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,jf(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,jf(),f)}}function w4(f){return f?new Date(f).getTime():void 0}function rY(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function b4(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:w4(f.nextRunAt),lastRunAt:w4(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:rY(f)}}function lY(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function C3(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:w4(f.startedAt),endedAt:w4(f.completedAt),status:lY(f.status),errorMessage:f.error}}class Q1{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new M2({dbPath:f.dbPath}),this.materializer=new y2({store:this.store}),this.runner=new G2({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.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(f){if(RH(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return b4(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?b4($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>b4($))}updateSchedule(f,$){if($.cronPattern!==void 0)RH($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let H=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!H)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule(f,{...$,scheduleId:f});return Q?b4(Q):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return C3(J,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((W)=>{let Q=$??this.store.getSpec(W.specId);if(!Q||Q.source!=="hub-schedule")return;return C3(W,Q.externalId)}).filter((W)=>{if(!W)return!1;return!f.status||W.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,H=0,W=0,Q;for(let Z of $){if(Z.status==="success"||Z.status==="completed")J+=1;if(!Q&&Z.status!=="success"&&Z.status!=="completed")Q=Z;if(Z.startedAt&&Z.endedAt)W+=Z.endedAt-Z.startedAt,H+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:H>0?W/H/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,H)=>String(J.nextRunAt).localeCompare(String(H.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:H})=>({scheduleId:J.externalId,name:J.title,nextRunAt:H}))}}o4();import{createSessionId as GA,resolveHubCommandTimeoutMs as hA}from"@cline/shared";import{spawn as eB}from"node:child_process";import{closeSync as fA,mkdirSync as $A,openSync as JA}from"node:fs";import{basename as HA,dirname as WA,join as QA}from"node:path";import{fileURLToPath as ZA}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as jA,isHubDaemonProcess as Z7,withResolvedClineBuildEnv as PA}from"@cline/shared";import{createHash as CB,randomBytes as EB}from"node:crypto";import{existsSync as SB}from"node:fs";import{chmod as kB,mkdir as DH,readFile as o3,rm as MH,writeFile as e3}from"node:fs/promises";import{dirname as f7,join as _H}from"node:path";import{resolveClineDataDir as S2,resolveClineDir as $7}from"@cline/shared/storage";var n3="0.0.38
|
|
275
|
+
WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,jf(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,jf(),f)}}function w4(f){return f?new Date(f).getTime():void 0}function rY(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function b4(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:w4(f.nextRunAt),lastRunAt:w4(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:rY(f)}}function lY(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function C3(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:w4(f.startedAt),endedAt:w4(f.completedAt),status:lY(f.status),errorMessage:f.error}}class Q1{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new M2({dbPath:f.dbPath}),this.materializer=new y2({store:this.store}),this.runner=new G2({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.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(f){if(RH(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return b4(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?b4($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>b4($))}updateSchedule(f,$){if($.cronPattern!==void 0)RH($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let H=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!H)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule(f,{...$,scheduleId:f});return Q?b4(Q):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return C3(J,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((W)=>{let Q=$??this.store.getSpec(W.specId);if(!Q||Q.source!=="hub-schedule")return;return C3(W,Q.externalId)}).filter((W)=>{if(!W)return!1;return!f.status||W.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,H=0,W=0,Q;for(let Z of $){if(Z.status==="success"||Z.status==="completed")J+=1;if(!Q&&Z.status!=="success"&&Z.status!=="completed")Q=Z;if(Z.startedAt&&Z.endedAt)W+=Z.endedAt-Z.startedAt,H+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:H>0?W/H/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,H)=>String(J.nextRunAt).localeCompare(String(H.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:H})=>({scheduleId:J.externalId,name:J.title,nextRunAt:H}))}}o4();import{createSessionId as GA,resolveHubCommandTimeoutMs as hA}from"@cline/shared";import{spawn as eB}from"node:child_process";import{closeSync as fA,mkdirSync as $A,openSync as JA}from"node:fs";import{basename as HA,dirname as WA,join as QA}from"node:path";import{fileURLToPath as ZA}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as jA,isHubDaemonProcess as Z7,withResolvedClineBuildEnv as PA}from"@cline/shared";import{createHash as CB,randomBytes as EB}from"node:crypto";import{existsSync as SB}from"node:fs";import{chmod as kB,mkdir as DH,readFile as o3,rm as MH,writeFile as e3}from"node:fs/promises";import{dirname as f7,join as _H}from"node:path";import{resolveClineDataDir as S2,resolveClineDir as $7}from"@cline/shared/storage";var n3="0.0.38";var a3={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:n3,repository:{type:"git",url:"https://github.com/cline/sdk",directory:"packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{development:"./src/index.ts",types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{development:"./src/hub/index.ts",types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{development:"./src/hub/daemon/entry.ts",types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{development:"./src/services/telemetry/index.ts",types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"rm -rf dist && bun run ./bun.mts && bun tsc -p tsconfig.build.json",clean:"rm -rf dist node_modules",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:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@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",jiti:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var mB="CLINE_HUB_DISCOVERY_PATH",IB="CLINE_HUB_BUILD_ID",t3=30000,xB=15000,gB=100;function vB(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function uB(f){return CB("sha256").update(f).digest("hex").slice(0,12)}function cB(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function e4(){return EB(32).toString("hex")}function dB(f){return new Promise(($)=>setTimeout($,f))}function rB(f){return`${f}.lock`}async function lB(f){try{let $=JSON.parse(await o3(_H(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function s3(f){await MH(f,{recursive:!0,force:!0}).catch(()=>{return})}function S0(){return process.env[IB]?.trim()||String(a3.version)}function y0(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${uB(f)}`,J=process.env[mB]?.trim()||_H(S2(),"locks","hub","owners",`${vB($)}.json`);return{ownerId:$,discoveryPath:J}}function J7(f=`hub-${Date.now().toString(36)}`){return y0(f)}async function Qf(f){try{let $=JSON.parse(await o3(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function f6(f,$){await DH(f7(f),{recursive:!0}),await MH(f,{force:!0}).catch(()=>{return}),await e3(f,`${JSON.stringify($,null,2)}
|
|
276
276
|
`,{encoding:"utf8",mode:384}),await kB(f,384)}async function zf(f){await MH(f,{force:!0}).catch(()=>{return})}async function $6(f,$){let J=rB(f);await DH(f7(J),{recursive:!0});let H=Date.now()+xB;while(!0)try{await DH(J,{recursive:!1}),await e3(_H(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
277
277
|
`,"utf8");try{return await $()}finally{await s3(J)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let Z=await lB(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):t3+1;if(!Z||!cB(Z.pid)||j>t3){await s3(J);continue}if(Date.now()>=H)throw Error(`Timed out waiting for hub startup lock ${J}`);await dB(gB)}}async function Pf(f){try{let $=await fetch(LH(f));if(!$.ok)return;return await $.json()}catch{return}}function cf(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function LH(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function H7(f){return SB(f)}import{CLINE_HUB_DEV_PORT as pB,CLINE_HUB_PORT as iB,resolveClineBuildEnv as nB}from"@cline/shared";var aB="CLINE_HUB_HOST",tB="CLINE_HUB_PORT",sB="CLINE_HUB_PATHNAME",zH="127.0.0.1",OH=iB,NH="/hub";function W7(f){return nB(f)==="development"?pB:OH}function qH(f={}){return(f.env??process.env)[aB]?.trim()||zH}function V1(f={}){let J=(f.env??process.env)[tB]?.trim();if(!J)return W7(f);let H=Number.parseInt(J,10);if(!Number.isInteger(H)||H<1||H>65535)return W7(f);return H}function bH(f={}){return(f.env??process.env)[sB]?.trim()||NH}function tf(f={},$={}){return{host:f.host??qH($),port:f.port??V1($),pathname:f.pathname??bH($)}}var oB="shared:cline";function Q7(f){let $=V0(f.trim());return y0(`workspace:${$||f.trim()}`)}function Xf(f=oB){return y0(f)}var XA=8000,VA=200,YA=3000,BA=100,AA="--cline-hub-daemon";function RA(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function FA(){try{let f=QA(S2(),"logs","hub-daemon.log");return $A(WA(f),{recursive:!0}),{fd:JA(f,"a"),logPath:f}}catch{return}}function k2(f){let $=f.buildId?.trim();return!!$&&$===S0()}async function yA(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Pf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,BA))}return!1}async function m2(f,$){if(k2(f))return;if(await I2(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await yA(f.url,YA),await zf($).catch(()=>{return})}function KA(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return ZA(new URL(`./entry.${f}`,import.meta.url))}function UA(f,$){let J=KA(),H=process.execPath?.trim();if(!H)throw Error("unable to resolve runtime executable for hub daemon");let W=HA(H).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=W&&J.toLowerCase().endsWith(".ts"),j=Q?[AA]:[...Z?["--conditions=development"]:[],J];return{launcher:H,args:[...j,"--cwd",f,...RA($)],cwd:f,env:{...PA(process.env),CLINE_NO_INTERACTIVE:"1",[jA]:"1"}}}function Y1(f,$={}){if(Z7())return;let J=UA(f,$),H=FA();try{eB(J.launcher,J.args,{detached:!0,stdio:H?["ignore",H.fd,H.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(H)fA(H.fd)}}function J6(f,$={}){if(Z7())return;let J=Xf(),H=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=tf($),Q=cf(W.host,W.port,W.pathname);Qf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let V=await Pf(Z.url);if(V?.url&&k2(V)&&await sf(V.url,{authToken:Z.authToken}))return;if(V?.url)await m2({...V,authToken:Z.authToken},J.discoveryPath);else await zf(J.discoveryPath).catch(()=>{return})}let j=await Pf(Q);if(j?.url)await m2(j,J.discoveryPath);let X=!H&&W.port!==0?{...W,port:0}:W;Y1(f,X)}).catch(()=>{})}async function j7(f,$={}){let J=Xf(),H=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=tf($),Z=cf(Q.host,Q.port,Q.pathname),j=(A)=>{if(!H)k0(A.url,A.authToken);return A},P=await Qf(J.discoveryPath);if(P?.url){let A=await Pf(P.url);if(A?.url&&k2(A)&&await sf(A.url,{authToken:P.authToken}))return j({url:A.url,authToken:P.authToken});if(A?.url)await m2({...A,authToken:P.authToken},J.discoveryPath);else await zf(J.discoveryPath).catch(()=>{return})}let X=await Pf(Z);if(X?.url)await m2(X,J.discoveryPath);let Y=!W&&Q.port!==0?{...Q,port:0}:Q;Y1(f,Y);let B=Date.now()+XA;while(Date.now()<B){let A=await Qf(J.discoveryPath);if(A?.url){let U=await Pf(A.url);if(U?.url&&k2(U)&&await sf(U.url,{authToken:A.authToken}))return j({url:U.url,authToken:A.authToken})}let R=await Pf(Z);if(R?.url&&!k2(R))await m2(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,VA))}throw Error("Timed out waiting for detached hub startup.")}function TA(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function B7(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return B7(f.data);return String(f)}function DA(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function P7(f){let $=f,J=DA($.reason);return new Rf("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:wH,{closeCode:$.code,closeReason:J||void 0})}function MA(f,$){if(f instanceof Rf)return f;if(f instanceof Error)return new Rf("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new Rf("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new Rf("hub_connect_failed",J);let H=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new Rf("hub_connect_failed",H?`Failed to connect to hub at ${$.toString()} (${H} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var _A=8000,LA=200,X7="*",V7=8000,zA="cline-hub-auth.",A7=new Map,R7=new Set,OA=3000,NA=3000,qA=100,wH="Hub connection closed",bA=250,wA=5000,Y7=0.5;class Rf extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function SH(f){return f instanceof Rf}class B1 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function H6(f,$){return f instanceof B1&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function F7(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=kH(f.toString());return J?A7.get(J):void 0}function CA(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function kH(f){if(!CA(f))return;let $=new URL(m0(f));return $.search="",$.hash="",$.toString()}function CH(f){let $=kH(f);return!!$&&R7.has($)}function k0(f,$){let J=kH(f);if(J){if(R7.add(J),$?.trim())A7.set(J,$)}return f}class df{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new Rf("hub_connection_closed",wH);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||F7(f);f.hash="";let H=new(TA())(f.toString(),$?[`${zA}${$}`]:void 0);this.socket=H;let W=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,P=setTimeout(()=>{if(j)return;j=!0,W=!0,this.lastCloseError=new Rf("hub_connect_timeout",`Timed out connecting to hub after ${V7}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{H.close()}catch{}Z(this.lastCloseError)},V7);H.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(P),Q()}),H.addEventListener("error",(X)=>{if(j)return;j=!0,clearTimeout(P),this.lastCloseError=MA(X,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),H.addEventListener("close",(X)=>{if(j)return;if(j=!0,clearTimeout(P),!W)this.lastCloseError=P7(X),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),H.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(B7(Q)))}),H.addEventListener("close",(Q)=>{if(this.socket!==H)return;if(!W)this.lastCloseError=P7(Q),this.sawSocketClose=!0;this.registered=!1;for(let Z of this.pendingReplies.values())Z.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,H={listener:f,sessionId:J};return this.listeners.add(H),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(H))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,H){let W=0,Q=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,H)}catch(Z){if(!Q||W>=1||!await this.recoverLocalHubTransport(Z))throw Z;W+=1}}async commandOnce(f,$,J,H){await this.connect();let W=GA("hubreq_"),Q=hA(f,H?.timeoutMs),Z=new Promise((P,X)=>{let V=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;X(new B1(f,"hub_command_timeout",`Hub command ${f} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(W,{resolve:(Y)=>{if(V)clearTimeout(V);P(Y)},reject:(Y)=>{if(V)clearTimeout(V);X(Y)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:W,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(P){throw this.pendingReplies.delete(W),P}let j=await Z;if(!j.ok)throw new B1(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!CH(this.currentUrl)||!SH(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await K$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,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 f=Math.min(bA*2**this.reconnectAttempt,wA),$=Math.round(f*(1-Y7)+Math.random()*f*Y7);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!CH(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await K$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new Rf("hub_connection_closed",wH),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.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(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new Rf("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),H=(this.subscriptionCounts.get(J)??0)+$;if(H<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,H),$>0&&H===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??X7}subscriptionSessionIdFromKey(f){return f===X7?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function m0(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function sf(f,$){let J=new df({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function EH(f,$){let J=m0(f),H=await Pf(J);if(!H)return{status:"unreachable",url:J};let W=S0(),Q=H.buildId?.trim();if(!Q||Q!==W)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await sf(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function EA(f){let $=Date.now()+_A;while(Date.now()<$){let J=await Qf(f.discoveryPath);if(J?.url){let H=await EH(J.url,{verifyConnection:!0,authToken:J.authToken});if(H.status==="compatible")return k0(H.url,J.authToken)}await new Promise((H)=>setTimeout(H,LA))}return}async function SA(f){let $=Date.now()+NA;while(Date.now()<$){if(!(await Pf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,qA))}return!1}function kA(f,$){try{return m0(f)===m0($)}catch{return!1}}function mA(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let H=J;if(H.status==="running"||H.status==="idle")return!0;return Array.isArray(H.participants)&&H.participants.length>0})}async function IA(f,$,J){let H=new df({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let W=await H.command("session.list",{limit:500},void 0,{timeoutMs:OA});return!mA(W.payload)}catch{return!1}finally{await H.dispose().catch(()=>{return})}}async function x2(f={}){if(f.endpoint?.trim()){let W=await EH(f.endpoint);return W.status==="compatible"?W.url:void 0}let $=Xf(),J=await Qf($.discoveryPath);if(!J?.url)return;let H=await EH(J.url);if(H.status==="compatible")return k0(H.url,J.authToken);if(H.status==="build_mismatch")await zf($.discoveryPath).catch(()=>{return});return}async function K$(f={}){let $=await x2(f);if($&&await sf($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Xf();return Y1(f.workspaceRoot??process.cwd()),await EA(J)}async function I2(f,$){let J=new URL(f),H=$?.trim()||F7(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:H?{authorization:`Bearer ${H}`}:void 0})).ok}async function mH(){let f=Xf(),$=await Qf(f.discoveryPath);if(!$?.url)return!1;try{if(await I2($.url,$.authToken))return!0}catch{}return!1}async function W6(f){if(!CH(f.url))return;let $=Xf(),J=await Qf($.discoveryPath);if(!J?.url||!kA(J.url,f.url))return;if(!await IA(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await mH())return;if(!await SA(J.url))return;return await zf($.discoveryPath).catch(()=>{return}),await K$({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}function xA(f,$){if(f instanceof Error)return f;if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"&&f.message.trim())return Error(f.message.trim());let J=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return Error(J?`Failed to connect to hub at ${$} (${J} event before socket open).`:`Failed to connect to hub at ${$}.`)}var gA="cline-hub-auth.";function vA(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function uA(f,$){let J=new URL(f),H=new URL($);return J.search="",J.hash="",H.search="",H.hash="",J.toString()===H.toString()}async function cA(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=Xf(),H=await Qf(J.discoveryPath);if(H?.url&&uA(f.toString(),H.url))return H.authToken;return}async function IH(f={}){let $=tf(f);if(!vA(f)){let J=Xf(),H=await Qf(J.discoveryPath);if(H?.url)return H.url}return cf($.host,$.port,$.pathname)}async function Q6(f){return await new Promise(($,J)=>{(async()=>{let H=new URL(f),W=await cA(H);H.hash="";let Q=new WebSocket(H.toString(),W?[`${gA}${W}`]:void 0),Z=new Map,j=0;Q.addEventListener("open",()=>{$({send(P){let X=P.requestId??`hub-client-${++j}`;return new Promise((V,Y)=>{Z.set(X,{resolve:V,reject:Y});let B={kind:"command",envelope:{...P,requestId:X}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(P)=>{let X=JSON.parse(String(P.data));if(X.kind==="reply"&&X.envelope.requestId){let V=Z.get(X.envelope.requestId);if(V)Z.delete(X.envelope.requestId),V.resolve(X.envelope)}}),Q.addEventListener("close",()=>{for(let P of Z.values())P.reject(Error("Hub connection closed"));Z.clear()}),Q.addEventListener("error",(P)=>{J(xA(P,f))})})().catch(J)})}async function y7(f){try{return(await Q6(f)).close(),!0}catch{return!1}}async function K7(f,$){let J=await IH(f),H=await Q6(J);try{return await H.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{H.close()}}function of(f){return f?JSON.parse(JSON.stringify(f)):{}}function Z6(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?of($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function U7(f,$){return f.error?.message??`hub command failed: ${$}`}function dA(f){let $=of(f);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let J=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...$,error:J.text.trim()};let H=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof H?.message==="string"&&H.message.trim())return{...$,error:H.message.trim()};return $}function rA(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let J=$;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function lA(f){let $=f.sessionId?.trim();if(!$)return;switch(f.event){case"iteration.started":return{sessionId:$,eventType:"runtime.chat.iteration_start",payload:of(f.payload)};case"iteration.finished":return{sessionId:$,eventType:"runtime.chat.iteration_end",payload:of(f.payload)};case"assistant.delta":return{sessionId:$,eventType:"runtime.chat.text_delta",payload:of(f.payload)};case"tool.started":return{sessionId:$,eventType:"runtime.chat.tool_call_start",payload:of(f.payload)};case"tool.finished":return{sessionId:$,eventType:"runtime.chat.tool_call_end",payload:of(f.payload)};case"approval.requested":return{sessionId:$,eventType:"approval.requested",payload:of(f.payload)};case"run.aborted":return{sessionId:$,eventType:"runtime.chat.aborted",payload:of(f.payload)};case"run.failed":return{sessionId:$,eventType:"runtime.chat.failed",payload:dA(f.payload)};case"run.completed":return{sessionId:$,eventType:"runtime.chat.completed",payload:of(f.payload)};default:return}}class xH{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new df({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-session-client",displayName:f.displayName??"hub session client",workspaceRoot:f.workspaceRoot,cwd:f.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:f.workspaceRoot,cwd:f.cwd,sessionConfig:{providerId:f.provider,modelId:f.model,apiKey:f.apiKey,cwd:f.cwd??f.workspaceRoot,workspaceRoot:f.workspaceRoot,systemPrompt:f.systemPrompt??"",mode:f.mode??"act",rules:f.rules,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawnAgent:f.enableSpawn!==!1,enableAgentTeams:f.enableTeams!==!1,disableMcpSettingsTools:f.disableMcpSettingsTools,missionLogIntervalSteps:f.missionStepInterval,missionLogIntervalMs:f.missionTimeIntervalMs},metadata:{source:f.source??"cli",provider:f.provider,model:f.model,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,prompt:void 0,interactive:f.interactive!==!1},runtimeOptions:{mode:f.mode,systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,autoApproveTools:f.autoApproveTools,toolExecutors:f.toolExecutors,configExtensions:f.configExtensions},modelSelection:{provider:f.provider,model:f.model,apiKey:f.apiKey},toolPolicies:f.toolPolicies}),J=Z6($.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession(f,$,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:$.prompt,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},f,J)).payload?.result}}async stopRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:f},f),{applied:!0}}async abortRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:f},f),{applied:!0}}async updateSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:f.sessionId,metadata:f.metadata},f.sessionId),{updated:!0}}async getSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.get",void 0,f);return Z6($.payload)}async readMessages(f){let $=f.trim();if(!$)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(U7(J,"session.messages"));let H=J.payload?.messages;return Array.isArray(H)?H:[]}async restore(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let H=f.config,W=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...H?{workspaceRoot:H.workspaceRoot,cwd:H.cwd,sessionConfig:{providerId:H.provider,modelId:H.model,apiKey:H.apiKey,cwd:H.cwd??H.workspaceRoot,workspaceRoot:H.workspaceRoot,systemPrompt:H.systemPrompt??"",mode:H.mode??"act",rules:H.rules,maxIterations:H.maxIterations,enableTools:H.enableTools,enableSpawnAgent:H.enableSpawn!==!1,enableAgentTeams:H.enableTeams!==!1,disableMcpSettingsTools:H.disableMcpSettingsTools,missionLogIntervalSteps:H.missionStepInterval,missionLogIntervalMs:H.missionTimeIntervalMs},metadata:{source:H.source??"cli",provider:H.provider,model:H.model,enableTools:H.enableTools,enableSpawn:H.enableSpawn,enableTeams:H.enableTeams,prompt:void 0,interactive:H.interactive!==!1},runtimeOptions:{mode:H.mode,systemPrompt:H.systemPrompt,maxIterations:H.maxIterations,enableTools:H.enableTools,enableSpawn:H.enableSpawn,enableTeams:H.enableTeams,autoApproveTools:H.autoApproveTools,configExtensions:H.configExtensions},modelSelection:{provider:H.provider,model:H.model,apiKey:H.apiKey},toolPolicies:H.toolPolicies}:{}},$);if(!W.ok)throw Error(U7(W,"session.restore"));let Q=Z6(W.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let Z=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,j=rA(W.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...Z?{messages:Z}:{},checkpoint:j}}async listSessions(f){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:f?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((H)=>Z6({session:H})).filter((H)=>Boolean(H?.sessionId))}async deleteSession(f,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:f,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(f){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:f.approvalId,approved:f.approved,payload:f.reason?{reason:f.reason}:void 0,responderClientId:f.responderClientId})}streamEvents(f,$){let J=new Set((f.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),H=this.client.subscribe((W)=>{let Q=lA(W);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;$.onEvent?.(Q)});return this.ensureMetadataApplied().catch((W)=>{$.onError?.(W instanceof Error?W:Error(String(W)))}),H}streamTeamProgress(f,$){let J=this.client.subscribe((H)=>{if(H.event!=="team.progress"||!H.payload)return;$.onProjection?.(H.payload)});return this.ensureMetadataApplied().catch((H)=>{$.onError?.(H instanceof Error?H:Error(String(H)))}),J}async createSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",f)).payload?.schedule}async listSchedules(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:f})).payload?.schedule}async updateSchedule(f,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:f,...$})).payload?.schedule}async pauseSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:f})).payload?.schedule}async resumeSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:f})).payload?.schedule}async deleteSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:f})).payload?.deleted===!0}async triggerScheduleNow(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:f})).payload?.execution}async listScheduleExecutions(f,$){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:f,limit:$});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let f=await this.client.command("schedule.active");return Array.isArray(f.payload?.executions)?f.payload?.executions:[]}async getUpcomingScheduledRuns(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:f});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}}class gH{client;constructor(f){this.client=new df({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.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(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}import{normalizeProviderId as PL}from"@cline/llms";var HV={};N(HV,{LocalRuntimeHost:()=>j0});import{homedir as $L}from"node:os";import{isAbsolute as JL,join as o9,resolve as HL}from"node:path";import{createSessionId as WL,isLikelyAuthError as QL,normalizeUserInput as ZL}from"@cline/shared";import{setHomeDirIfUnset as jL}from"@cline/shared/storage";var v7={};N(v7,{createContextCompactionPrepareTurn:()=>d2});import{createHandler as sA}from"@cline/llms";var G7=200000,h7=0.95;var vH=20000;var T7=8;function pA(f){return Math.max(1,Math.ceil(f.length/4))}function U$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
|
|
278
278
|
...[truncated ${f.length-$} chars]`}function iA(f){if(typeof f==="string")return U$(f,2000);return f.map(($)=>{switch($.type){case"text":return $.text;case"file":return`<file path="${$.path}">
|
package/dist/index.js
CHANGED
|
@@ -426,7 +426,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
426
426
|
`)[0]?.trim())}function M0(f){if(!f)return;let $={...f},J=$$(typeof $.title==="string"?$.title:void 0);if(J)$.title=J;else delete $.title;return Object.keys($).length>0?$:void 0}function C1(f){let $=M0(f.metadata)??{},J=f.title!==void 0?$$(f.title):dJ(f.prompt);if(J)$.title=J;return Object.keys($).length>0?$:void 0}function rJ(f){let $=b1(f);if($)return{agent:"teammate",sessionId:$.rootSessionId,taskType:"team"};let J=D8(f);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:f}}function lJ(f){return{version:1,updated_at:f.updatedAt,agent:f.context.agent,sessionId:f.context.sessionId,...f.context.taskType?{taskType:f.context.taskType}:{},messages:M8(f.messages),...f.systemPrompt?{system_prompt:f.systemPrompt}:{}}}function E7(f,$,J){BF(RF(f),{recursive:!0}),AF(f,`${JSON.stringify(lJ({updatedAt:$,context:J,messages:[]}),null,2)}
|
|
427
427
|
`,"utf8")}function S7(f,$){return yf.parse({version:1,session_id:f.sessionId,source:f.source,pid:f.pid,started_at:f.startedAt,ended_at:$?.endedAt??f.endedAt??void 0,exit_code:$?.exitCode??f.exitCode??void 0,status:$?.status??f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName??void 0,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt??void 0,metadata:$?.metadata??f.metadata??void 0,messages_path:f.messagesPath??void 0})}async function k7(f,$,J){let H=0;while(!0){let W=await f();if(W===void 0)return{updated:!1};let Q=await $(W);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(H+=1,H>=J)return Q;continue}return Q}}import{existsSync as UF}from"node:fs";import{readFile as GF}from"node:fs/promises";import{formatDisplayUserInput as m7}from"@cline/shared";class E1{listeners=new Set;subscribe(f,$){let J={listener:f,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit(f){let $=f.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$)continue;J.listener(f)}}get size(){return this.listeners.size}}async function J$(f){let $=f?.trim();if(!$||!UF($))return[];try{let J=(await GF($,"utf8")).trim();if(!J)return[];let H=JSON.parse(J);if(Array.isArray(H))return I7(H);if(H&&typeof H==="object"&&!Array.isArray(H)){let W=H.messages;if(Array.isArray(W))return I7(W)}return[]}catch{return[]}}function hF(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:m7(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:m7($.text)}})}}function I7(f){return f.map(hF)}function x7(f){return f?{...f}:void 0}async function g7(f,$){if(!(f.hookName==="tool_call"||!!f.parent_agent_id))return;await $.queueSpawnRequest(f);let H=await $.upsertSubagentSessionFromHook(f);if(!H)return;await $.appendSubagentHookAudit(H,f),await $.applySubagentStatus(H,f)}function L8(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function Lf(f){let $=L8(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function z8(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function _F(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function iJ(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function LF(f){let $=f.match(/\d{13,}/g);if(!$||$.length===0)return 0;let J=0;for(let H of $){let W=Number.parseInt(H,10);if(Number.isFinite(W)&&W>J)J=W}return J}function nJ(f){return{sessionId:f.session_id,source:f.source,pid:f.pid,startedAt:f.started_at,endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspace_root,teamName:f.team_name,enableTools:f.enable_tools,enableSpawn:f.enable_spawn,enableTeams:f.enable_teams,isSubagent:!1,prompt:f.prompt,metadata:f.metadata,messagesPath:f.messages_path,updatedAt:f.ended_at??f.started_at}}async function zF(f){let $=iJ(f);if($===0)return[];let J=d7(),W=(await TF(J,{withFileTypes:!0}).catch(()=>[])).filter((Z)=>Z.isDirectory()).map((Z)=>({entry:Z,recency:LF(Z.name.trim())})).sort((Z,j)=>j.recency-Z.recency||j.entry.name.localeCompare(Z.entry.name));return(await Promise.all(W.map(async({entry:Z})=>{let j=Z.name.trim();if(!j)return;let P=c7(J,j,`${j}.json`),X=await u7(P,"utf8").catch(()=>{return});if(!X)return;let V;try{V=JSON.parse(X)}catch{return}let Y=yf.safeParse(V);if(!Y.success)return;return nJ(Y.data)}))).filter((Z)=>Boolean(Z)).sort((Z,j)=>j.startedAt.localeCompare(Z.startedAt)).slice(0,$)}async function OF(f,$){let J=iJ($);if(J===0)return await f.listSessions(0),[];return(await f.listSessions(J)).slice(0,J)}function NF(f){if(typeof f==="string")return f.trim();let $=[];for(let J of f){if(!J||typeof J!=="object")continue;let H=J;if(H.type!=="text")continue;let W=H.text?.trim();if(W)$.push(W)}return $.join(`
|
|
428
428
|
`).trim()}function v7(f){return f.replace(/\s+/g," ").trim()}function qF(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function bF(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let H=v7(NF(J.content));if(!H)continue;let W=$==="user"?v7(DF(H)):H,Q=MF(W.split(`
|
|
429
|
-
`)[0]??W);return qF(Q,50)}return}function wF(f){let $=0;for(let J of f)$+=z8(J.metrics?.cost)??0;return $}function CF(f){let $,J;for(let H=f.length-1;H>=0;H-=1){let W=f[H];if(!$)$=Lf(W.modelInfo?.provider);if(!J)J=Lf(W.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function EF(f){return Lf(f?.provider)??Lf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function SF(f){return Lf(f?.model)??Lf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function pJ(f,$){let J=_F(f.metadata),H=L8($?.title)??L8(J?.title),W=z8($?.totalCost)??z8(J?.totalCost),Q=J||H!==void 0||W!==void 0?{...J??{},...H!==void 0?{title:H}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...f,provider:Lf($?.provider)??Lf(f.provider)??EF(J)??"",model:Lf($?.model)??Lf(f.model)??SF(J)??"",metadata:Q}}async function kF(f,$){return await Promise.all($.map(async(J)=>{let H=pJ(J),W=Boolean(L8(H.metadata?.title)),Q=Boolean(Lf(H.provider)),Z=Boolean(Lf(H.model)),j=z8(H.metadata?.totalCost),P=j!==void 0&&j>0;if(W&&Q&&Z&&P)return H;let X=await f.readSessionMessages(J.sessionId);if(X.length===0)return H;let V=CF(X),Y=wF(X);return pJ(J,{title:W?void 0:bF(X),provider:Q?void 0:V.provider,model:Z?void 0:V.model,totalCost:P||Y<=0?void 0:Y})}))}async function aJ(f,$={}){let J=iJ($.limit),H=await OF(f,J),W=$.includeManifestFallback===!0&&H.length<J?await zF(Math.min(Math.max(J*2,100),500)):[],Q=new Map;for(let j of[...H,...W]){if(Q.has(j.sessionId))continue;Q.set(j.sessionId,j)}let Z=W.length===0?H:Array.from(Q.values()).sort((j,P)=>P.startedAt.localeCompare(j.startedAt)).slice(0,J);if($.hydrate===!1)return Z.map((j)=>pJ(j));return await kF(f,Z)}async function mF(f){let $=f.trim();if(!$)return;let J=c7(d7(),$,`${$}.json`),H=await u7(J,"utf8").catch(()=>{return});if(!H)return;try{let W=yf.safeParse(JSON.parse(H));return W.success?W.data.messages_path:void 0}catch{return}}async function IF(f,$={}){let J=new Map;return await aJ({listSessions:async(W)=>{let Q=await f.listSessions(W);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(w1)},readSessionMessages:async(W)=>{let Q=J.get(W)?.messagesPath??await mF(W);return await J$(Q)}},$)}import{createSessionId as wy,resolveHubCommandTimeoutMs as Cy}from"@cline/shared";import{spawn as Yy}from"node:child_process";import{closeSync as By,mkdirSync as Ay,openSync as Ry}from"node:fs";import{basename as Fy,dirname as yy,join as Ky}from"node:path";import{fileURLToPath as Uy}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as Gy,isHubDaemonProcess as JQ,withResolvedClineBuildEnv as hy}from"@cline/shared";import{createHash as xF,randomBytes as gF}from"node:crypto";import{existsSync as vF}from"node:fs";import{chmod as uF,mkdir as tJ,readFile as a7,rm as sJ,writeFile as t7}from"node:fs/promises";import{dirname as s7,join as oJ}from"node:path";import{resolveClineDataDir as eJ,resolveClineDir as Bb}from"@cline/shared/storage";var l7="0.0.38
|
|
429
|
+
`)[0]??W);return qF(Q,50)}return}function wF(f){let $=0;for(let J of f)$+=z8(J.metrics?.cost)??0;return $}function CF(f){let $,J;for(let H=f.length-1;H>=0;H-=1){let W=f[H];if(!$)$=Lf(W.modelInfo?.provider);if(!J)J=Lf(W.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function EF(f){return Lf(f?.provider)??Lf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function SF(f){return Lf(f?.model)??Lf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function pJ(f,$){let J=_F(f.metadata),H=L8($?.title)??L8(J?.title),W=z8($?.totalCost)??z8(J?.totalCost),Q=J||H!==void 0||W!==void 0?{...J??{},...H!==void 0?{title:H}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...f,provider:Lf($?.provider)??Lf(f.provider)??EF(J)??"",model:Lf($?.model)??Lf(f.model)??SF(J)??"",metadata:Q}}async function kF(f,$){return await Promise.all($.map(async(J)=>{let H=pJ(J),W=Boolean(L8(H.metadata?.title)),Q=Boolean(Lf(H.provider)),Z=Boolean(Lf(H.model)),j=z8(H.metadata?.totalCost),P=j!==void 0&&j>0;if(W&&Q&&Z&&P)return H;let X=await f.readSessionMessages(J.sessionId);if(X.length===0)return H;let V=CF(X),Y=wF(X);return pJ(J,{title:W?void 0:bF(X),provider:Q?void 0:V.provider,model:Z?void 0:V.model,totalCost:P||Y<=0?void 0:Y})}))}async function aJ(f,$={}){let J=iJ($.limit),H=await OF(f,J),W=$.includeManifestFallback===!0&&H.length<J?await zF(Math.min(Math.max(J*2,100),500)):[],Q=new Map;for(let j of[...H,...W]){if(Q.has(j.sessionId))continue;Q.set(j.sessionId,j)}let Z=W.length===0?H:Array.from(Q.values()).sort((j,P)=>P.startedAt.localeCompare(j.startedAt)).slice(0,J);if($.hydrate===!1)return Z.map((j)=>pJ(j));return await kF(f,Z)}async function mF(f){let $=f.trim();if(!$)return;let J=c7(d7(),$,`${$}.json`),H=await u7(J,"utf8").catch(()=>{return});if(!H)return;try{let W=yf.safeParse(JSON.parse(H));return W.success?W.data.messages_path:void 0}catch{return}}async function IF(f,$={}){let J=new Map;return await aJ({listSessions:async(W)=>{let Q=await f.listSessions(W);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(w1)},readSessionMessages:async(W)=>{let Q=J.get(W)?.messagesPath??await mF(W);return await J$(Q)}},$)}import{createSessionId as wy,resolveHubCommandTimeoutMs as Cy}from"@cline/shared";import{spawn as Yy}from"node:child_process";import{closeSync as By,mkdirSync as Ay,openSync as Ry}from"node:fs";import{basename as Fy,dirname as yy,join as Ky}from"node:path";import{fileURLToPath as Uy}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as Gy,isHubDaemonProcess as JQ,withResolvedClineBuildEnv as hy}from"@cline/shared";import{createHash as xF,randomBytes as gF}from"node:crypto";import{existsSync as vF}from"node:fs";import{chmod as uF,mkdir as tJ,readFile as a7,rm as sJ,writeFile as t7}from"node:fs/promises";import{dirname as s7,join as oJ}from"node:path";import{resolveClineDataDir as eJ,resolveClineDir as Bb}from"@cline/shared/storage";var l7="0.0.38";var p7={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:l7,repository:{type:"git",url:"https://github.com/cline/sdk",directory:"packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{development:"./src/index.ts",types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{development:"./src/hub/index.ts",types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{development:"./src/hub/daemon/entry.ts",types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{development:"./src/services/telemetry/index.ts",types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"rm -rf dist && bun run ./bun.mts && bun tsc -p tsconfig.build.json",clean:"rm -rf dist node_modules",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:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@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",jiti:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var cF="CLINE_HUB_DISCOVERY_PATH",dF="CLINE_HUB_BUILD_ID",i7=30000,rF=15000,lF=100;function pF(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function iF(f){return xF("sha256").update(f).digest("hex").slice(0,12)}function nF(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function o7(){return gF(32).toString("hex")}function aF(f){return new Promise(($)=>setTimeout($,f))}function tF(f){return`${f}.lock`}async function sF(f){try{let $=JSON.parse(await a7(oJ(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function n7(f){await sJ(f,{recursive:!0,force:!0}).catch(()=>{return})}function m$(){return process.env[dF]?.trim()||String(p7.version)}function H$(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${iF(f)}`,J=process.env[cF]?.trim()||oJ(eJ(),"locks","hub","owners",`${pF($)}.json`);return{ownerId:$,discoveryPath:J}}function Rb(f=`hub-${Date.now().toString(36)}`){return H$(f)}async function Zf(f){try{let $=JSON.parse(await a7(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function e7(f,$){await tJ(s7(f),{recursive:!0}),await sJ(f,{force:!0}).catch(()=>{return}),await t7(f,`${JSON.stringify($,null,2)}
|
|
430
430
|
`,{encoding:"utf8",mode:384}),await uF(f,384)}async function rf(f){await sJ(f,{force:!0}).catch(()=>{return})}async function fQ(f,$){let J=tF(f);await tJ(s7(J),{recursive:!0});let H=Date.now()+rF;while(!0)try{await tJ(J,{recursive:!1}),await t7(oJ(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
431
431
|
`,"utf8");try{return await $()}finally{await n7(J)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let Z=await sF(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):i7+1;if(!Z||!nF(Z.pid)||j>i7){await n7(J);continue}if(Date.now()>=H)throw Error(`Timed out waiting for hub startup lock ${J}`);await aF(lF)}}async function Yf(f){try{let $=await fetch(oF(f));if(!$.ok)return;return await $.json()}catch{return}}function $0(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function oF(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function Fb(f){return vF(f)}import{CLINE_HUB_DEV_PORT as eF,CLINE_HUB_PORT as fy,resolveClineBuildEnv as $y}from"@cline/shared";var Jy="CLINE_HUB_HOST",Hy="CLINE_HUB_PORT",Wy="CLINE_HUB_PATHNAME",Qy="127.0.0.1",Zy=fy,jy="/hub";function $Q(f){return $y(f)==="development"?eF:Zy}function Py(f={}){return(f.env??process.env)[Jy]?.trim()||Qy}function O8(f={}){let J=(f.env??process.env)[Hy]?.trim();if(!J)return $Q(f);let H=Number.parseInt(J,10);if(!Number.isInteger(H)||H<1||H>65535)return $Q(f);return H}function Xy(f={}){return(f.env??process.env)[Wy]?.trim()||jy}function _0(f={},$={}){return{host:f.host??Py($),port:f.port??O8($),pathname:f.pathname??Xy($)}}var Vy="shared:cline";function Tb(f){let $=s0(f.trim());return H$(`workspace:${$||f.trim()}`)}function Bf(f=Vy){return H$(f)}var Ty=8000,Dy=200,My=3000,_y=100,Ly="--cline-hub-daemon";function zy(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function Oy(){try{let f=Ky(eJ(),"logs","hub-daemon.log");return Ay(yy(f),{recursive:!0}),{fd:Ry(f,"a"),logPath:f}}catch{return}}function S1(f){let $=f.buildId?.trim();return!!$&&$===m$()}async function Ny(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Yf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,_y))}return!1}async function k1(f,$){if(S1(f))return;if(await fH(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await Ny(f.url,My),await rf($).catch(()=>{return})}function qy(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return Uy(new URL(`./entry.${f}`,import.meta.url))}function by(f,$){let J=qy(),H=process.execPath?.trim();if(!H)throw Error("unable to resolve runtime executable for hub daemon");let W=Fy(H).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=W&&J.toLowerCase().endsWith(".ts"),j=Q?[Ly]:[...Z?["--conditions=development"]:[],J];return{launcher:H,args:[...j,"--cwd",f,...zy($)],cwd:f,env:{...hy(process.env),CLINE_NO_INTERACTIVE:"1",[Gy]:"1"}}}function N8(f,$={}){if(JQ())return;let J=by(f,$),H=Oy();try{Yy(J.launcher,J.args,{detached:!0,stdio:H?["ignore",H.fd,H.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(H)By(H.fd)}}function HQ(f,$={}){if(JQ())return;let J=Bf(),H=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=_0($),Q=$0(W.host,W.port,W.pathname);Zf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let V=await Yf(Z.url);if(V?.url&&S1(V)&&await L0(V.url,{authToken:Z.authToken}))return;if(V?.url)await k1({...V,authToken:Z.authToken},J.discoveryPath);else await rf(J.discoveryPath).catch(()=>{return})}let j=await Yf(Q);if(j?.url)await k1(j,J.discoveryPath);let X=!H&&W.port!==0?{...W,port:0}:W;N8(f,X)}).catch(()=>{})}async function Cb(f,$={}){let J=Bf(),H=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=_0($),Z=$0(Q.host,Q.port,Q.pathname),j=(A)=>{if(!H)I$(A.url,A.authToken);return A},P=await Zf(J.discoveryPath);if(P?.url){let A=await Yf(P.url);if(A?.url&&S1(A)&&await L0(A.url,{authToken:P.authToken}))return j({url:A.url,authToken:P.authToken});if(A?.url)await k1({...A,authToken:P.authToken},J.discoveryPath);else await rf(J.discoveryPath).catch(()=>{return})}let X=await Yf(Z);if(X?.url)await k1(X,J.discoveryPath);let Y=!W&&Q.port!==0?{...Q,port:0}:Q;N8(f,Y);let B=Date.now()+Ty;while(Date.now()<B){let A=await Zf(J.discoveryPath);if(A?.url){let U=await Yf(A.url);if(U?.url&&S1(U)&&await L0(U.url,{authToken:A.authToken}))return j({url:U.url,authToken:A.authToken})}let R=await Yf(Z);if(R?.url&&!S1(R))await k1(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,Dy))}throw Error("Timed out waiting for detached hub startup.")}function Ey(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function PQ(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return PQ(f.data);return String(f)}function Sy(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function WQ(f){let $=f,J=Sy($.reason);return new zf("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:$H,{closeCode:$.code,closeReason:J||void 0})}function ky(f,$){if(f instanceof zf)return f;if(f instanceof Error)return new zf("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new zf("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new zf("hub_connect_failed",J);let H=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new zf("hub_connect_failed",H?`Failed to connect to hub at ${$.toString()} (${H} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var my=8000,Iy=200,QQ="*",ZQ=8000,xy="cline-hub-auth.",XQ=new Map,VQ=new Set,gy=3000,vy=3000,uy=100,$H="Hub connection closed",cy=250,dy=5000,jQ=0.5;class zf extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function ry(f){return f instanceof zf}class q8 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function YQ(f,$){return f instanceof q8&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function BQ(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=WH(f.toString());return J?XQ.get(J):void 0}function ly(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function WH(f){if(!ly(f))return;let $=new URL(x$(f));return $.search="",$.hash="",$.toString()}function JH(f){let $=WH(f);return!!$&&VQ.has($)}function I$(f,$){let J=WH(f);if(J){if(VQ.add(J),$?.trim())XQ.set(J,$)}return f}class J0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new zf("hub_connection_closed",$H);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||BQ(f);f.hash="";let H=new(Ey())(f.toString(),$?[`${xy}${$}`]:void 0);this.socket=H;let W=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,P=setTimeout(()=>{if(j)return;j=!0,W=!0,this.lastCloseError=new zf("hub_connect_timeout",`Timed out connecting to hub after ${ZQ}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{H.close()}catch{}Z(this.lastCloseError)},ZQ);H.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(P),Q()}),H.addEventListener("error",(X)=>{if(j)return;j=!0,clearTimeout(P),this.lastCloseError=ky(X,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),H.addEventListener("close",(X)=>{if(j)return;if(j=!0,clearTimeout(P),!W)this.lastCloseError=WQ(X),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),H.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(PQ(Q)))}),H.addEventListener("close",(Q)=>{if(this.socket!==H)return;if(!W)this.lastCloseError=WQ(Q),this.sawSocketClose=!0;this.registered=!1;for(let Z of this.pendingReplies.values())Z.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,H={listener:f,sessionId:J};return this.listeners.add(H),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(H))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,H){let W=0,Q=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,H)}catch(Z){if(!Q||W>=1||!await this.recoverLocalHubTransport(Z))throw Z;W+=1}}async commandOnce(f,$,J,H){await this.connect();let W=wy("hubreq_"),Q=Cy(f,H?.timeoutMs),Z=new Promise((P,X)=>{let V=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;X(new q8(f,"hub_command_timeout",`Hub command ${f} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(W,{resolve:(Y)=>{if(V)clearTimeout(V);P(Y)},reject:(Y)=>{if(V)clearTimeout(V);X(Y)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:W,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(P){throw this.pendingReplies.delete(W),P}let j=await Z;if(!j.ok)throw new q8(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!JH(this.currentUrl)||!ry(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await m1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,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 f=Math.min(cy*2**this.reconnectAttempt,dy),$=Math.round(f*(1-jQ)+Math.random()*f*jQ);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!JH(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await m1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new zf("hub_connection_closed",$H),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.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(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new zf("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),H=(this.subscriptionCounts.get(J)??0)+$;if(H<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,H),$>0&&H===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??QQ}subscriptionSessionIdFromKey(f){return f===QQ?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function x$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function L0(f,$){let J=new J0({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function HH(f,$){let J=x$(f),H=await Yf(J);if(!H)return{status:"unreachable",url:J};let W=m$(),Q=H.buildId?.trim();if(!Q||Q!==W)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await L0(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function py(f){let $=Date.now()+my;while(Date.now()<$){let J=await Zf(f.discoveryPath);if(J?.url){let H=await HH(J.url,{verifyConnection:!0,authToken:J.authToken});if(H.status==="compatible")return I$(H.url,J.authToken)}await new Promise((H)=>setTimeout(H,Iy))}return}async function iy(f){let $=Date.now()+vy;while(Date.now()<$){if(!(await Yf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,uy))}return!1}function ny(f,$){try{return x$(f)===x$($)}catch{return!1}}function ay(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let H=J;if(H.status==="running"||H.status==="idle")return!0;return Array.isArray(H.participants)&&H.participants.length>0})}async function ty(f,$,J){let H=new J0({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let W=await H.command("session.list",{limit:500},void 0,{timeoutMs:gy});return!ay(W.payload)}catch{return!1}finally{await H.dispose().catch(()=>{return})}}async function QH(f={}){if(f.endpoint?.trim()){let W=await HH(f.endpoint);return W.status==="compatible"?W.url:void 0}let $=Bf(),J=await Zf($.discoveryPath);if(!J?.url)return;let H=await HH(J.url);if(H.status==="compatible")return I$(H.url,J.authToken);if(H.status==="build_mismatch")await rf($.discoveryPath).catch(()=>{return});return}async function m1(f={}){let $=await QH(f);if($&&await L0($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Bf();return N8(f.workspaceRoot??process.cwd()),await py(J)}async function fH(f,$){let J=new URL(f),H=$?.trim()||BQ(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:H?{authorization:`Bearer ${H}`}:void 0})).ok}async function sy(){let f=Bf(),$=await Zf(f.discoveryPath);if(!$?.url)return!1;try{if(await fH($.url,$.authToken))return!0}catch{}return!1}async function AQ(f){if(!JH(f.url))return;let $=Bf(),J=await Zf($.discoveryPath);if(!J?.url||!ny(J.url,f.url))return;if(!await ty(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await sy())return;if(!await iy(J.url))return;return await rf($.discoveryPath).catch(()=>{return}),await m1({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}import{createSessionId as RQ,HUB_CHECKPOINT_CAPABILITY as $K,HUB_COMPACTION_CAPABILITY as JK,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as HK,HUB_HOOK_CAPABILITY_PREFIX as WK,HUB_MISTAKE_LIMIT_CAPABILITY as QK,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ZK,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as jK,isHubToolExecutorName as PK}from"@cline/shared";function oy(f){return f?JSON.parse(JSON.stringify(f)):void 0}function ey(f){return f?JSON.parse(JSON.stringify(f)):void 0}function fK(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,H=(Array.isArray($?.history)?$.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let j=typeof Z.ref==="string"?Z.ref.trim():"",P=Number(Z.createdAt),X=Number(Z.runCount);if(!j||!Number.isFinite(P)||!Number.isInteger(X))return[];return[{ref:j,createdAt:P,runCount:X,...Z.kind==="stash"||Z.kind==="commit"?{kind:Z.kind}:{}}]}),W=H.at(-1),Q=f?.checkpointEnabled===!0?!0:void 0;if(!Q&&H.length===0)return;return{...Q?{enabled:Q}:{},...W?{latest:W}:{},history:H}}function z0(f){let{session:$}=f,J=oy($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:ey(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...(()=>{let H=fK(J);return H?{checkpoint:H}:{}})()}}function ZH(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function g$(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var XK=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function FQ(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function yQ(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function KQ(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function W$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function UQ(f,$){let J={manifest:[],handlers:new Map};for(let W of Object.keys($.toolExecutors??{}).filter(PK)){let Q=$.toolExecutors?.[W];if(typeof Q!=="function")continue;W$(J,{kind:"toolExecutor",executor:W,capabilityName:`${ZK}${W}`},async({payload:Z,abortSignal:j})=>{let P=Array.isArray(Z.args)?[...Z.args]:[],X={...KQ(Z.context),signal:j};return{result:await Q(...P,X)}})}for(let W of f?.extraTools??[])W$(J,{kind:"tool",name:W.name,description:W.description,inputSchema:g$(W.inputSchema)??{},...W.lifecycle?{lifecycle:g$(W.lifecycle)}:{},capabilityName:`${HK}${W.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let P={...KQ(Q.context),signal:Z};return{result:await W.execute(Q.input,{...P,emitUpdate:(V)=>{j({update:V})}})}});let H=f?.hooks;if(H)for(let W of XK){let Q=H[W];if(typeof Q!=="function")continue;W$(J,{kind:"hook",name:W,capabilityName:`${WK}${W}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let W=f.compaction.compact;W$(J,{kind:"compaction",capabilityName:JK,config:FQ(f.compaction)},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let W=f.checkpoint.createCheckpoint;W$(J,{kind:"checkpoint",capabilityName:$K,config:FQ(f.checkpoint)},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let W=f.onConsecutiveMistakeLimitReached;W$(J,{kind:"mistakeLimit",capabilityName:QK},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.userInstructionService){let W=f.userInstructionService;W$(J,{kind:"userInstructionService",capabilityName:jK},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return J}function VK(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return"Capability request was cancelled."}function YK(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function BK(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function AK(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,H=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||H===void 0)return;return{inputTokens:J,outputTokens:H,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function RK(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,H=BK(J)?J:J==="failed"?"error":"completed",W=AK(f?.usage??$?.usage);return{type:"done",reason:H,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:W}}function jH(f,$){return f.error?.message??`hub command failed: ${$}`}function I1(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function TQ(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:Pf.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:I1(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:I1(f.status)==="completed"?0:I1(f.status)==="failed"?1:void 0,status:I1(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function Q$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function FK(f){let $=Q$(f?.snapshot);if($)return ZH($);let J=f?.session;return J?TQ(J):void 0}function GQ(f,$,J){let H=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return yf.parse({version:1,session_id:f,source:$.source??Pf.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:I1(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:H,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function hQ(f,$){return yf.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class Z${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new E1;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=Vf(f.capabilities)??{},this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new J0({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!YQ(f,"session.create"))return!1;let $=await AQ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=UQ(f.localRuntime,$),H=f.config.sessionId?.trim()||RQ(),W=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:g$({...f.config,sessionId:H}),metadata:{...f.sessionMetadata??{},source:f.source??Pf.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:g$(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(H,$,J.handlers);let Q;try{Q=await W()}catch(X){if(this.cleanupPlannedSession(H),await this.recoverLocalHubStartupDeadlock(X)){this.registerPlannedSession(H,$,J.handlers);try{Q=await W()}catch(V){throw this.cleanupPlannedSession(H),V}}else throw X}let Z=Q$(Q.payload?.snapshot),j=Q.payload?.session,P=(Z?.sessionId??j?.sessionId)?.trim();if(!P)throw this.cleanupPlannedSession(H),Error("Hub runtime did not return a session id.");if(P!==H)this.cleanupPlannedSession(H),this.registerPlannedSession(P,$,J.handlers);return{sessionId:P,manifest:Z?hQ(Z,f):GQ(P,f,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let H=f.start,W=H?this.resolveCapabilities(H):void 0,Q=H?UQ(H.localRuntime,W??{}):{manifest:[],handlers:new Map},Z=H?H.config.sessionId?.trim()||RQ():void 0;if(Z&&W)this.sessionCapabilities.set(Z,W);if(Z&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Z,Q.handlers),this.ensureSessionSubscription(Z);let j;try{j=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...H?{workspaceRoot:H.config.workspaceRoot?.trim()||H.config.cwd,cwd:H.config.cwd??f.cwd,sessionConfig:g$({...H.config,sessionId:Z}),metadata:{...H.sessionMetadata??{},source:H.source??Pf.CORE,provider:H.config.providerId,model:H.config.modelId,enableTools:H.config.enableTools,enableSpawn:H.config.enableSpawnAgent,enableTeams:H.config.enableAgentTeams,teamName:H.config.teamName,prompt:H.prompt,interactive:H.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...H.localRuntime?.configExtensions?{configExtensions:H.localRuntime.configExtensions}:{}},toolPolicies:g$(H.toolPolicies)}:{}},$)}catch(A){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw A}if(!j.ok){let A=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error(A)}let P=Q$(j.payload?.snapshot),X=j.payload?.session,V=(P?.sessionId??X?.sessionId)?.trim();if(J&&!V){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error("Hub checkpoint restore returned no session id")}if(V&&Z&&V!==Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);if(V&&W)this.sessionCapabilities.set(V,W);if(V&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(V,Q.handlers);if(V)this.ensureSessionSubscription(V);let Y=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,B=j.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:P?hQ(P,H??{}):GQ(V,H??{},X),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:Y,checkpoint:B}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=Q$($.payload?.snapshot);if(J?.usage)return{...J.usage};let H=$.payload?.session;return H?.usage?{...H.usage}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:typeof $==="string"?$:void 0},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $=await this.client.command("session.get",void 0,f);return FK($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((W)=>{let Q=Q$(W);return Q?[ZH(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(TQ)}async listSettings(f){let $=await this.client.command("settings.list",yQ(f));if(!$.ok)throw Error(jH($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",yQ(f));if(!$.ok)throw Error(jH($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(jH(J,"session.messages"));let H=J.payload?.messages;return Array.isArray(H)?H:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((H)=>{this.handleHubEvent(H)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return Vf(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:RK(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f);return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f);return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=Q$(f.payload?.snapshot),H=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:H?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",H=f.payload?.redacted===!0;if(!J&&!H)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:H}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=Q$(f.payload?.snapshot),H=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:H?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:$,reason:J,ts:f.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let H=typeof f.payload?.requestId==="string"?f.payload.requestId:"",W=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!H)return;let Q=this.sessionClientContributionHandlers.get($)?.get(W);if(!Q){await this.client.command("capability.respond",{requestId:H,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${$}.`},$).catch(()=>{});return}let Z=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(H,j);let P=(X)=>{this.client.command("capability.progress",{requestId:H,payload:X},$)};try{let X=await Q({payload:Z,abortSignal:j.signal,progress:P});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:H,ok:!0,payload:X},$)}catch(X){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:H,ok:!1,error:X instanceof Error?X.message:String(X)},$)}finally{this.activeCapabilityAbortControllers.delete(H)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(VK(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let H=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",W=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",Q=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!H||!W||!Q)return;let Z=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},j=YK(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:$,toolCallId:W,toolName:Q,toolInput:j});let P=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:W,toolName:Q,input:j,policy:Z})).catch((X)=>({approved:!1,reason:X instanceof Error?X.message:`Tool approval request failed: ${String(X)}`}));await this.client.command("approval.respond",{approvalId:H,approved:P.approved,reason:P.reason},$).catch(()=>{})}}class b8 extends Z${constructor(f){super({url:x$(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}import{existsSync as yK,mkdirSync as KK}from"node:fs";import{join as UK}from"node:path";import{asBool as x1,asOptionalString as lf,asString as H0,ensureSessionSchema as GK,loadSqliteDb as hK,nowIso as w8,toBoolInt as g1}from"@cline/shared/db";import{resolveDbDataDir as TK}from"@cline/shared/storage";class O0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??TK()}init(){this.getRawDb()}ensureSessionsDir(){if(!yK(this.sessionsDirPath))KK(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return UK(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=hK(this.sessionDbPath());return GK(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=w8();this.run(`INSERT OR REPLACE INTO sessions (
|
|
432
432
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cline/core",
|
|
3
3
|
"description": "Cline Core SDK for Node Runtime",
|
|
4
|
-
"version": "0.0.38
|
|
4
|
+
"version": "0.0.38",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/cline/sdk",
|
|
@@ -48,9 +48,9 @@
|
|
|
48
48
|
"test:watch": "vitest --config vitest.config.ts"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@cline/agents": "
|
|
52
|
-
"@cline/shared": "
|
|
53
|
-
"@cline/llms": "
|
|
51
|
+
"@cline/agents": "workspace:*",
|
|
52
|
+
"@cline/shared": "workspace:*",
|
|
53
|
+
"@cline/llms": "workspace:*",
|
|
54
54
|
"@opentelemetry/api": "^1.9.0",
|
|
55
55
|
"@opentelemetry/api-logs": "^0.214.0",
|
|
56
56
|
"@opentelemetry/exporter-logs-otlp-http": "^0.214.0",
|