@cline/core 0.0.52-nightly.1782444026 → 0.0.52

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.
@@ -496,7 +496,7 @@ ${JSON.stringify(J,null,2)}`}startClaimLeaseHeartbeat($){let Q=Math.max(1000,Mat
496
496
  updated_at = ?
497
497
  WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,Q,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,Q){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(Q,z0(),$)}attachReportPathToRun($,Q){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(Q,z0(),$)}}class A5{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new K5({dbPath:$.dbPath});let Q=$.specs;this.reconciler=new x7({store:this.store,specs:Q}),this.materializer=new j5({store:this.store}),this.eventIngress=new E7({store:this.store,logger:$.logger}),this.runner=new V5({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:Q,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new g7({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Z)=>{let J=$.logger;if(J)if(J.error)J.error("cron.watcher.failed",{error:Z});else J.log("cron.watcher.failed",{error:Z})}})}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($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var XK={};P(XK,{manifestToSessionRecord:()=>XZ,listSessionHistoryFromBackend:()=>p7,listSessionHistory:()=>jZ,hydrateSessionHistory:()=>YK});import{readdir as DE,readFile as ZK}from"node:fs/promises";import{join as JK}from"node:path";import{formatDisplayUserInput as RE,normalizeUserInput as _E}from"@cline/shared";import{resolveSessionDataDir as WK}from"@cline/shared/storage";import{existsSync as FE}from"node:fs";import{readFile as fE}from"node:fs/promises";import{formatDisplayUserInput as tG}from"@cline/shared";class F5{listeners=new Set;subscribe($,Q){let Z={listener:$,sessionId:Q?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let Q=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==Q)continue;Z.listener($)}}get size(){return this.listeners.size}}async function P$($){let Q=$?.trim();if(!Q||!FE(Q))return[];try{let Z=(await fE(Q,"utf8")).trim();if(!Z)return[];let J=JSON.parse(Z);if(Array.isArray(J))return eG(J);if(J&&typeof J==="object"&&!Array.isArray(J)){let W=J.messages;if(Array.isArray(W))return eG(W)}return[]}catch{return[]}}function UE($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:tG($.content)};return{...$,content:$.content.map((Q)=>{if(Q.type!=="text"||typeof Q.text!=="string")return Q;return{...Q,text:tG(Q.text)}})}}function eG($){return $.map(UE)}function u7($){return $?{...$}:void 0}async function $K($,Q){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await Q.queueSpawnRequest($);let J=await Q.upsertSubagentSessionFromHook($);if(!J)return;await Q.appendSubagentHookAudit(J,$),await Q.applySubagentStatus(J,$)}function f5($){if(typeof $!=="string")return;let Q=$.trim();return Q.length>0?Q:void 0}function r0($){let Q=f5($);if(!Q)return;return Q.toLowerCase()==="unknown"?void 0:Q}function YZ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function TE($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function l7($){let Q=$??200;return Number.isFinite(Q)?Math.max(0,Math.floor(Q)):200}function LE($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function zE($){return $.isSubagent!==!0&&!f5($.parentSessionId)}function OE($){let Q=$.match(/\d{13,}/g);if(!Q||Q.length===0)return 0;let Z=0;for(let J of Q){let W=Number.parseInt(J,10);if(Number.isFinite(W)&&W>Z)Z=W}return Z}function XZ($){return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name,enableTools:$.enable_tools,enableSpawn:$.enable_spawn,enableTeams:$.enable_teams,isSubagent:!1,prompt:$.prompt,metadata:$.metadata,messagesPath:$.messages_path,updatedAt:$.ended_at??$.started_at}}async function qE($){let Q=l7($);if(Q===0)return[];let Z=WK(),W=(await DE(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:OE(X.name.trim())})).sort((X,j)=>j.recency-X.recency||j.entry.name.localeCompare(X.entry.name));return(await Promise.all(W.map(async({entry:X})=>{let j=X.name.trim();if(!j)return;let V=JK(Z,j,`${j}.json`),B=await ZK(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=C0.safeParse(H);if(!G.success)return;return XZ(G.data)}))).filter((X)=>Boolean(X)).sort((X,j)=>j.startedAt.localeCompare(X.startedAt)).slice(0,Q)}async function ME($,Q,Z){let J=l7(Q);if(J===0)return await $.listSessions(0),[];let W=Z.includeSubagents?J:LE(J),Y=await $.listSessions(W);return(Z.includeSubagents?Y:Y.filter(zE)).slice(0,J)}function EE($){if(typeof $==="string")return $.trim();let Q=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let J=Z;if(J.type!=="text")continue;let W=J.text?.trim();if(W)Q.push(W)}return Q.join(`
498
498
  `).trim()}function QK($){return $.replace(/\s+/g," ").trim()}function NE($,Q){if($.length<=Q)return $;return`${$.slice(0,Math.max(0,Q-3)).trimEnd()}...`}function PE($){for(let Q of["user","assistant"])for(let Z of $){if(Z.role!==Q)continue;let J=QK(EE(Z.content));if(!J)continue;let W=Q==="user"?QK(RE(J)):J,Y=_E(W.split(`
499
- `)[0]??W);return NE(Y,50)}return}function CE($){let Q=0;for(let Z of $)Q+=YZ(Z.metrics?.cost)??0;return Q}function wE($){let Q,Z;for(let J=$.length-1;J>=0;J-=1){let W=$[J];if(!Q)Q=r0(W.modelInfo?.provider);if(!Z)Z=r0(W.modelInfo?.id);if(Q&&Z)break}return{provider:Q,model:Z}}function SE($){return r0($?.provider)??r0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function yE($){return r0($?.model)??r0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function d7($,Q){let Z=TE($.metadata),J=f5(Q?.title)??f5(Z?.title),W=YZ(Q?.totalCost)??YZ(Z?.totalCost),Y=Z||J!==void 0||W!==void 0?{...Z??{},...J!==void 0?{title:J}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:r0(Q?.provider)??r0($.provider)??SE(Z)??"",model:r0(Q?.model)??r0($.model)??yE(Z)??"",metadata:Y}}function bE($){let Q=$.content;if(!Array.isArray(Q))return!1;return Q.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function hE($,Q){if($.status!=="running"||$.interactive!==!0)return!1;let Z=Q.at(-1);return Z?.role==="assistant"&&!bE(Z)}async function kE($,Q){return await Promise.all(Q.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let J=await $.readSessionMessages(Z.sessionId);return hE(Z,J)?{...Z,status:"idle"}:Z}))}async function YK($,Q){return await Promise.all(Q.map(async(Z)=>{let J=d7(Z),W=Boolean(f5(J.metadata?.title)),Y=Boolean(r0(J.provider)),X=Boolean(r0(J.model)),j=YZ(J.metadata?.totalCost),V=j!==void 0&&j>0;if(W&&Y&&X&&V)return J;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return J;let H=wE(B),G=CE(B);return d7(Z,{title:W?void 0:PE(B),provider:Y?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function jZ($,Q={}){let Z=l7(Q.limit),J=Q.includeSubagents===!0,W=await ME($,Z,{includeSubagents:J}),Y=Q.includeManifestFallback===!0&&W.length<Z?await qE(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...W,...Y]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let j=Y.length===0?W:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await kE($,j);if(Q.hydrate===!1)return V.map((B)=>d7(B));return await YK($,V)}async function IE($){let Q=$.trim();if(!Q)return;let Z=JK(WK(),Q,`${Q}.json`),J=await ZK(Z,"utf8").catch(()=>{return});if(!J)return;try{let W=C0.safeParse(JSON.parse(J));return W.success?W.data.messages_path:void 0}catch{return}}async function p7($,Q={}){let Z=new Map;return await jZ({listSessions:async(W)=>{let Y=await $.listSessions(W);Z.clear();for(let X of Y)Z.set(X.sessionId,X);return Y.map(U6)},readSessionMessages:async(W)=>{let Y=Z.get(W)?.messagesPath??await IE(W);return await P$(Y)}},Q)}var _A={};P(_A,{resolveSessionBackend:()=>N3,createRuntimeHost:()=>J4});import{captureSdkError as DA}from"@cline/shared";import{createSessionId as wN,isHubProtocolCompatible as SN,resolveClineBuildEnv as yN,resolveHubCommandTimeoutMs as bN}from"@cline/shared";import{spawn as jN}from"node:child_process";import{closeSync as VN,mkdirSync as BN,openSync as HN}from"node:fs";import{basename as GN,dirname as KN,join as AN}from"node:path";import{fileURLToPath as FN}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fN,isHubDaemonProcess as TK,isHubProtocolCompatible as UN,resolveClineBuildEnv as LK,withResolvedClineBuildEnv as DN}from"@cline/shared";import{createHash as xE,randomBytes as gE}from"node:crypto";import{existsSync as mE}from"node:fs";import{chmod as vE,mkdir as r7,readFile as GK,rm as i7,writeFile as KK}from"node:fs/promises";import{dirname as AK,join as n7}from"node:path";import{resolveClineDataDir as M2,resolveClineDir as FK}from"@cline/shared/storage";var VK="0.0.52-nightly.1782444026";var U5={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:VK,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var cE="CLINE_HUB_DISCOVERY_PATH",uE="CLINE_HUB_BUILD_ID",BK=30000,dE=15000,lE=100;function pE($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function rE($){return xE("sha256").update($).digest("hex").slice(0,12)}function iE($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function VZ(){return gE(32).toString("hex")}function nE($){return new Promise((Q)=>setTimeout(Q,$))}function aE($){return`${$}.lock`}async function sE($){try{let Q=JSON.parse(await GK(n7($,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function HK($){await i7($,{recursive:!0,force:!0}).catch(()=>{return})}function BZ(){return process.env[uE]?.trim()||String(U5.version)}function d1($=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${rE($)}`,Z=process.env[cE]?.trim()||n7(M2(),"locks","hub","owners",`${pE(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}function fK($=`hub-${Date.now().toString(36)}`){return d1($)}async function F0($){try{let Q=JSON.parse(await GK($,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function HZ($,Q){await r7(AK($),{recursive:!0}),await i7($,{force:!0}).catch(()=>{return}),await KK($,`${JSON.stringify(Q,null,2)}
499
+ `)[0]??W);return NE(Y,50)}return}function CE($){let Q=0;for(let Z of $)Q+=YZ(Z.metrics?.cost)??0;return Q}function wE($){let Q,Z;for(let J=$.length-1;J>=0;J-=1){let W=$[J];if(!Q)Q=r0(W.modelInfo?.provider);if(!Z)Z=r0(W.modelInfo?.id);if(Q&&Z)break}return{provider:Q,model:Z}}function SE($){return r0($?.provider)??r0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function yE($){return r0($?.model)??r0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function d7($,Q){let Z=TE($.metadata),J=f5(Q?.title)??f5(Z?.title),W=YZ(Q?.totalCost)??YZ(Z?.totalCost),Y=Z||J!==void 0||W!==void 0?{...Z??{},...J!==void 0?{title:J}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:r0(Q?.provider)??r0($.provider)??SE(Z)??"",model:r0(Q?.model)??r0($.model)??yE(Z)??"",metadata:Y}}function bE($){let Q=$.content;if(!Array.isArray(Q))return!1;return Q.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function hE($,Q){if($.status!=="running"||$.interactive!==!0)return!1;let Z=Q.at(-1);return Z?.role==="assistant"&&!bE(Z)}async function kE($,Q){return await Promise.all(Q.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let J=await $.readSessionMessages(Z.sessionId);return hE(Z,J)?{...Z,status:"idle"}:Z}))}async function YK($,Q){return await Promise.all(Q.map(async(Z)=>{let J=d7(Z),W=Boolean(f5(J.metadata?.title)),Y=Boolean(r0(J.provider)),X=Boolean(r0(J.model)),j=YZ(J.metadata?.totalCost),V=j!==void 0&&j>0;if(W&&Y&&X&&V)return J;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return J;let H=wE(B),G=CE(B);return d7(Z,{title:W?void 0:PE(B),provider:Y?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function jZ($,Q={}){let Z=l7(Q.limit),J=Q.includeSubagents===!0,W=await ME($,Z,{includeSubagents:J}),Y=Q.includeManifestFallback===!0&&W.length<Z?await qE(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...W,...Y]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let j=Y.length===0?W:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await kE($,j);if(Q.hydrate===!1)return V.map((B)=>d7(B));return await YK($,V)}async function IE($){let Q=$.trim();if(!Q)return;let Z=JK(WK(),Q,`${Q}.json`),J=await ZK(Z,"utf8").catch(()=>{return});if(!J)return;try{let W=C0.safeParse(JSON.parse(J));return W.success?W.data.messages_path:void 0}catch{return}}async function p7($,Q={}){let Z=new Map;return await jZ({listSessions:async(W)=>{let Y=await $.listSessions(W);Z.clear();for(let X of Y)Z.set(X.sessionId,X);return Y.map(U6)},readSessionMessages:async(W)=>{let Y=Z.get(W)?.messagesPath??await IE(W);return await P$(Y)}},Q)}var _A={};P(_A,{resolveSessionBackend:()=>N3,createRuntimeHost:()=>J4});import{captureSdkError as DA}from"@cline/shared";import{createSessionId as wN,isHubProtocolCompatible as SN,resolveClineBuildEnv as yN,resolveHubCommandTimeoutMs as bN}from"@cline/shared";import{spawn as jN}from"node:child_process";import{closeSync as VN,mkdirSync as BN,openSync as HN}from"node:fs";import{basename as GN,dirname as KN,join as AN}from"node:path";import{fileURLToPath as FN}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fN,isHubDaemonProcess as TK,isHubProtocolCompatible as UN,resolveClineBuildEnv as LK,withResolvedClineBuildEnv as DN}from"@cline/shared";import{createHash as xE,randomBytes as gE}from"node:crypto";import{existsSync as mE}from"node:fs";import{chmod as vE,mkdir as r7,readFile as GK,rm as i7,writeFile as KK}from"node:fs/promises";import{dirname as AK,join as n7}from"node:path";import{resolveClineDataDir as M2,resolveClineDir as FK}from"@cline/shared/storage";var VK="0.0.52";var U5={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:VK,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var cE="CLINE_HUB_DISCOVERY_PATH",uE="CLINE_HUB_BUILD_ID",BK=30000,dE=15000,lE=100;function pE($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function rE($){return xE("sha256").update($).digest("hex").slice(0,12)}function iE($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function VZ(){return gE(32).toString("hex")}function nE($){return new Promise((Q)=>setTimeout(Q,$))}function aE($){return`${$}.lock`}async function sE($){try{let Q=JSON.parse(await GK(n7($,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function HK($){await i7($,{recursive:!0,force:!0}).catch(()=>{return})}function BZ(){return process.env[uE]?.trim()||String(U5.version)}function d1($=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${rE($)}`,Z=process.env[cE]?.trim()||n7(M2(),"locks","hub","owners",`${pE(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}function fK($=`hub-${Date.now().toString(36)}`){return d1($)}async function F0($){try{let Q=JSON.parse(await GK($,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function HZ($,Q){await r7(AK($),{recursive:!0}),await i7($,{force:!0}).catch(()=>{return}),await KK($,`${JSON.stringify(Q,null,2)}
500
500
  `,{encoding:"utf8",mode:384}),await vE($,384)}async function S0($){await i7($,{force:!0}).catch(()=>{return})}async function GZ($,Q){let Z=aE($);await r7(AK(Z),{recursive:!0});let J=Date.now()+dE;while(!0)try{await r7(Z,{recursive:!1}),await KK(n7(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
501
501
  `,"utf8");try{return await Q()}finally{await HK(Z)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let X=await sE(Z),j=X?Date.now()-Date.parse(X.acquiredAt):BK+1;if(!X||!iE(X.pid)||j>BK){await HK(Z);continue}if(Date.now()>=J)throw Error(`Timed out waiting for hub startup lock ${Z}`);await nE(lE)}}async function l1($,Q){try{let Z=await fetch(Q?.authToken?a7($):KZ($),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let J=await Z.json();if(typeof J.protocolVersion!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string")return;return{protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,host:J.host,port:J.port,url:J.url,hubId:typeof J.hubId==="string"?J.hubId:void 0,authToken:typeof J.authToken==="string"?J.authToken:void 0,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:typeof J.startedAt==="string"?J.startedAt:void 0,updatedAt:typeof J.updatedAt==="string"?J.updatedAt:void 0}}catch{return}}function Y1($,Q,Z="/hub"){return new URL(`ws://${$}:${Q}${Z}`).toString()}function KZ($){let Q=new URL($);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function a7($){let Q=new URL(KZ($));return Q.pathname="/status",Q.toString()}function UK($){return mE($)}import{CLINE_HUB_DEV_PORT as oE,CLINE_HUB_PORT as tE,resolveClineBuildEnv as eE}from"@cline/shared";var $N="CLINE_HUB_HOST",QN="CLINE_HUB_PORT",ZN="CLINE_HUB_PATHNAME",s7="127.0.0.1",o7=tE,t7="/hub";function DK($){return eE($)==="development"?oE:o7}function e7($={}){return($.env??process.env)[$N]?.trim()||s7}function p8($={}){let Z=($.env??process.env)[QN]?.trim();if(!Z)return DK($);let J=Number.parseInt(Z,10);if(!Number.isInteger(J)||J<1||J>65535)return DK($);return J}function $3($={}){return($.env??process.env)[ZN]?.trim()||t7}function i0($={},Q={}){return{host:$.host??e7(Q),port:$.port??p8(Q),pathname:$.pathname??$3(Q)}}import{join as JN}from"node:path";var WN="shared:cline",YN="CLINE_HUB_DISCOVERY_PATH",XN="hub-production";function RK($){let Q=g1($.trim());return d1(`workspace:${Q||$.trim()}`)}function y0($=WN){return d1($)}function n0(){return{ownerId:XN,discoveryPath:process.env[YN]?.trim()||JN(M2(),"locks","hub","production.json")}}var RN=8000,_N=200,TN=3000,LN=100,zN=[100,250,500,1000,2000],ON="--cline-hub-daemon";function qN($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function MN(){try{let $=AN(M2(),"logs","hub-daemon.log");return BN(KN($),{recursive:!0}),{fd:HN($,"a"),logPath:$}}catch{return}}function zK(){return LK()==="production"?n0():y0()}function E2($){return UN($).compatible}function _K($,Q,Z){if(!Q||Q.url!==Z)return $;return{...$,authToken:$.authToken??Q.authToken,pid:$.pid??Q.pid}}async function N2($,Q){try{return await l1($,{authToken:Q})}catch{return}}async function EN($,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await N2($))?.url)return!0;await new Promise((W)=>setTimeout(W,LN))}return!1}async function AZ($,Q){if(await R5($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await EN($.url,TN);return await S0(Q).catch(()=>{return}),Z}async function D5($,Q){if(E2($))return!0;return AZ($,Q)}async function OK($){if(LK()!=="production")return;let Q=y0();if(Q.discoveryPath===$.discoveryPath)return;let Z=await F0(Q.discoveryPath);if(Z?.url)await AZ(Z,Q.discoveryPath);else await S0(Q.discoveryPath).catch(()=>{return})}function NN(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return FN(new URL(`./entry.${$}`,import.meta.url))}function PN($,Q){let Z=NN(),J=process.execPath?.trim();if(!J)throw Error("unable to resolve runtime executable for hub daemon");let W=GN(J).toLowerCase().includes("bun"),Y=Z.startsWith("/$bunfs/"),X=W&&Z.toLowerCase().endsWith(".ts"),j=Y?[ON]:[...X?["--conditions=development"]:[],Z];return{launcher:J,args:[...j,"--cwd",$,...qN(Q)],cwd:$,env:{...DN(process.env),CLINE_NO_INTERACTIVE:"1",[fN]:"1"}}}function CN($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function Q3($,Q={}){if(TK())return;let Z=PN($,Q),J=MN();try{jN(Z.launcher,Z.args,{detached:!0,stdio:J?["ignore",J.fd,J.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(J)VN(J.fd)}}async function r8($,Q={}){for(let Z=0;;Z++)try{Q3($,Q);return}catch(J){let W=zN[Z];if(!CN(J)||W===void 0)throw J;await new Promise((Y)=>setTimeout(Y,W))}}function FZ($,Q={}){if(TK())return;let Z=zK(),J=i0(Q),W=Y1(J.host,J.port,J.pathname),Y=Q.allowPortFallback===!0&&J.port!==0;OK(Z).catch(()=>{return}).then(()=>F0(Z.discoveryPath)).then(async(X)=>{let j=!1;if(X?.url)if(!X.authToken){if(j=!0,!await AZ(X,Z.discoveryPath)&&!Y)return}else{let H=await N2(X.url,X.authToken);if(H?.url&&E2(H)&&await K1(H.url,{authToken:X.authToken}))return;if(H?.url)await D5({...H,authToken:X.authToken},Z.discoveryPath);else await S0(Z.discoveryPath).catch(()=>{return})}let V=await N2(W);if(V?.url){if(E2(V)){if(!Y||!j)return}else if(!await D5({...V,authToken:void 0},Z.discoveryPath)&&!Y)return}let B=Y?{...J,port:0}:J;await r8($,B)}).catch(()=>{})}async function qK($,Q={}){let Z=zK(),J=Q.host!==void 0||Q.port!==void 0||Q.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=i0(Q),Y=Y1(W.host,W.port,W.pathname),X=(A)=>{if(!J)C$(A.url,A.authToken);return A};await OK(Z).catch(()=>{return});let j=await F0(Z.discoveryPath),V=!1;if(j?.url){let A=j.authToken;if(!A)V=!0,await AZ(j,Z.discoveryPath);else{let F=await N2(j.url,A);if(F?.url&&E2(F)&&await K1(F.url,{authToken:A}))return X({url:F.url,authToken:A});if(F?.url)await D5({...F,authToken:A},Z.discoveryPath);else await S0(Z.discoveryPath).catch(()=>{return})}}let B=await N2(Y);if(B?.url){let A=_K(B,j,Y);if(E2(B))throw Error(`A compatible Cline Hub is already running at ${Y}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${V?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await D5(A,Z.discoveryPath)&&Q.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${Y} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=Q.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await r8($,G);let K=Date.now()+RN;while(Date.now()<K){let A=await F0(Z.discoveryPath);if(A?.url&&A.authToken){let R=await N2(A.url,A.authToken);if(R?.url&&E2(R)&&await K1(R.url,{authToken:A.authToken}))return X({url:R.url,authToken:A.authToken})}let F=await N2(Y);if(F?.url&&!E2(F)){let R=_K(F,A,Y);if(!await D5(R,Z.discoveryPath)&&Q.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${Y} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,_N))}throw Error("Timed out waiting for detached hub startup.")}function fZ(){return yN()==="production"?n0():y0()}function hN(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function CK($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((Q)=>Buffer.from(Q))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return CK($.data);return String($)}function kN($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function MK($){let Q=$,Z=kN(Q.reason);return new M0("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:Z3,{closeCode:Q.code,closeReason:Z||void 0})}function IN($,Q){if($ instanceof M0)return $;if($ instanceof Error)return new M0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new M0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new M0("hub_connect_failed",Z);let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new M0("hub_connect_failed",J?`Failed to connect to hub at ${Q.toString()} (${J} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var xN=8000,gN=200,EK="*",NK=8000,mN="cline-hub-auth.",wK=new Map,SK=new Set,vN=3000,cN=3000,uN=100,Z3="Hub connection closed",dN=250,lN=5000,PK=0.5;class M0 extends Error{code;details;constructor($,Q,Z){super(Q);this.code=$;this.details=Z;this.name="HubTransportError"}}function Y3($){return $ instanceof M0}class i8 extends Error{command;code;constructor($,Q,Z){super(Z);this.command=$;this.code=Q;this.name="HubCommandError"}}function UZ($,Q){return $ instanceof i8&&$.code==="hub_command_timeout"&&(Q===void 0||$.command===Q)}function yK($){let Q=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Q)return Q;let Z=X3($.toString());return Z?wK.get(Z):void 0}function pN($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function X3($){if(!pN($))return;let Q=new URL(w$($));return Q.search="",Q.hash="",Q.toString()}function J3($){let Q=X3($);return!!Q&&SK.has(Q)}function C$($,Q){let Z=X3($);if(Z){if(SK.add(Z),Q?.trim())wK.set(Z,Q)}return $}class X1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new M0("hub_connection_closed",Z3);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.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 $=new URL(this.currentUrl),Q=this.options.authToken?.trim()||yK($);$.hash="";let J=new(hN())($.toString(),Q?[`${mN}${Q}`]:void 0);this.socket=J;let W=!1;this.connectPromise=new Promise((Y,X)=>{let j=!1,V=setTimeout(()=>{if(j)return;j=!0,W=!0,this.lastCloseError=new M0("hub_connect_timeout",`Timed out connecting to hub after ${NK}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{J.close()}catch{}X(this.lastCloseError)},NK);J.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(V),Y()}),J.addEventListener("error",(B)=>{if(j)return;j=!0,clearTimeout(V),this.lastCloseError=IN(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),J.addEventListener("close",(B)=>{if(j)return;if(j=!0,clearTimeout(V),!W)this.lastCloseError=MK(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),J.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(CK(Y)))}),J.addEventListener("close",(Y)=>{if(this.socket!==J)return;if(!W)this.lastCloseError=MK(Y),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.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 Y of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Y));this.reconnectAttempt=0}subscribe($,Q){let Z=Q?.sessionId?.trim()||void 0,J={listener:$,sessionId:Z};return this.listeners.add(J),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(J))return;this.adjustSubscriptionCount(Z,-1)}}async command($,Q,Z,J){let W=0,Y=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,Q,Z,J)}catch(X){if(!Y||W>=1||!await this.recoverLocalHubTransport(X))throw X;W+=1}}async commandOnce($,Q,Z,J){await this.connect();let W=wN("hubreq_"),Y=bN($,J?.timeoutMs),X=new Promise((V,B)=>{let H=Y===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;B(new i8($,"hub_command_timeout",`Hub command ${$} timed out after ${Y}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.`))},Y);this.pendingReplies.set(W,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Z,timeoutMs:Y,payload:Q}})}catch(V){throw this.pendingReplies.delete(W),V}let j=await X;if(!j.ok){if(j.error?.code===L2){let V=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new c1(V,j.error.message)}throw new i8($,j.error?.code,j.error?.message??`Hub command ${$} failed`)}return j}async recoverLocalHubTransport($){if(!J3(this.currentUrl)||!Y3($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await P2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,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 $=Math.min(dN*2**this.reconnectAttempt,lN),Q=Math.round($*(1-PK)+Math.random()*$*PK);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!J3(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await P2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new M0("hub_connection_closed",Z3),this.sawSocketClose=!1;for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.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($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new M0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,Q){this.sendFrame({kind:$,clientId:this.clientId,...Q?{sessionId:Q}:{}})}adjustSubscriptionCount($,Q){let Z=this.subscriptionKeyForSessionId($),J=(this.subscriptionCounts.get(Z)??0)+Q;if(J<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,J),Q>0&&J===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??EK}subscriptionSessionIdFromKey($){return $===EK?void 0:$}handleFrame($){switch($.kind){case"reply":{let Q=$.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve($.envelope);return}case"event":for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==$.envelope.sessionId?.trim())continue;Q.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function w$($){let Q=new URL($);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function K1($,Q){let Z=new X1({url:$,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function W3($,Q){let Z=w$($),J=await l1(Z,{authToken:Q?.authToken});if(!J)return{status:"unreachable",url:Z};if(!SN(J).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await K1(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function rN($){let Q=Date.now()+xN;while(Date.now()<Q){let Z=await F0($.discoveryPath);if(Z?.url){let J=await W3(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(J.status==="compatible")return C$(J.url,Z.authToken)}await new Promise((J)=>setTimeout(J,gN))}return}async function iN($){let Q=Date.now()+cN;while(Date.now()<Q){if(!(await l1($).catch(()=>{return}))?.url)return!0;await new Promise((J)=>setTimeout(J,uN))}return!1}function nN($,Q){try{return w$($)===w$(Q)}catch{return!1}}function aN($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let J=Z;if(J.status==="running"||J.status==="idle"||J.status==="pending")return!0;return Array.isArray(J.participants)&&J.participants.length>0})}async function sN($,Q,Z){let J=new X1({url:$,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let W=await J.command("session.list",{limit:500},void 0,{timeoutMs:vN});return!aN(W.payload)}catch{return!1}finally{await J.dispose().catch(()=>{return})}}async function _5($={}){if($.endpoint?.trim()){let W=await W3($.endpoint);return W.status==="compatible"?W.url:void 0}let Q=fZ(),Z=await F0(Q.discoveryPath);if(!Z?.url)return;let J=await W3(Z.url,{authToken:Z.authToken});if(J.status==="compatible")return C$(J.url,Z.authToken);if(J.status==="protocol_mismatch")await S0(Q.discoveryPath).catch(()=>{return});return}async function P2($={}){let Q=await _5($);if(Q&&await K1(Q,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return Q;if($.endpoint?.trim())return;let Z=fZ();return await r8($.workspaceRoot??process.cwd()),await rN(Z)}async function R5($,Q){let Z=new URL($),J=Q?.trim()||yK(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:J?{authorization:`Bearer ${J}`}:void 0})).ok}async function j3($=fZ()){let Q=await F0($.discoveryPath);if(!Q?.url)return!1;try{if(await R5(Q.url,Q.authToken))return!0}catch{}return!1}async function DZ($){if(!J3($.url))return;let Q=fZ(),Z=await F0(Q.discoveryPath);if(!Z?.url||!nN(Z.url,$.url))return;if(!await sN(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await j3())return;if(!await iN(Z.url))return;return await S0(Q.discoveryPath).catch(()=>{return}),await P2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var pK={};P(pK,{HubRuntimeHost:()=>p1});import{captureSdkError as hK,createSessionId as kK,HUB_CHECKPOINT_CAPABILITY as $P,HUB_COMPACTION_CAPABILITY as QP,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ZP,HUB_HOOK_CAPABILITY_PREFIX as JP,HUB_MISTAKE_LIMIT_CAPABILITY as WP,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as YP,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as XP,isHubToolExecutorName as jP}from"@cline/shared";var bK={};P(bK,{createCoreSessionSnapshot:()=>A1,coreSessionSnapshotToRecord:()=>RZ});function oN($){return $?JSON.parse(JSON.stringify($)):void 0}function tN($){return $?JSON.parse(JSON.stringify($)):void 0}function eN($){let Q=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,J=(Array.isArray(Q?.history)?Q.history:[]).filter((X)=>!!X&&typeof X==="object"&&!Array.isArray(X)).flatMap((X)=>{let j=typeof X.ref==="string"?X.ref.trim():"",V=Number(X.createdAt),B=Number(X.runCount);if(!j||!Number.isFinite(V)||!Number.isInteger(B))return[];return[{ref:j,createdAt:V,runCount:B,...X.kind==="stash"||X.kind==="commit"?{kind:X.kind}:{}}]}),W=J.at(-1),Y=$?.checkpointEnabled===!0?!0:void 0;if(!Y&&J.length===0)return;return{...Y?{enabled:Y}:{},...W?{latest:W}:{},history:J}}function A1($){let{session:Q}=$,Z=oN(Q.metadata);return{version:1,sessionId:Q.sessionId,source:Q.source,status:Q.status,createdAt:Q.startedAt,updatedAt:Q.updatedAt,endedAt:Q.endedAt??null,exitCode:Q.exitCode??null,interactive:Q.interactive,workspace:{cwd:Q.cwd,root:Q.workspaceRoot},model:{providerId:Q.provider,modelId:Q.model},capabilities:{enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams},lineage:{...Q.parentSessionId?{parentSessionId:Q.parentSessionId}:{},...Q.parentAgentId?{parentAgentId:Q.parentAgentId}:{},...Q.agentId?{agentId:Q.agentId}:{},...Q.conversationId?{conversationId:Q.conversationId}:{},isSubagent:Q.isSubagent},...Q.teamName?{team:{name:Q.teamName}}:{},...Q.prompt?{prompt:Q.prompt}:{},...Z?{metadata:Z}:{},...Q.messagesPath?{artifacts:{messagesPath:Q.messagesPath}}:{},...$.messages?{messages:tN($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let J=eN(Z);return J?{checkpoint:J}:{}})()}}function RZ($){return{sessionId:$.sessionId,parentSessionId:$.lineage.parentSessionId,agentId:$.lineage.agentId,parentAgentId:$.lineage.parentAgentId,conversationId:$.lineage.conversationId,isSubagent:$.lineage.isSubagent,source:$.source,startedAt:$.createdAt,endedAt:$.endedAt??void 0,exitCode:$.exitCode??void 0,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspaceRoot:$.workspace.root,teamName:$.team?.name,enableTools:$.capabilities.enableTools,enableSpawn:$.capabilities.enableSpawn,enableTeams:$.capabilities.enableTeams,prompt:$.prompt,metadata:$.metadata,updatedAt:$.updatedAt,messagesPath:$.artifacts?.messagesPath}}function n8($){if(!$)return;return JSON.parse(JSON.stringify($))}var VP=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function IK($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function xK($){if(!$)return;let{userInstructionService:Q,...Z}=$;return JSON.parse(JSON.stringify(Z))}function gK($){let Q=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof Q.agentId==="string"?Q.agentId:"",conversationId:typeof Q.conversationId==="string"?Q.conversationId:"",iteration:typeof Q.iteration==="number"?Q.iteration:0,metadata:Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0}}function C2($,Q,Z){$.manifest.push(Q),$.handlers.set(Q.capabilityName,Z)}function mK($,Q){let Z={manifest:[],handlers:new Map};for(let W of Object.keys(Q.toolExecutors??{}).filter(jP)){let Y=Q.toolExecutors?.[W];if(typeof Y!=="function")continue;C2(Z,{kind:"toolExecutor",executor:W,capabilityName:`${YP}${W}`},async({payload:X,abortSignal:j})=>{let V=Array.isArray(X.args)?[...X.args]:[],B={...gK(X.context),signal:j};return{result:await Y(...V,B)}})}for(let W of $?.extraTools??[])C2(Z,{kind:"tool",name:W.name,description:W.description,inputSchema:n8(W.inputSchema)??{},...W.lifecycle?{lifecycle:n8(W.lifecycle)}:{},capabilityName:`${ZP}${W.name}`},async({payload:Y,abortSignal:X,progress:j})=>{let V={...gK(Y.context),signal:X};return{result:await W.execute(Y.input,{...V,emitUpdate:(H)=>{j({update:H})}})}});let J=$?.hooks;if(J)for(let W of VP){let Y=J[W];if(typeof Y!=="function")continue;C2(Z,{kind:"hook",name:W,capabilityName:`${JP}${W}`},async({payload:X})=>({control:await Y(X.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;C2(Z,{kind:"compaction",capabilityName:QP,config:IK($.compaction)},async({payload:Y})=>({result:await W(Y.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;C2(Z,{kind:"checkpoint",capabilityName:$P,config:IK($.checkpoint)},async({payload:Y})=>({result:await W(Y.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;C2(Z,{kind:"mistakeLimit",capabilityName:WP},async({payload:Y})=>({result:await W(Y.context)}))}if($?.userInstructionService){let W=$.userInstructionService;C2(Z,{kind:"userInstructionService",capabilityName:XP},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Z}function dK($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let Q=$.message;if(typeof Q==="string"&&Q.trim())return Q.trim()}return}function BP($){return dK($)??"Capability request was cancelled."}function HP($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function GP($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function KP($){if(!$||typeof $!=="object"||Array.isArray($))return;let Q=$,Z=typeof Q.inputTokens==="number"?Q.inputTokens:void 0,J=typeof Q.outputTokens==="number"?Q.outputTokens:void 0;if(Z===void 0||J===void 0)return;return{inputTokens:Z,outputTokens:J,cacheReadTokens:typeof Q.cacheReadTokens==="number"?Q.cacheReadTokens:0,cacheWriteTokens:typeof Q.cacheWriteTokens==="number"?Q.cacheWriteTokens:0,totalCost:typeof Q.totalCost==="number"?Q.totalCost:0}}function vK($){if(!$)return;return{inputTokens:typeof $.inputTokens==="number"?$.inputTokens:0,outputTokens:typeof $.outputTokens==="number"?$.outputTokens:0,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function V3($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function S$($,Q){return V3($?.[Q])??0}function AP($){let Q=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Z=$?.totals&&typeof $.totals==="object"?$.totals:void 0,J=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=J?.teamRole==="teammate"||J?.teamRole==="lead"?J.teamRole:void 0;return{event:{type:"usage",agentId:typeof J?.agentId==="string"?J.agentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,inputTokens:S$(Q,"inputTokens"),outputTokens:S$(Q,"outputTokens"),cacheReadTokens:S$(Q,"cacheReadTokens"),cacheWriteTokens:S$(Q,"cacheWriteTokens"),cost:V3(Q?.totalCost),totalInputTokens:S$(Z,"inputTokens"),totalOutputTokens:S$(Z,"outputTokens"),totalCacheReadTokens:S$(Z,"cacheReadTokens"),totalCacheWriteTokens:S$(Z,"cacheWriteTokens"),totalCost:V3(Z?.totalCost)},teamAgentId:typeof J?.teamAgentId==="string"?J.teamAgentId:void 0,teamRole:W}}function FP($){let Q=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Z=$?.reason??Q?.finishReason,J=GP(Z)?Z:Z==="failed"?"error":"completed",W=KP($?.usage??Q?.usage);return{type:"done",reason:J,text:typeof $?.text==="string"?$.text:typeof Q?.text==="string"?Q.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof Q?.iterations==="number"?Q.iterations:0,usage:W}}function _Z($,Q){return $.error?.message??`hub command failed: ${Q}`}function T5($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function lK($){let Q=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof Q?.agentId==="string"?Q.agentId:void 0),parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,isSubagent:typeof Q?.isSubagent==="boolean"?Q.isSubagent:!1,source:typeof Q?.source==="string"?Q.source:R0.CORE,pid:typeof Q?.pid==="number"?Q.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:T5($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:T5($.status)==="completed"?0:T5($.status)==="failed"?1:void 0,status:T5($.status),interactive:Q?.interactive===!0,provider:typeof Q?.provider==="string"?Q.provider:"hub",model:typeof Q?.model==="string"?Q.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof Q?.teamName==="string"?Q.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??Q?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??Q?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??Q?.enableTeams===!0,prompt:typeof Q?.prompt==="string"?Q.prompt:void 0,metadata:Q,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,hookPath:typeof Q?.hookPath==="string"?Q.hookPath:void 0}}function y$($){if(!$||typeof $!=="object"||Array.isArray($))return;let Q=$;return Q.version===1&&typeof Q.sessionId==="string"?JSON.parse(JSON.stringify(Q)):void 0}function fP($){let Q=y$($?.snapshot);if(Q)return RZ(Q);let Z=$?.session;return Z?lK(Z):void 0}function cK($,Q,Z){let J=Z?.workspaceRoot?.trim()||Q.config.workspaceRoot||Q.config.cwd;return C0.parse({version:1,session_id:$,source:Q.source??R0.CORE,pid:process.pid,started_at:new Date(Z?.createdAt??Date.now()).toISOString(),status:T5(Z?.status),interactive:Q.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Z?.cwd?.trim()||Q.config.cwd,workspace_root:J,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,metadata:Q.sessionMetadata&&Object.keys(Q.sessionMetadata).length>0?Q.sessionMetadata:void 0})}function uK($,Q){return C0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??Q.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class p1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new F5;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,Q){this.clientContext=Q,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd},this.defaultCapabilities=L0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Z)=>this.requestPendingPromptsList(Z),update:(Z)=>this.requestPendingPromptUpdate(Z),delete:(Z)=>this.requestPendingPromptDelete(Z)},this.client=this.createClient($.url)}createClient($){return new X1({...this.clientOptions,url:$})}async replaceClient($){let Q=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(Q.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!UZ($,"session.create"))return!1;let Q=await DZ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!Q)return!1;return await this.replaceClient(Q),!0}registerPlannedSession($,Q,Z){if(this.sessionCapabilities.set($,Q),Z.size>0)this.sessionClientContributionHandlers.set($,Z);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let Q=this.resolveCapabilities($),Z=mK($.localRuntime,Q),J=$.config.sessionId?.trim()||kK(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:n8({...$.config,sessionId:J}),metadata:{...$.sessionMetadata??{},source:$.source??R0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Z.manifest.length>0?{clientContributions:Z.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:n8($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(J,Q,Z.handlers);let Y;try{Y=await W()}catch(B){if(this.cleanupPlannedSession(J),await this.recoverLocalHubStartupDeadlock(B)){this.registerPlannedSession(J,Q,Z.handlers);try{Y=await W()}catch(H){throw this.cleanupPlannedSession(J),H}}else throw B}let X=y$(Y.payload?.snapshot),j=Y.payload?.session,V=(X?.sessionId??j?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(J),Error("Hub runtime did not return a session id.");if(V!==J)this.cleanupPlannedSession(J),this.registerPlannedSession(V,Q,Z.handlers);return{sessionId:V,manifest:X?uK(X,$):cK(V,$,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let Q=$.sessionId.trim();if(!Q)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.start)throw Error("start is required when restore.messages is true");let J=$.start,W=J?this.resolveCapabilities(J):void 0,Y=J?mK(J.localRuntime,W??{}):{manifest:[],handlers:new Map},X=J?J.config.sessionId?.trim()||kK():void 0;if(X&&W)this.sessionCapabilities.set(X,W);if(X&&Y.handlers.size>0)this.sessionClientContributionHandlers.set(X,Y.handlers),this.ensureSessionSubscription(X);let j;try{j=await this.client.command("session.restore",{sessionId:Q,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...J?{workspaceRoot:J.config.workspaceRoot?.trim()||J.config.cwd,cwd:J.config.cwd??$.cwd,sessionConfig:n8({...J.config,sessionId:X}),metadata:{...J.sessionMetadata??{},source:J.source??R0.CORE,provider:J.config.providerId,model:J.config.modelId,enableTools:J.config.enableTools,enableSpawn:J.config.enableSpawnAgent,enableTeams:J.config.enableAgentTeams,teamName:J.config.teamName,prompt:J.prompt,interactive:J.interactive===!0},runtimeOptions:{...Y.manifest.length>0?{clientContributions:Y.manifest}:{},...J.localRuntime?.configExtensions?{configExtensions:J.localRuntime.configExtensions}:{}},toolPolicies:n8(J.toolPolicies)}:{}},Q)}catch(A){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw A}if(!j.ok){let A=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error(A)}let V=y$(j.payload?.snapshot),B=j.payload?.session,H=(V?.sessionId??B?.sessionId)?.trim();if(Z&&!H){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error("Hub checkpoint restore returned no session id")}if(H&&X&&H!==X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&Y.handlers.size>0)this.sessionClientContributionHandlers.set(H,Y.handlers);if(H)this.ensureSessionSubscription(H);let G=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,K=j.payload?.checkpoint;if(!K)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:V?uK(V,J??{}):cK(H,J??{},B),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:G,checkpoint:K}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let Q=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(Q.payload?.prompts)?Q.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let Q=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(Q.payload?.prompts)?Q.payload.prompts:[],prompt:Q.payload?.prompt,updated:Q.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let Q=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(Q.payload?.prompts)?Q.payload.prompts:[],prompt:Q.payload?.prompt,removed:Q.payload?.removed===!0}}async getAccumulatedUsage($){let Q=await this.client.command("session.get",{includeSnapshot:!0},$),Z=y$(Q.payload?.snapshot);if(Z){let X=Z.usage?{...Z.usage}:void 0,j=Z.aggregateUsage?{...Z.aggregateUsage}:void 0;return X||j?{usage:X,aggregateUsage:j}:void 0}let J=Q.payload?.session,W=vK(J?.usage),Y=vK(J?.aggregateUsage);return W||Y?{usage:W,aggregateUsage:Y}:void 0}async abort($,Q){await this.client.command("run.abort",{sessionId:$,reason:dK(Q)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,Q]of this.sessionSubscriptions){Q();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let Q;try{Q=await this.client.command("session.get",void 0,$)}catch(Z){if(u1(Z))return;throw Z}return fP(Q.payload)}async listSessions($=100){let Q=await this.client.command("session.list",{limit:$}),Z=Array.isArray(Q.payload?.snapshots)?Q.payload.snapshots.flatMap((W)=>{let Y=y$(W);return Y?[RZ(Y)]:[]}):[];if(Z.length>0)return Z;return(Q.payload?.sessions??[]).map(lK)}async listSettings($){let Q=await this.client.command("settings.list",xK($));if(!Q.ok)throw Error(_Z(Q,"settings.list"));return Q.payload?.snapshot}async toggleSetting($){let Q=await this.client.command("settings.toggle",xK($));if(!Q.ok)throw Error(_Z(Q,"settings.toggle"));return{snapshot:Q.payload?.snapshot,changedTypes:Array.isArray(Q.payload?.changedTypes)?Q.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,Q){let Z={...Q.metadata??{}};if(typeof Q.prompt==="string")Z.prompt=Q.prompt;if(typeof Q.title==="string")Z.title=Q.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Z})).ok}}async readSessionMessages($){let Q=$.trim();if(!Q)return[];let Z=await this.client.command("session.messages",{sessionId:Q},Q);if(!Z.ok)throw hK(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(_Z(Z,"session.messages")),severity:Z.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:Q,errorCode:Z.error?.code,runtimeAddress:this.runtimeAddress}}),Error(_Z(Z,"session.messages"));let J=Z.payload?.messages;return Array.isArray(J)?J:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,Q){return this.events.subscribe($,Q)}ensureSessionSubscription($){let Q=$.trim();if(!Q||this.sessionSubscriptions.has(Q))return;let Z=this.client.subscribe((J)=>{this.handleHubEvent(J)},{sessionId:Q});this.sessionSubscriptions.set(Q,typeof Z==="function"?Z:()=>{})}disposeSessionSubscription($){let Q=$.trim();if(!Q)return;this.sessionSubscriptions.get(Q)?.(),this.sessionSubscriptions.delete(Q),this.agentDoneEmittedForCurrentRunBySession.delete(Q)}resolveCapabilities($){return L0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:FP($.payload)}})}handleHubEvent($){let Q=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Z,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Z,$)});return}if(!Q)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(Q);let Z=y$($.payload?.snapshot),J=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:Q,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:Q,status:J?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"";if(!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_start",contentType:"text",text:Z}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"",J=$.payload?.redacted===!0;if(!Z&&!J)return;this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_start",contentType:"reasoning",reasoning:Z,redacted:J}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:Q,payload:$.payload});return}case"usage.updated":{let Z=AP($.payload);this.events.emit({type:"agent_event",payload:{sessionId:Q,event:Z.event,teamAgentId:Z.teamAgentId,teamRole:Z.teamRole}});return}case"tool.started":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z&&this.pendingApprovalToolCallIds.delete(Z))return;this.emitToolCallContentStart({sessionId:Q,toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z)this.pendingApprovalToolCallIds.delete(Z);this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_end",contentType:"tool",toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Z=y$($.payload?.snapshot),J=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:Q,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:Q,status:J?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:Q,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Z=$.payload?.prompt;if(!Z)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:Q,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Z=y$($.payload?.snapshot),J=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:Q,payload:{...$.payload,reason:J}}),Z?.interactive===!0&&j0(Z.status))return;this.events.emit({type:"ended",payload:{sessionId:Q,reason:J,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,Q,Z){try{hK(this.telemetry,{component:"core",operation:$,error:Q,severity:"warn",handled:!0,context:{event:Z.event,sessionId:Z.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let Q=$.sessionId?.trim();if(!Q)return;let Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Z&&Z!==this.client.getClientId())return;let J=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!J)return;let Y=this.sessionClientContributionHandlers.get(Q)?.get(W);if(!Y){await this.client.command("capability.respond",{requestId:J,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${Q}.`},Q).catch(()=>{});return}let X=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(J,j);let V=(B)=>{this.client.command("capability.progress",{requestId:J,payload:B},Q).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let B=await Y({payload:X,abortSignal:j.signal,progress:V});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:J,ok:!0,payload:B},Q)}catch(B){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:J,ok:!1,error:B instanceof Error?B.message:String(B)},Q)}finally{this.activeCapabilityAbortControllers.delete(J)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let Q=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!Q)return;let Z=this.activeCapabilityAbortControllers.get(Q);if(!Z)return;Z.abort(BP($.payload.error))}async handleApprovalRequested($){let Q=$.sessionId?.trim();if(!Q)return;let Z=this.sessionCapabilities.get(Q)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Z)return;let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",Y=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!J||!W||!Y)return;let X=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},j=HP($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:Q,toolCallId:W,toolName:Y,toolInput:j});let V=await Promise.resolve(Z({sessionId:Q,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:Q,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:Y,input:j,policy:X})).catch((B)=>({approved:!1,reason:B instanceof Error?B.message:`Tool approval request failed: ${String(B)}`}));await this.client.command("approval.respond",{approvalId:J,approved:V.approved,reason:V.reason},Q).catch(()=>{})}}var rK={};P(rK,{RemoteRuntimeHost:()=>a8});class a8 extends p1{constructor($){super({url:w$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var iK={};P(iK,{SqliteSessionStore:()=>f1});import{existsSync as UP,mkdirSync as DP}from"node:fs";import{join as RP}from"node:path";import{asBool as L5,asOptionalString as F1,asString as r1,ensureSessionSchema as _P,loadSqliteDb as TP,nowIso as TZ,toBoolInt as z5}from"@cline/shared/db";import{resolveDbDataDir as LP}from"@cline/shared/storage";class f1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??LP()}init(){this.getRawDb()}ensureSessionsDir(){if(!UP(this.sessionsDirPath))DP(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return RP(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=TP(this.sessionDbPath());return _P($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,Q=[]){return this.getRawDb().prepare($).run(...Q)}queryOne($,Q=[]){return this.getRawDb().prepare($).get(...Q)??void 0}queryAll($,Q=[]){return this.getRawDb().prepare($).all(...Q)}create($){let Q=TZ();this.run(`INSERT OR REPLACE INTO sessions (
502
502
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
package/dist/hub/index.js CHANGED
@@ -273,7 +273,7 @@ ${JSON.stringify(J,null,2)}`}startClaimLeaseHeartbeat($){let Q=Math.max(1000,Mat
273
273
  error = ?,
274
274
  scheduled_for = COALESCE(?, scheduled_for),
275
275
  updated_at = ?
276
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,Q,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,Q){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(Q,D0(),$)}attachReportPathToRun($,Q){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(Q,D0(),$)}}function $9($){return $?new Date($).getTime():void 0}function pU($){let Q=$.metadata?{...$.metadata}:void 0;if(Q)delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions;return Q}function e5($){let Q=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof Q?.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:$9($.nextRunAt),lastRunAt:$9($.lastRunAt),createdBy:typeof Q?.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:Q?.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0,metadata:pU($)}}function rU($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function kJ($,Q){return{executionId:$.runId,scheduleId:Q,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:$9($.startedAt),endedAt:$9($.completedAt),status:rU($.status),errorMessage:$.error}}class a2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new C4({dbPath:$.dbPath}),this.materializer=new z4({store:this.store}),this.runner=new M4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,eventPublisher:$.eventPublisher,workspaceRoot:"",logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.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($){if(SJ($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return e5(this.store.createHubSchedule($))}getSchedule($){let Q=this.store.getHubSchedule($);return Q?e5(Q):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((Q)=>e5(Q))}updateSchedule($,Q){if(Q.cronPattern!==void 0)SJ(Q.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let J=Q.workspaceRoot!==void 0?Q.workspaceRoot.trim():Z.workspaceRoot;if((Q.enabled??Z.enabled)&&!J)throw Error("workspaceRoot is required for enabled schedules");let Y=this.store.updateHubSchedule($,{...Q,scheduleId:$});return Y?e5(Y):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let Q=this.store.enqueueHubScheduleRun($,"manual");if(!Q)return;await this.runner.tick();let Z=this.store.getRun(Q.runId)??Q;return kJ(Z,$)}triggerScheduleNowDetached($){let Q=this.store.enqueueHubScheduleRun($,"manual");if(!Q)return;return this.runner.tick().catch(()=>{return}),kJ(Q,$)}listScheduleExecutions($){let Q=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:Q?.specId,limit:$.limit};return this.store.listRuns(Z).map((W)=>{let Y=Q??this.store.getSpec(W.specId);if(!Y||Y.source!=="hub-schedule")return;return kJ(W,Y.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let Q=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(Q.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,J=0,W=0,Y;for(let X of Q){if(X.status==="success"||X.status==="completed")Z+=1;if(!Y&&X.status!=="success"&&X.status!=="completed")Y=X;if(X.startedAt&&X.endedAt)W+=X.endedAt-X.startedAt,J+=1}return{totalRuns:Q.length,successRate:Z/Q.length,avgDurationSeconds:J>0?W/J/1000:0,lastFailure:Y}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let Q=this.store.getSpec($.specId);if(!Q||Q.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:Q.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:Q.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+Q.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let Q={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(Q).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,J)=>String(Z.nextRunAt).localeCompare(String(J.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:J})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:J}))}}O9();import{createSessionId as kR,isHubProtocolCompatible as IR,resolveClineBuildEnv as xR,resolveHubCommandTimeoutMs as gR}from"@cline/shared";var Qj={};P(Qj,{splitCoreSessionConfig:()=>m4,isSessionNotFoundError:()=>b1,SessionNotFoundError:()=>y1,SESSION_NOT_FOUND_ERROR_CODE:()=>u$});var u$="session_not_found";class y1 extends Error{sessionId;code="session_not_found";constructor($,Q){super(Q??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function b1($){return $ instanceof y1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function m4($){let{hooks:Q,logger:Z,telemetry:J,extensionContext:W,extraTools:Y,extensions:X,onTeamEvent:j,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(Q)K.hooks=Q;if(Z)K.logger=Z;if(J)K.telemetry=J;if(W)K.extensionContext=W;if(Y)K.extraTools=Y;if(X)K.extensions=X;if(j)K.onTeamEvent=j;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let A=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...A?{localRuntime:A}:{}}}import{spawn as KR}from"node:child_process";import{closeSync as AR,mkdirSync as FR,openSync as fR}from"node:fs";import{basename as UR,dirname as DR,join as RR}from"node:path";import{fileURLToPath as _R}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as TR,isHubDaemonProcess as fj,isHubProtocolCompatible as LR,resolveClineBuildEnv as Uj,withResolvedClineBuildEnv as zR}from"@cline/shared";import{createHash as uD,randomBytes as dD}from"node:crypto";import{existsSync as lD}from"node:fs";import{chmod as pD,mkdir as vJ,readFile as Xj,rm as cJ,writeFile as jj}from"node:fs/promises";import{dirname as Vj,join as uJ}from"node:path";import{resolveClineDataDir as d$,resolveClineDir as Bj}from"@cline/shared/storage";var Jj="0.0.52-nightly.1782444026";var v4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Jj,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var rD="CLINE_HUB_DISCOVERY_PATH",iD="CLINE_HUB_BUILD_ID",Wj=30000,nD=15000,aD=100;function sD($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function oD($){return uD("sha256").update($).digest("hex").slice(0,12)}function tD($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function q9(){return dD(32).toString("hex")}function eD($){return new Promise((Q)=>setTimeout(Q,$))}function $R($){return`${$}.lock`}async function QR($){try{let Q=JSON.parse(await Xj(uJ($,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function Yj($){await cJ($,{recursive:!0,force:!0}).catch(()=>{return})}function M9(){return process.env[iD]?.trim()||String(v4.version)}function h1($=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${oD($)}`,Z=process.env[rD]?.trim()||uJ(d$(),"locks","hub","owners",`${sD(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}function Hj($=`hub-${Date.now().toString(36)}`){return h1($)}async function G0($){try{let Q=JSON.parse(await Xj($,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function E9($,Q){await vJ(Vj($),{recursive:!0}),await cJ($,{force:!0}).catch(()=>{return}),await jj($,`${JSON.stringify(Q,null,2)}
276
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,Q,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,Q){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(Q,D0(),$)}attachReportPathToRun($,Q){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(Q,D0(),$)}}function $9($){return $?new Date($).getTime():void 0}function pU($){let Q=$.metadata?{...$.metadata}:void 0;if(Q)delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions;return Q}function e5($){let Q=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof Q?.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:$9($.nextRunAt),lastRunAt:$9($.lastRunAt),createdBy:typeof Q?.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:Q?.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0,metadata:pU($)}}function rU($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function kJ($,Q){return{executionId:$.runId,scheduleId:Q,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:$9($.startedAt),endedAt:$9($.completedAt),status:rU($.status),errorMessage:$.error}}class a2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new C4({dbPath:$.dbPath}),this.materializer=new z4({store:this.store}),this.runner=new M4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,eventPublisher:$.eventPublisher,workspaceRoot:"",logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.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($){if(SJ($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return e5(this.store.createHubSchedule($))}getSchedule($){let Q=this.store.getHubSchedule($);return Q?e5(Q):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((Q)=>e5(Q))}updateSchedule($,Q){if(Q.cronPattern!==void 0)SJ(Q.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let J=Q.workspaceRoot!==void 0?Q.workspaceRoot.trim():Z.workspaceRoot;if((Q.enabled??Z.enabled)&&!J)throw Error("workspaceRoot is required for enabled schedules");let Y=this.store.updateHubSchedule($,{...Q,scheduleId:$});return Y?e5(Y):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let Q=this.store.enqueueHubScheduleRun($,"manual");if(!Q)return;await this.runner.tick();let Z=this.store.getRun(Q.runId)??Q;return kJ(Z,$)}triggerScheduleNowDetached($){let Q=this.store.enqueueHubScheduleRun($,"manual");if(!Q)return;return this.runner.tick().catch(()=>{return}),kJ(Q,$)}listScheduleExecutions($){let Q=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:Q?.specId,limit:$.limit};return this.store.listRuns(Z).map((W)=>{let Y=Q??this.store.getSpec(W.specId);if(!Y||Y.source!=="hub-schedule")return;return kJ(W,Y.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let Q=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(Q.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,J=0,W=0,Y;for(let X of Q){if(X.status==="success"||X.status==="completed")Z+=1;if(!Y&&X.status!=="success"&&X.status!=="completed")Y=X;if(X.startedAt&&X.endedAt)W+=X.endedAt-X.startedAt,J+=1}return{totalRuns:Q.length,successRate:Z/Q.length,avgDurationSeconds:J>0?W/J/1000:0,lastFailure:Y}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let Q=this.store.getSpec($.specId);if(!Q||Q.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:Q.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:Q.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+Q.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let Q={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(Q).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,J)=>String(Z.nextRunAt).localeCompare(String(J.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:J})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:J}))}}O9();import{createSessionId as kR,isHubProtocolCompatible as IR,resolveClineBuildEnv as xR,resolveHubCommandTimeoutMs as gR}from"@cline/shared";var Qj={};P(Qj,{splitCoreSessionConfig:()=>m4,isSessionNotFoundError:()=>b1,SessionNotFoundError:()=>y1,SESSION_NOT_FOUND_ERROR_CODE:()=>u$});var u$="session_not_found";class y1 extends Error{sessionId;code="session_not_found";constructor($,Q){super(Q??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function b1($){return $ instanceof y1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function m4($){let{hooks:Q,logger:Z,telemetry:J,extensionContext:W,extraTools:Y,extensions:X,onTeamEvent:j,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(Q)K.hooks=Q;if(Z)K.logger=Z;if(J)K.telemetry=J;if(W)K.extensionContext=W;if(Y)K.extraTools=Y;if(X)K.extensions=X;if(j)K.onTeamEvent=j;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let A=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...A?{localRuntime:A}:{}}}import{spawn as KR}from"node:child_process";import{closeSync as AR,mkdirSync as FR,openSync as fR}from"node:fs";import{basename as UR,dirname as DR,join as RR}from"node:path";import{fileURLToPath as _R}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as TR,isHubDaemonProcess as fj,isHubProtocolCompatible as LR,resolveClineBuildEnv as Uj,withResolvedClineBuildEnv as zR}from"@cline/shared";import{createHash as uD,randomBytes as dD}from"node:crypto";import{existsSync as lD}from"node:fs";import{chmod as pD,mkdir as vJ,readFile as Xj,rm as cJ,writeFile as jj}from"node:fs/promises";import{dirname as Vj,join as uJ}from"node:path";import{resolveClineDataDir as d$,resolveClineDir as Bj}from"@cline/shared/storage";var Jj="0.0.52";var v4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:Jj,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var rD="CLINE_HUB_DISCOVERY_PATH",iD="CLINE_HUB_BUILD_ID",Wj=30000,nD=15000,aD=100;function sD($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function oD($){return uD("sha256").update($).digest("hex").slice(0,12)}function tD($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function q9(){return dD(32).toString("hex")}function eD($){return new Promise((Q)=>setTimeout(Q,$))}function $R($){return`${$}.lock`}async function QR($){try{let Q=JSON.parse(await Xj(uJ($,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function Yj($){await cJ($,{recursive:!0,force:!0}).catch(()=>{return})}function M9(){return process.env[iD]?.trim()||String(v4.version)}function h1($=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${oD($)}`,Z=process.env[rD]?.trim()||uJ(d$(),"locks","hub","owners",`${sD(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}function Hj($=`hub-${Date.now().toString(36)}`){return h1($)}async function G0($){try{let Q=JSON.parse(await Xj($,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function E9($,Q){await vJ(Vj($),{recursive:!0}),await cJ($,{force:!0}).catch(()=>{return}),await jj($,`${JSON.stringify(Q,null,2)}
277
277
  `,{encoding:"utf8",mode:384}),await pD($,384)}async function w0($){await cJ($,{force:!0}).catch(()=>{return})}async function N9($,Q){let Z=$R($);await vJ(Vj(Z),{recursive:!0});let J=Date.now()+nD;while(!0)try{await vJ(Z,{recursive:!1}),await jj(uJ(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
278
278
  `,"utf8");try{return await Q()}finally{await Yj(Z)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let X=await QR(Z),j=X?Date.now()-Date.parse(X.acquiredAt):Wj+1;if(!X||!tD(X.pid)||j>Wj){await Yj(Z);continue}if(Date.now()>=J)throw Error(`Timed out waiting for hub startup lock ${Z}`);await eD(aD)}}async function k1($,Q){try{let Z=await fetch(Q?.authToken?dJ($):P9($),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let J=await Z.json();if(typeof J.protocolVersion!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string")return;return{protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,host:J.host,port:J.port,url:J.url,hubId:typeof J.hubId==="string"?J.hubId:void 0,authToken:typeof J.authToken==="string"?J.authToken:void 0,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:typeof J.startedAt==="string"?J.startedAt:void 0,updatedAt:typeof J.updatedAt==="string"?J.updatedAt:void 0}}catch{return}}function e0($,Q,Z="/hub"){return new URL(`ws://${$}:${Q}${Z}`).toString()}function P9($){let Q=new URL($);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function dJ($){let Q=new URL(P9($));return Q.pathname="/status",Q.toString()}function Gj($){return lD($)}import{CLINE_HUB_DEV_PORT as ZR,CLINE_HUB_PORT as JR,resolveClineBuildEnv as WR}from"@cline/shared";var YR="CLINE_HUB_HOST",XR="CLINE_HUB_PORT",jR="CLINE_HUB_PATHNAME",lJ="127.0.0.1",pJ=JR,rJ="/hub";function Kj($){return WR($)==="development"?ZR:pJ}function iJ($={}){return($.env??process.env)[YR]?.trim()||lJ}function J8($={}){let Z=($.env??process.env)[XR]?.trim();if(!Z)return Kj($);let J=Number.parseInt(Z,10);if(!Number.isInteger(J)||J<1||J>65535)return Kj($);return J}function nJ($={}){return($.env??process.env)[jR]?.trim()||rJ}function V1($={},Q={}){return{host:$.host??iJ(Q),port:$.port??J8(Q),pathname:$.pathname??nJ(Q)}}import{join as VR}from"node:path";var BR="shared:cline",HR="CLINE_HUB_DISCOVERY_PATH",GR="hub-production";function Aj($){let Q=q1($.trim());return h1(`workspace:${Q||$.trim()}`)}function $1($=BR){return h1($)}function B1(){return{ownerId:GR,discoveryPath:process.env[HR]?.trim()||VR(d$(),"locks","hub","production.json")}}var OR=8000,qR=200,MR=3000,ER=100,NR=[100,250,500,1000,2000],PR="--cline-hub-daemon";function CR($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function wR(){try{let $=RR(d$(),"logs","hub-daemon.log");return FR(DR($),{recursive:!0}),{fd:fR($,"a"),logPath:$}}catch{return}}function Dj(){return Uj()==="production"?B1():$1()}function l$($){return LR($).compatible}function Fj($,Q,Z){if(!Q||Q.url!==Z)return $;return{...$,authToken:$.authToken??Q.authToken,pid:$.pid??Q.pid}}async function p$($,Q){try{return await k1($,{authToken:Q})}catch{return}}async function SR($,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await p$($))?.url)return!0;await new Promise((W)=>setTimeout(W,ER))}return!1}async function C9($,Q){if(await u4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await SR($.url,MR);return await w0(Q).catch(()=>{return}),Z}async function c4($,Q){if(l$($))return!0;return C9($,Q)}async function Rj($){if(Uj()!=="production")return;let Q=$1();if(Q.discoveryPath===$.discoveryPath)return;let Z=await G0(Q.discoveryPath);if(Z?.url)await C9(Z,Q.discoveryPath);else await w0(Q.discoveryPath).catch(()=>{return})}function yR(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return _R(new URL(`./entry.${$}`,import.meta.url))}function bR($,Q){let Z=yR(),J=process.execPath?.trim();if(!J)throw Error("unable to resolve runtime executable for hub daemon");let W=UR(J).toLowerCase().includes("bun"),Y=Z.startsWith("/$bunfs/"),X=W&&Z.toLowerCase().endsWith(".ts"),j=Y?[PR]:[...X?["--conditions=development"]:[],Z];return{launcher:J,args:[...j,"--cwd",$,...CR(Q)],cwd:$,env:{...zR(process.env),CLINE_NO_INTERACTIVE:"1",[TR]:"1"}}}function hR($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function aJ($,Q={}){if(fj())return;let Z=bR($,Q),J=wR();try{KR(Z.launcher,Z.args,{detached:!0,stdio:J?["ignore",J.fd,J.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(J)AR(J.fd)}}async function W8($,Q={}){for(let Z=0;;Z++)try{aJ($,Q);return}catch(J){let W=NR[Z];if(!hR(J)||W===void 0)throw J;await new Promise((Y)=>setTimeout(Y,W))}}function w9($,Q={}){if(fj())return;let Z=Dj(),J=V1(Q),W=e0(J.host,J.port,J.pathname),Y=Q.allowPortFallback===!0&&J.port!==0;Rj(Z).catch(()=>{return}).then(()=>G0(Z.discoveryPath)).then(async(X)=>{let j=!1;if(X?.url)if(!X.authToken){if(j=!0,!await C9(X,Z.discoveryPath)&&!Y)return}else{let H=await p$(X.url,X.authToken);if(H?.url&&l$(H)&&await H1(H.url,{authToken:X.authToken}))return;if(H?.url)await c4({...H,authToken:X.authToken},Z.discoveryPath);else await w0(Z.discoveryPath).catch(()=>{return})}let V=await p$(W);if(V?.url){if(l$(V)){if(!Y||!j)return}else if(!await c4({...V,authToken:void 0},Z.discoveryPath)&&!Y)return}let B=Y?{...J,port:0}:J;await W8($,B)}).catch(()=>{})}async function _j($,Q={}){let Z=Dj(),J=Q.host!==void 0||Q.port!==void 0||Q.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=V1(Q),Y=e0(W.host,W.port,W.pathname),X=(A)=>{if(!J)J$(A.url,A.authToken);return A};await Rj(Z).catch(()=>{return});let j=await G0(Z.discoveryPath),V=!1;if(j?.url){let A=j.authToken;if(!A)V=!0,await C9(j,Z.discoveryPath);else{let F=await p$(j.url,A);if(F?.url&&l$(F)&&await H1(F.url,{authToken:A}))return X({url:F.url,authToken:A});if(F?.url)await c4({...F,authToken:A},Z.discoveryPath);else await w0(Z.discoveryPath).catch(()=>{return})}}let B=await p$(Y);if(B?.url){let A=Fj(B,j,Y);if(l$(B))throw Error(`A compatible Cline Hub is already running at ${Y}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${V?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await c4(A,Z.discoveryPath)&&Q.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${Y} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=Q.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await W8($,G);let K=Date.now()+OR;while(Date.now()<K){let A=await G0(Z.discoveryPath);if(A?.url&&A.authToken){let R=await p$(A.url,A.authToken);if(R?.url&&l$(R)&&await H1(R.url,{authToken:A.authToken}))return X({url:R.url,authToken:A.authToken})}let F=await p$(Y);if(F?.url&&!l$(F)){let R=Fj(F,A,Y);if(!await c4(R,Z.discoveryPath)&&Q.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${Y} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,qR))}throw Error("Timed out waiting for detached hub startup.")}function S9(){return xR()==="production"?B1():$1()}function mR(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function qj($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((Q)=>Buffer.from(Q))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return qj($.data);return String($)}function vR($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function Tj($){let Q=$,Z=vR(Q.reason);return new q0("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:sJ,{closeCode:Q.code,closeReason:Z||void 0})}function cR($,Q){if($ instanceof q0)return $;if($ instanceof Error)return new q0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new q0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new q0("hub_connect_failed",Z);let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new q0("hub_connect_failed",J?`Failed to connect to hub at ${Q.toString()} (${J} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var uR=8000,dR=200,Lj="*",zj=8000,lR="cline-hub-auth.",Mj=new Map,Ej=new Set,pR=3000,rR=3000,iR=100,sJ="Hub connection closed",nR=250,aR=5000,Oj=0.5;class q0 extends Error{code;details;constructor($,Q,Z){super(Q);this.code=$;this.details=Z;this.name="HubTransportError"}}function eJ($){return $ instanceof q0}class Y8 extends Error{command;code;constructor($,Q,Z){super(Z);this.command=$;this.code=Q;this.name="HubCommandError"}}function y9($,Q){return $ instanceof Y8&&$.code==="hub_command_timeout"&&(Q===void 0||$.command===Q)}function Nj($){let Q=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Q)return Q;let Z=$W($.toString());return Z?Mj.get(Z):void 0}function sR($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function $W($){if(!sR($))return;let Q=new URL(W$($));return Q.search="",Q.hash="",Q.toString()}function oJ($){let Q=$W($);return!!Q&&Ej.has(Q)}function J$($,Q){let Z=$W($);if(Z){if(Ej.add(Z),Q?.trim())Mj.set(Z,Q)}return $}class Q1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new q0("hub_connection_closed",sJ);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.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 $=new URL(this.currentUrl),Q=this.options.authToken?.trim()||Nj($);$.hash="";let J=new(mR())($.toString(),Q?[`${lR}${Q}`]:void 0);this.socket=J;let W=!1;this.connectPromise=new Promise((Y,X)=>{let j=!1,V=setTimeout(()=>{if(j)return;j=!0,W=!0,this.lastCloseError=new q0("hub_connect_timeout",`Timed out connecting to hub after ${zj}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{J.close()}catch{}X(this.lastCloseError)},zj);J.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(V),Y()}),J.addEventListener("error",(B)=>{if(j)return;j=!0,clearTimeout(V),this.lastCloseError=cR(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),J.addEventListener("close",(B)=>{if(j)return;if(j=!0,clearTimeout(V),!W)this.lastCloseError=Tj(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),J.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(qj(Y)))}),J.addEventListener("close",(Y)=>{if(this.socket!==J)return;if(!W)this.lastCloseError=Tj(Y),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.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 Y of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Y));this.reconnectAttempt=0}subscribe($,Q){let Z=Q?.sessionId?.trim()||void 0,J={listener:$,sessionId:Z};return this.listeners.add(J),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(J))return;this.adjustSubscriptionCount(Z,-1)}}async command($,Q,Z,J){let W=0,Y=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,Q,Z,J)}catch(X){if(!Y||W>=1||!await this.recoverLocalHubTransport(X))throw X;W+=1}}async commandOnce($,Q,Z,J){await this.connect();let W=kR("hubreq_"),Y=gR($,J?.timeoutMs),X=new Promise((V,B)=>{let H=Y===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;B(new Y8($,"hub_command_timeout",`Hub command ${$} timed out after ${Y}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.`))},Y);this.pendingReplies.set(W,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Z,timeoutMs:Y,payload:Q}})}catch(V){throw this.pendingReplies.delete(W),V}let j=await X;if(!j.ok){if(j.error?.code===u$){let V=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new y1(V,j.error.message)}throw new Y8($,j.error?.code,j.error?.message??`Hub command ${$} failed`)}return j}async recoverLocalHubTransport($){if(!oJ(this.currentUrl)||!eJ($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await r$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,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 $=Math.min(nR*2**this.reconnectAttempt,aR),Q=Math.round($*(1-Oj)+Math.random()*$*Oj);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!oJ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await r$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new q0("hub_connection_closed",sJ),this.sawSocketClose=!1;for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.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($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,Q){this.sendFrame({kind:$,clientId:this.clientId,...Q?{sessionId:Q}:{}})}adjustSubscriptionCount($,Q){let Z=this.subscriptionKeyForSessionId($),J=(this.subscriptionCounts.get(Z)??0)+Q;if(J<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,J),Q>0&&J===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??Lj}subscriptionSessionIdFromKey($){return $===Lj?void 0:$}handleFrame($){switch($.kind){case"reply":{let Q=$.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve($.envelope);return}case"event":for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==$.envelope.sessionId?.trim())continue;Q.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function W$($){let Q=new URL($);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function H1($,Q){let Z=new Q1({url:$,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function tJ($,Q){let Z=W$($),J=await k1(Z,{authToken:Q?.authToken});if(!J)return{status:"unreachable",url:Z};if(!IR(J).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await H1(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function oR($){let Q=Date.now()+uR;while(Date.now()<Q){let Z=await G0($.discoveryPath);if(Z?.url){let J=await tJ(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(J.status==="compatible")return J$(J.url,Z.authToken)}await new Promise((J)=>setTimeout(J,dR))}return}async function tR($){let Q=Date.now()+rR;while(Date.now()<Q){if(!(await k1($).catch(()=>{return}))?.url)return!0;await new Promise((J)=>setTimeout(J,iR))}return!1}function eR($,Q){try{return W$($)===W$(Q)}catch{return!1}}function $_($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let J=Z;if(J.status==="running"||J.status==="idle"||J.status==="pending")return!0;return Array.isArray(J.participants)&&J.participants.length>0})}async function Q_($,Q,Z){let J=new Q1({url:$,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let W=await J.command("session.list",{limit:500},void 0,{timeoutMs:pR});return!$_(W.payload)}catch{return!1}finally{await J.dispose().catch(()=>{return})}}async function d4($={}){if($.endpoint?.trim()){let W=await tJ($.endpoint);return W.status==="compatible"?W.url:void 0}let Q=S9(),Z=await G0(Q.discoveryPath);if(!Z?.url)return;let J=await tJ(Z.url,{authToken:Z.authToken});if(J.status==="compatible")return J$(J.url,Z.authToken);if(J.status==="protocol_mismatch")await w0(Q.discoveryPath).catch(()=>{return});return}async function r$($={}){let Q=await d4($);if(Q&&await H1(Q,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return Q;if($.endpoint?.trim())return;let Z=S9();return await W8($.workspaceRoot??process.cwd()),await oR(Z)}async function u4($,Q){let Z=new URL($),J=Q?.trim()||Nj(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:J?{authorization:`Bearer ${J}`}:void 0})).ok}async function QW($=S9()){let Q=await G0($.discoveryPath);if(!Q?.url)return!1;try{if(await u4(Q.url,Q.authToken))return!0}catch{}return!1}async function b9($){if(!oJ($.url))return;let Q=S9(),Z=await G0(Q.discoveryPath);if(!Z?.url||!eR(Z.url,$.url))return;if(!await Q_(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await QW())return;if(!await tR(Z.url))return;return await w0(Q.discoveryPath).catch(()=>{return}),await r$({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as Z_}from"@cline/shared";function J_($,Q){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Z?`Failed to connect to hub at ${Q} (${Z} event before socket open).`:`Failed to connect to hub at ${Q}.`)}var W_="cline-hub-auth.";function Y_($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function X_($,Q){let Z=new URL($),J=new URL(Q);return Z.search="",Z.hash="",J.search="",J.hash="",Z.toString()===J.toString()}function Pj(){return Z_()==="production"?B1():$1()}async function j_($){let Q=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Q)return Q;let Z=Pj(),J=await G0(Z.discoveryPath);if(J?.url&&X_($.toString(),J.url))return J.authToken;return}async function ZW($={}){let Q=V1($);if(!Y_($)){let Z=Pj(),J=await G0(Z.discoveryPath);if(J?.url)return J.url}return e0(Q.host,Q.port,Q.pathname)}async function h9($){return await new Promise((Q,Z)=>{(async()=>{let J=new URL($),W=await j_(J);J.hash="";let Y=new WebSocket(J.toString(),W?[`${W_}${W}`]:void 0),X=new Map,j=0;Y.addEventListener("open",()=>{Q({send(V){let B=V.requestId??`hub-client-${++j}`;return new Promise((H,G)=>{X.set(B,{resolve:H,reject:G});let K={kind:"command",envelope:{...V,requestId:B}};Y.send(JSON.stringify(K))})},close(){Y.close()}})}),Y.addEventListener("message",(V)=>{let B=JSON.parse(String(V.data));if(B.kind==="reply"&&B.envelope.requestId){let H=X.get(B.envelope.requestId);if(H)X.delete(B.envelope.requestId),H.resolve(B.envelope)}}),Y.addEventListener("close",()=>{for(let V of X.values())V.reject(Error("Hub connection closed"));X.clear()}),Y.addEventListener("error",(V)=>{Z(J_(V,$))})})().catch(Z)})}async function Cj($){try{return(await h9($)).close(),!0}catch{return!1}}async function wj($,Q){let Z=await ZW($),J=await h9(Z);try{return await J.send({version:Q.version??"v1",clientId:Q.clientId??"hub-client",...Q})}finally{J.close()}}function JW($){return $?JSON.parse(JSON.stringify($)):{}}function k9($){let Q=$?.session&&typeof $.session==="object"?$.session:void 0;if(!Q)return;let Z=Q.metadata&&typeof Q.metadata==="object"?JW(Q.metadata):void 0;return{sessionId:typeof Q.sessionId==="string"?Q.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function Sj($,Q){return $.error?.message??`hub command failed: ${Q}`}function V_($){let Q=JW($);if(typeof Q.error==="string"&&Q.error.trim())return{...Q,error:Q.error.trim()};let Z=Q.result&&typeof Q.result==="object"?Q.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...Q,error:Z.text.trim()};let J=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof J?.message==="string"&&J.message.trim())return{...Q,error:J.message.trim()};return Q}function yj($){let Q=$?.sessionId;return typeof Q==="string"&&Q.trim()?Q.trim():void 0}function B_($){let Q=$?.checkpoint;if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error("hub checkpoint restore returned no checkpoint");let Z=Q;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function H_($){let Q=JW($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||yj(Q)||"",eventType:"schedule.execution.completed",payload:Q};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||yj(Q)||"",eventType:"schedule.execution.failed",payload:Q};let Z=$.sessionId?.trim();if(!Z)return;switch($.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:Q};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:Q};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:Q};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:Q};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:Q};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:Q};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:Q};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:Q};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:V_($.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:Q};default:return}}class WW{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new Q1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.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($){await this.ensureMetadataApplied();let Q=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Z=k9(Q.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession($,Q,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:Q.prompt,mode:Q.config.mode,attachments:Q.attachments,delivery:Q.delivery,timeoutSeconds:Q.config.timeoutSeconds},$,Z)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let Q;try{Q=await this.client.command("session.get",void 0,$)}catch(Z){if(b1(Z))return;throw Z}return k9(Q.payload)}async readMessages($){let Q=$.trim();if(!Q)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:Q},Q);if(!Z.ok)throw Error(Sj(Z,"session.messages"));let J=Z.payload?.messages;return Array.isArray(J)?J:[]}async restore($){let Q=$.sessionId.trim();if(!Q)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let J=$.config,W=await this.client.command("session.restore",{sessionId:Q,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...J?{workspaceRoot:J.workspaceRoot,cwd:J.cwd,sessionConfig:{providerId:J.provider,modelId:J.model,apiKey:J.apiKey,cwd:J.cwd??J.workspaceRoot,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:J.mode??"act",rules:J.rules,maxIterations:J.maxIterations,enableTools:J.enableTools,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},metadata:{source:J.source??"cli",provider:J.provider,model:J.model,enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams,prompt:void 0,interactive:J.interactive!==!1},runtimeOptions:{mode:J.mode,systemPrompt:J.systemPrompt,maxIterations:J.maxIterations,enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams,autoApproveTools:J.autoApproveTools,configExtensions:J.configExtensions},modelSelection:{provider:J.provider,model:J.model,apiKey:J.apiKey},toolPolicies:J.toolPolicies}:{}},Q);if(!W.ok)throw Error(Sj(W,"session.restore"));let Y=k9(W.payload);if(Z&&!Y?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,j=B_(W.payload);return{sessionId:Y?.sessionId,startResult:Y?.sessionId?{sessionId:Y.sessionId,manifestPath:"",messagesPath:Y.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:j}}async listSessions($){await this.ensureMetadataApplied();let Q=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(Q.payload?.sessions)?Q.payload?.sessions:[]).map((J)=>k9({session:J})).filter((J)=>Boolean(J?.sessionId))}async deleteSession($,Q=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:Q})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,Q){let Z=new Set(($.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),J=this.client.subscribe((W)=>{let Y=H_(W);if(!Y)return;if(Z.size>0&&!Z.has(Y.sessionId))return;Q.onEvent?.(Y)});return this.ensureMetadataApplied().catch((W)=>{Q.onError?.(W instanceof Error?W:Error(String(W)))}),J}streamTeamProgress($,Q){let Z=this.client.subscribe((J)=>{if(J.event!=="team.progress"||!J.payload)return;Q.onProjection?.(J.payload)});return this.ensureMetadataApplied().catch((J)=>{Q.onError?.(J instanceof Error?J:Error(String(J)))}),Z}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list");return Array.isArray(Q.payload?.schedules)?Q.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,Q){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...Q})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,Q){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:$,limit:Q});return Array.isArray(Z.payload?.executions)?Z.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(Q.payload?.upcoming)?Q.payload?.upcoming:[]}}class YW{client;constructor($){this.client=new Q1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.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($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let Q=await this.client.command("session.list",{limit:$});return Array.isArray(Q.payload?.sessions)?Q.payload.sessions:[]}subscribeUI($){return this.client.subscribe((Q)=>{switch(Q.event){case"ui.notify":$.onNotify?.(Q.payload);break;case"ui.show_window":$.onShowWindow?.(Q.payload);break;case"hub.client.registered":$.onClientRegistered?.(Q.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(Q.payload??{});break;case"session.created":$.onSessionCreated?.(Q.payload??{});break;case"session.updated":$.onSessionUpdated?.(Q.payload??{});break;case"session.detached":$.onSessionDetached?.(Q.payload??{});break}})}}import{normalizeProviderId as Lh}from"@cline/llms";var rF={};P(rF,{LocalRuntimeHost:()=>R1});import{readdirSync as Kh}from"node:fs";import{homedir as Ah}from"node:os";import{isAbsolute as Fh,join as nY,resolve as aY}from"node:path";import{captureSdkError as m2,createSessionId as fh,isLikelyAuthError as Uh,normalizeUserInput as Dh}from"@cline/shared";import{setHomeDirIfUnset as Rh}from"@cline/shared/storage";var jV={};P(jV,{saveProviderOAuthCredentials:()=>a$,resolveProviderApiKeyFromSettings:()=>DW,loginAndSaveProviderOAuthCredentials:()=>o4,isOAuthProvider:()=>n$,getProviderOAuthCredentialsFromSettings:()=>t4,getProviderAuthStorageId:()=>UW,getProviderAuthHandler:()=>Y0,getPersistedProviderApiKey:()=>G8,formatProviderOAuthApiKey:()=>RW});import{getClineEnvironmentConfig as YV}from"@cline/shared";R0();var uj={};P(uj,{startClineDeviceAuth:()=>GW,refreshClineToken:()=>m9,loginClineOAuth:()=>l4,getValidClineCredentials:()=>p4,completeClineDeviceAuth:()=>KW});import{getClineEnvironmentConfig as XW}from"@cline/shared";var bj={};P(bj,{startLocalOAuthServer:()=>Z1});function G_(){let $;return{promise:new Promise((Z)=>{$=Z}),resolve:$}}async function Z1($){let Q=await import("node:http"),Z=$.host??"127.0.0.1",J=$.timeoutMs??300000,W=$.successHtml??K_,Y=G_(),X=!1,j=null,V=null,B=null,H=(A)=>{if(X)return;X=!0,Y.resolve(A)},G=()=>{if(j)clearTimeout(j),j=null;let A=B;if(B=null,V)V.close(),V.closeAllConnections?.(),V=null;if(A!==null&&$.onClose)Promise.resolve($.onClose({host:Z,port:A})).catch(()=>{})},K=async()=>{return j=setTimeout(()=>{G(),H(null)},J),Y.promise};for(let A of $.ports){let F=Q.createServer((U,D)=>{try{let f=new URL(U.url||"",`http://${Z}:${A}`);if(f.pathname!==$.callbackPath){D.statusCode=404,D.end("Not found");return}let L={url:f,code:f.searchParams.get("code")??void 0,state:f.searchParams.get("state")??void 0,provider:f.searchParams.get("provider")??void 0,error:f.searchParams.get("error")??void 0};if(L.error){D.statusCode=400,D.end(`Authentication failed: ${L.error}`),G(),H(L);return}if(!L.code){D.statusCode=400,D.end("Missing authorization code");return}if($.expectedState&&L.state!==$.expectedState){D.statusCode=400,D.end("State mismatch");return}D.statusCode=200,D.setHeader("Content-Type","text/html; charset=utf-8"),D.end(W),G(),H(L)}catch{D.statusCode=500,D.end("Internal error")}}),R=await new Promise((U)=>{let D=(f)=>{F.off("error",D),U({bound:!1,error:f})};F.once("error",D),F.listen(A,Z,()=>{F.off("error",D),V=F,U({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw G(),R.error}if(R.bound){B=A;let U=`http://${Z}:${A}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Z,port:A,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:K,cancelWait:()=>{G(),H(null)},close:()=>{G(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var K_=`<!DOCTYPE html>
279
279
  <html lang="en">
package/dist/index.js CHANGED
@@ -453,7 +453,7 @@ ${JSON.stringify(J,null,2)}`}startClaimLeaseHeartbeat($){let Q=Math.max(1000,Mat
453
453
  `)[0]?.trim())}function u1($){if(!$)return;let Q={...$},Z=P$(typeof Q.title==="string"?Q.title:void 0);if(Z)Q.title=Z;else delete Q.title;return Object.keys(Q).length>0?Q:void 0}function d8($){let Q=u1($.metadata)??{},Z=$.title!==void 0?P$($.title):fJ($.prompt);if(Z)Q.title=Z;return Object.keys(Q).length>0?Q:void 0}function UJ($){let Q=c8($);if(Q)return{agent:"teammate",sessionId:Q.rootSessionId,taskType:"team"};let Z=V5($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function DJ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:B5($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function OV($,Q,Z){Sz(bz($),{recursive:!0}),yz($,`${JSON.stringify(DJ({updatedAt:Q,context:Z,messages:[]}),null,2)}
454
454
  `,"utf8")}function qV($,Q){return E0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:Q?.endedAt??$.endedAt??void 0,exit_code:Q?.exitCode??$.exitCode??void 0,status:Q?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:Q?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function MV($,Q,Z){let J=0;while(!0){let W=await $();if(W===void 0)return{updated:!1};let Y=await Q(W);if(typeof Y==="object"&&Y!==null&&"updated"in Y&&Y.updated===!1){if(J+=1,J>=Z)return Y;continue}return Y}}import{existsSync as xz}from"node:fs";import{readFile as gz}from"node:fs/promises";import{formatDisplayUserInput as EV}from"@cline/shared";class l8{listeners=new Set;subscribe($,Q){let Z={listener:$,sessionId:Q?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let Q=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==Q)continue;Z.listener($)}}get size(){return this.listeners.size}}async function d1($){let Q=$?.trim();if(!Q||!xz(Q))return[];try{let Z=(await gz(Q,"utf8")).trim();if(!Z)return[];let J=JSON.parse(Z);if(Array.isArray(J))return NV(J);if(J&&typeof J==="object"&&!Array.isArray(J)){let W=J.messages;if(Array.isArray(W))return NV(W)}return[]}catch{return[]}}function mz($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:EV($.content)};return{...$,content:$.content.map((Q)=>{if(Q.type!=="text"||typeof Q.text!=="string")return Q;return{...Q,text:EV(Q.text)}})}}function NV($){return $.map(mz)}function RJ($){return $?{...$}:void 0}async function PV($,Q){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await Q.queueSpawnRequest($);let J=await Q.upsertSubagentSessionFromHook($);if(!J)return;await Q.appendSubagentHookAudit(J,$),await Q.applySubagentStatus(J,$)}function p8($){if(typeof $!=="string")return;let Q=$.trim();return Q.length>0?Q:void 0}function I0($){let Q=p8($);if(!Q)return;return Q.toLowerCase()==="unknown"?void 0:Q}function G5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function dz($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function TJ($){let Q=$??200;return Number.isFinite(Q)?Math.max(0,Math.floor(Q)):200}function lz($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function pz($){return $.isSubagent!==!0&&!p8($.parentSessionId)}function rz($){let Q=$.match(/\d{13,}/g);if(!Q||Q.length===0)return 0;let Z=0;for(let J of Q){let W=Number.parseInt(J,10);if(Number.isFinite(W)&&W>Z)Z=W}return Z}function LJ($){return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name,enableTools:$.enable_tools,enableSpawn:$.enable_spawn,enableTeams:$.enable_teams,isSubagent:!1,prompt:$.prompt,metadata:$.metadata,messagesPath:$.messages_path,updatedAt:$.ended_at??$.started_at}}async function iz($){let Q=TJ($);if(Q===0)return[];let Z=yV(),W=(await vz(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:rz(X.name.trim())})).sort((X,j)=>j.recency-X.recency||j.entry.name.localeCompare(X.entry.name));return(await Promise.all(W.map(async({entry:X})=>{let j=X.name.trim();if(!j)return;let V=SV(Z,j,`${j}.json`),B=await wV(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=E0.safeParse(H);if(!G.success)return;return LJ(G.data)}))).filter((X)=>Boolean(X)).sort((X,j)=>j.startedAt.localeCompare(X.startedAt)).slice(0,Q)}async function nz($,Q,Z){let J=TJ(Q);if(J===0)return await $.listSessions(0),[];let W=Z.includeSubagents?J:lz(J),Y=await $.listSessions(W);return(Z.includeSubagents?Y:Y.filter(pz)).slice(0,J)}function az($){if(typeof $==="string")return $.trim();let Q=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let J=Z;if(J.type!=="text")continue;let W=J.text?.trim();if(W)Q.push(W)}return Q.join(`
455
455
  `).trim()}function CV($){return $.replace(/\s+/g," ").trim()}function sz($,Q){if($.length<=Q)return $;return`${$.slice(0,Math.max(0,Q-3)).trimEnd()}...`}function oz($){for(let Q of["user","assistant"])for(let Z of $){if(Z.role!==Q)continue;let J=CV(az(Z.content));if(!J)continue;let W=Q==="user"?CV(cz(J)):J,Y=uz(W.split(`
456
- `)[0]??W);return sz(Y,50)}return}function tz($){let Q=0;for(let Z of $)Q+=G5(Z.metrics?.cost)??0;return Q}function ez($){let Q,Z;for(let J=$.length-1;J>=0;J-=1){let W=$[J];if(!Q)Q=I0(W.modelInfo?.provider);if(!Z)Z=I0(W.modelInfo?.id);if(Q&&Z)break}return{provider:Q,model:Z}}function $O($){return I0($?.provider)??I0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function QO($){return I0($?.model)??I0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function _J($,Q){let Z=dz($.metadata),J=p8(Q?.title)??p8(Z?.title),W=G5(Q?.totalCost)??G5(Z?.totalCost),Y=Z||J!==void 0||W!==void 0?{...Z??{},...J!==void 0?{title:J}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:I0(Q?.provider)??I0($.provider)??$O(Z)??"",model:I0(Q?.model)??I0($.model)??QO(Z)??"",metadata:Y}}function ZO($){let Q=$.content;if(!Array.isArray(Q))return!1;return Q.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function JO($,Q){if($.status!=="running"||$.interactive!==!0)return!1;let Z=Q.at(-1);return Z?.role==="assistant"&&!ZO(Z)}async function WO($,Q){return await Promise.all(Q.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let J=await $.readSessionMessages(Z.sessionId);return JO(Z,J)?{...Z,status:"idle"}:Z}))}async function YO($,Q){return await Promise.all(Q.map(async(Z)=>{let J=_J(Z),W=Boolean(p8(J.metadata?.title)),Y=Boolean(I0(J.provider)),X=Boolean(I0(J.model)),j=G5(J.metadata?.totalCost),V=j!==void 0&&j>0;if(W&&Y&&X&&V)return J;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return J;let H=ez(B),G=tz(B);return _J(Z,{title:W?void 0:oz(B),provider:Y?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function zJ($,Q={}){let Z=TJ(Q.limit),J=Q.includeSubagents===!0,W=await nz($,Z,{includeSubagents:J}),Y=Q.includeManifestFallback===!0&&W.length<Z?await iz(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...W,...Y]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let j=Y.length===0?W:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await WO($,j);if(Q.hydrate===!1)return V.map((B)=>_J(B));return await YO($,V)}async function XO($){let Q=$.trim();if(!Q)return;let Z=SV(yV(),Q,`${Q}.json`),J=await wV(Z,"utf8").catch(()=>{return});if(!J)return;try{let W=E0.safeParse(JSON.parse(J));return W.success?W.data.messages_path:void 0}catch{return}}async function jO($,Q={}){let Z=new Map;return await zJ({listSessions:async(W)=>{let Y=await $.listSessions(W);Z.clear();for(let X of Y)Z.set(X.sessionId,X);return Y.map(u8)},readSessionMessages:async(W)=>{let Y=Z.get(W)?.messagesPath??await XO(W);return await d1(Y)}},Q)}import{captureSdkError as AG}from"@cline/shared";import{createSessionId as Vq,isHubProtocolCompatible as Bq,resolveClineBuildEnv as Hq,resolveHubCommandTimeoutMs as Gq}from"@cline/shared";import{spawn as gO}from"node:child_process";import{closeSync as mO,mkdirSync as vO,openSync as cO}from"node:fs";import{basename as uO,dirname as dO,join as lO}from"node:path";import{fileURLToPath as pO}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as rO,isHubDaemonProcess as iV,isHubProtocolCompatible as iO,resolveClineBuildEnv as nV,withResolvedClineBuildEnv as nO}from"@cline/shared";import{createHash as VO,randomBytes as BO}from"node:crypto";import{existsSync as HO}from"node:fs";import{chmod as GO,mkdir as OJ,readFile as xV,rm as qJ,writeFile as gV}from"node:fs/promises";import{dirname as mV,join as MJ}from"node:path";import{resolveClineDataDir as i8,resolveClineDir as rv}from"@cline/shared/storage";var hV="0.0.52-nightly.1782444026";var r8={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:hV,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var KO="CLINE_HUB_DISCOVERY_PATH",AO="CLINE_HUB_BUILD_ID",kV=30000,FO=15000,fO=100;function UO($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function DO($){return VO("sha256").update($).digest("hex").slice(0,12)}function RO($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function vV(){return BO(32).toString("hex")}function _O($){return new Promise((Q)=>setTimeout(Q,$))}function TO($){return`${$}.lock`}async function LO($){try{let Q=JSON.parse(await xV(MJ($,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function IV($){await qJ($,{recursive:!0,force:!0}).catch(()=>{return})}function cV(){return process.env[AO]?.trim()||String(r8.version)}function C$($=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${DO($)}`,Z=process.env[KO]?.trim()||MJ(i8(),"locks","hub","owners",`${UO(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}function nv($=`hub-${Date.now().toString(36)}`){return C$($)}async function A0($){try{let Q=JSON.parse(await xV($,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function uV($,Q){await OJ(mV($),{recursive:!0}),await qJ($,{force:!0}).catch(()=>{return}),await gV($,`${JSON.stringify(Q,null,2)}
456
+ `)[0]??W);return sz(Y,50)}return}function tz($){let Q=0;for(let Z of $)Q+=G5(Z.metrics?.cost)??0;return Q}function ez($){let Q,Z;for(let J=$.length-1;J>=0;J-=1){let W=$[J];if(!Q)Q=I0(W.modelInfo?.provider);if(!Z)Z=I0(W.modelInfo?.id);if(Q&&Z)break}return{provider:Q,model:Z}}function $O($){return I0($?.provider)??I0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function QO($){return I0($?.model)??I0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function _J($,Q){let Z=dz($.metadata),J=p8(Q?.title)??p8(Z?.title),W=G5(Q?.totalCost)??G5(Z?.totalCost),Y=Z||J!==void 0||W!==void 0?{...Z??{},...J!==void 0?{title:J}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:I0(Q?.provider)??I0($.provider)??$O(Z)??"",model:I0(Q?.model)??I0($.model)??QO(Z)??"",metadata:Y}}function ZO($){let Q=$.content;if(!Array.isArray(Q))return!1;return Q.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function JO($,Q){if($.status!=="running"||$.interactive!==!0)return!1;let Z=Q.at(-1);return Z?.role==="assistant"&&!ZO(Z)}async function WO($,Q){return await Promise.all(Q.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let J=await $.readSessionMessages(Z.sessionId);return JO(Z,J)?{...Z,status:"idle"}:Z}))}async function YO($,Q){return await Promise.all(Q.map(async(Z)=>{let J=_J(Z),W=Boolean(p8(J.metadata?.title)),Y=Boolean(I0(J.provider)),X=Boolean(I0(J.model)),j=G5(J.metadata?.totalCost),V=j!==void 0&&j>0;if(W&&Y&&X&&V)return J;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return J;let H=ez(B),G=tz(B);return _J(Z,{title:W?void 0:oz(B),provider:Y?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function zJ($,Q={}){let Z=TJ(Q.limit),J=Q.includeSubagents===!0,W=await nz($,Z,{includeSubagents:J}),Y=Q.includeManifestFallback===!0&&W.length<Z?await iz(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...W,...Y]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let j=Y.length===0?W:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await WO($,j);if(Q.hydrate===!1)return V.map((B)=>_J(B));return await YO($,V)}async function XO($){let Q=$.trim();if(!Q)return;let Z=SV(yV(),Q,`${Q}.json`),J=await wV(Z,"utf8").catch(()=>{return});if(!J)return;try{let W=E0.safeParse(JSON.parse(J));return W.success?W.data.messages_path:void 0}catch{return}}async function jO($,Q={}){let Z=new Map;return await zJ({listSessions:async(W)=>{let Y=await $.listSessions(W);Z.clear();for(let X of Y)Z.set(X.sessionId,X);return Y.map(u8)},readSessionMessages:async(W)=>{let Y=Z.get(W)?.messagesPath??await XO(W);return await d1(Y)}},Q)}import{captureSdkError as AG}from"@cline/shared";import{createSessionId as Vq,isHubProtocolCompatible as Bq,resolveClineBuildEnv as Hq,resolveHubCommandTimeoutMs as Gq}from"@cline/shared";import{spawn as gO}from"node:child_process";import{closeSync as mO,mkdirSync as vO,openSync as cO}from"node:fs";import{basename as uO,dirname as dO,join as lO}from"node:path";import{fileURLToPath as pO}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as rO,isHubDaemonProcess as iV,isHubProtocolCompatible as iO,resolveClineBuildEnv as nV,withResolvedClineBuildEnv as nO}from"@cline/shared";import{createHash as VO,randomBytes as BO}from"node:crypto";import{existsSync as HO}from"node:fs";import{chmod as GO,mkdir as OJ,readFile as xV,rm as qJ,writeFile as gV}from"node:fs/promises";import{dirname as mV,join as MJ}from"node:path";import{resolveClineDataDir as i8,resolveClineDir as rv}from"@cline/shared/storage";var hV="0.0.52";var r8={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:hV,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var KO="CLINE_HUB_DISCOVERY_PATH",AO="CLINE_HUB_BUILD_ID",kV=30000,FO=15000,fO=100;function UO($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function DO($){return VO("sha256").update($).digest("hex").slice(0,12)}function RO($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(Q){return Q instanceof Error&&"code"in Q?String(Q.code)==="EPERM":!1}}function vV(){return BO(32).toString("hex")}function _O($){return new Promise((Q)=>setTimeout(Q,$))}function TO($){return`${$}.lock`}async function LO($){try{let Q=JSON.parse(await xV(MJ($,"owner.json"),"utf8"));if(typeof Q.pid!=="number"||typeof Q.acquiredAt!=="string")return;return{pid:Q.pid,acquiredAt:Q.acquiredAt}}catch{return}}async function IV($){await qJ($,{recursive:!0,force:!0}).catch(()=>{return})}function cV(){return process.env[AO]?.trim()||String(r8.version)}function C$($=process.argv[1]?.trim()||process.cwd()){let Q=`hub-${DO($)}`,Z=process.env[KO]?.trim()||MJ(i8(),"locks","hub","owners",`${UO(Q)}.json`);return{ownerId:Q,discoveryPath:Z}}function nv($=`hub-${Date.now().toString(36)}`){return C$($)}async function A0($){try{let Q=JSON.parse(await xV($,"utf8"));if(typeof Q.hubId!=="string"||typeof Q.protocolVersion!=="string"||typeof Q.authToken!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string"||typeof Q.startedAt!=="string"||typeof Q.updatedAt!=="string")return;return{hubId:Q.hubId,protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,authToken:Q.authToken,host:Q.host,port:Q.port,url:Q.url,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:Q.startedAt,updatedAt:Q.updatedAt}}catch{return}}async function uV($,Q){await OJ(mV($),{recursive:!0}),await qJ($,{force:!0}).catch(()=>{return}),await gV($,`${JSON.stringify(Q,null,2)}
457
457
  `,{encoding:"utf8",mode:384}),await GO($,384)}async function n0($){await qJ($,{force:!0}).catch(()=>{return})}async function dV($,Q){let Z=TO($);await OJ(mV(Z),{recursive:!0});let J=Date.now()+FO;while(!0)try{await OJ(Z,{recursive:!1}),await gV(MJ(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
458
458
  `,"utf8");try{return await Q()}finally{await IV(Z)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let X=await LO(Z),j=X?Date.now()-Date.parse(X.acquiredAt):kV+1;if(!X||!RO(X.pid)||j>kV){await IV(Z);continue}if(Date.now()>=J)throw Error(`Timed out waiting for hub startup lock ${Z}`);await _O(fO)}}async function w$($,Q){try{let Z=await fetch(Q?.authToken?zO($):lV($),{headers:Q?.authToken?{authorization:`Bearer ${Q.authToken}`}:void 0});if(!Z.ok)return;let J=await Z.json();if(typeof J.protocolVersion!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string")return;return{protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,host:J.host,port:J.port,url:J.url,hubId:typeof J.hubId==="string"?J.hubId:void 0,authToken:typeof J.authToken==="string"?J.authToken:void 0,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:typeof J.startedAt==="string"?J.startedAt:void 0,updatedAt:typeof J.updatedAt==="string"?J.updatedAt:void 0}}catch{return}}function A1($,Q,Z="/hub"){return new URL(`ws://${$}:${Q}${Z}`).toString()}function lV($){let Q=new URL($);return Q.protocol=Q.protocol==="wss:"?"https:":"http:",Q.pathname="/health",Q.search="",Q.toString()}function zO($){let Q=new URL(lV($));return Q.pathname="/status",Q.toString()}function av($){return HO($)}import{CLINE_HUB_DEV_PORT as OO,CLINE_HUB_PORT as qO,resolveClineBuildEnv as MO}from"@cline/shared";var EO="CLINE_HUB_HOST",NO="CLINE_HUB_PORT",PO="CLINE_HUB_PATHNAME",CO="127.0.0.1",wO=qO,SO="/hub";function pV($){return MO($)==="development"?OO:wO}function yO($={}){return($.env??process.env)[EO]?.trim()||CO}function K5($={}){let Z=($.env??process.env)[NO]?.trim();if(!Z)return pV($);let J=Number.parseInt(Z,10);if(!Number.isInteger(J)||J<1||J>65535)return pV($);return J}function bO($={}){return($.env??process.env)[PO]?.trim()||SO}function l1($={},Q={}){return{host:$.host??yO(Q),port:$.port??K5(Q),pathname:$.pathname??bO(Q)}}import{join as hO}from"node:path";var kO="shared:cline",IO="CLINE_HUB_DISCOVERY_PATH",xO="hub-production";function Zc($){let Q=q$($.trim());return C$(`workspace:${Q||$.trim()}`)}function F1($=kO){return C$($)}function p1(){return{ownerId:xO,discoveryPath:process.env[IO]?.trim()||hO(i8(),"locks","hub","production.json")}}var aO=8000,sO=200,oO=3000,tO=100,eO=[100,250,500,1000,2000],$q="--cline-hub-daemon";function Qq($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function Zq(){try{let $=lO(i8(),"logs","hub-daemon.log");return vO(dO($),{recursive:!0}),{fd:cO($,"a"),logPath:$}}catch{return}}function aV(){return nV()==="production"?p1():F1()}function S$($){return iO($).compatible}function rV($,Q,Z){if(!Q||Q.url!==Z)return $;return{...$,authToken:$.authToken??Q.authToken,pid:$.pid??Q.pid}}async function y$($,Q){try{return await w$($,{authToken:Q})}catch{return}}async function Jq($,Q){let Z=Date.now()+Q;while(Date.now()<Z){if(!(await y$($))?.url)return!0;await new Promise((W)=>setTimeout(W,tO))}return!1}async function A5($,Q){if(await EJ($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await Jq($.url,oO);return await n0(Q).catch(()=>{return}),Z}async function n8($,Q){if(S$($))return!0;return A5($,Q)}async function sV($){if(nV()!=="production")return;let Q=F1();if(Q.discoveryPath===$.discoveryPath)return;let Z=await A0(Q.discoveryPath);if(Z?.url)await A5(Z,Q.discoveryPath);else await n0(Q.discoveryPath).catch(()=>{return})}function Wq(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return pO(new URL(`./entry.${$}`,import.meta.url))}function Yq($,Q){let Z=Wq(),J=process.execPath?.trim();if(!J)throw Error("unable to resolve runtime executable for hub daemon");let W=uO(J).toLowerCase().includes("bun"),Y=Z.startsWith("/$bunfs/"),X=W&&Z.toLowerCase().endsWith(".ts"),j=Y?[$q]:[...X?["--conditions=development"]:[],Z];return{launcher:J,args:[...j,"--cwd",$,...Qq(Q)],cwd:$,env:{...nO(process.env),CLINE_NO_INTERACTIVE:"1",[rO]:"1"}}}function Xq($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function jq($,Q={}){if(iV())return;let Z=Yq($,Q),J=Zq();try{gO(Z.launcher,Z.args,{detached:!0,stdio:J?["ignore",J.fd,J.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(J)mO(J.fd)}}async function F5($,Q={}){for(let Z=0;;Z++)try{jq($,Q);return}catch(J){let W=eO[Z];if(!Xq(J)||W===void 0)throw J;await new Promise((Y)=>setTimeout(Y,W))}}function oV($,Q={}){if(iV())return;let Z=aV(),J=l1(Q),W=A1(J.host,J.port,J.pathname),Y=Q.allowPortFallback===!0&&J.port!==0;sV(Z).catch(()=>{return}).then(()=>A0(Z.discoveryPath)).then(async(X)=>{let j=!1;if(X?.url)if(!X.authToken){if(j=!0,!await A5(X,Z.discoveryPath)&&!Y)return}else{let H=await y$(X.url,X.authToken);if(H?.url&&S$(H)&&await r1(H.url,{authToken:X.authToken}))return;if(H?.url)await n8({...H,authToken:X.authToken},Z.discoveryPath);else await n0(Z.discoveryPath).catch(()=>{return})}let V=await y$(W);if(V?.url){if(S$(V)){if(!Y||!j)return}else if(!await n8({...V,authToken:void 0},Z.discoveryPath)&&!Y)return}let B=Y?{...J,port:0}:J;await F5($,B)}).catch(()=>{})}async function Ac($,Q={}){let Z=aV(),J=Q.host!==void 0||Q.port!==void 0||Q.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=l1(Q),Y=A1(W.host,W.port,W.pathname),X=(A)=>{if(!J)N2(A.url,A.authToken);return A};await sV(Z).catch(()=>{return});let j=await A0(Z.discoveryPath),V=!1;if(j?.url){let A=j.authToken;if(!A)V=!0,await A5(j,Z.discoveryPath);else{let F=await y$(j.url,A);if(F?.url&&S$(F)&&await r1(F.url,{authToken:A}))return X({url:F.url,authToken:A});if(F?.url)await n8({...F,authToken:A},Z.discoveryPath);else await n0(Z.discoveryPath).catch(()=>{return})}}let B=await y$(Y);if(B?.url){let A=rV(B,j,Y);if(S$(B))throw Error(`A compatible Cline Hub is already running at ${Y}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${V?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await n8(A,Z.discoveryPath)&&Q.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${Y} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=Q.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await F5($,G);let K=Date.now()+aO;while(Date.now()<K){let A=await A0(Z.discoveryPath);if(A?.url&&A.authToken){let R=await y$(A.url,A.authToken);if(R?.url&&S$(R)&&await r1(R.url,{authToken:A.authToken}))return X({url:R.url,authToken:A.authToken})}let F=await y$(Y);if(F?.url&&!S$(F)){let R=rV(F,A,Y);if(!await n8(R,Z.discoveryPath)&&Q.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${Y} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,sO))}throw Error("Timed out waiting for detached hub startup.")}function U5(){return Hq()==="production"?p1():F1()}function Kq(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function ZB($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((Q)=>Buffer.from(Q))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return ZB($.data);return String($)}function Aq($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function tV($){let Q=$,Z=Aq(Q.reason);return new x0("hub_connection_closed",Q.code||Z?`Hub connection closed (code=${Q.code??0}${Z?`, reason=${Z}`:""})`:NJ,{closeCode:Q.code,closeReason:Z||void 0})}function Fq($,Q){if($ instanceof x0)return $;if($ instanceof Error)return new x0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new x0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new x0("hub_connect_failed",Z);let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new x0("hub_connect_failed",J?`Failed to connect to hub at ${Q.toString()} (${J} event before socket open).`:`Failed to connect to hub at ${Q.toString()}.`)}var fq=8000,Uq=200,eV="*",$B=8000,Dq="cline-hub-auth.",JB=new Map,WB=new Set,Rq=3000,_q=3000,Tq=100,NJ="Hub connection closed",Lq=250,zq=5000,QB=0.5;class x0 extends Error{code;details;constructor($,Q,Z){super(Q);this.code=$;this.details=Z;this.name="HubTransportError"}}function Oq($){return $ instanceof x0}class f5 extends Error{command;code;constructor($,Q,Z){super(Z);this.command=$;this.code=Q;this.name="HubCommandError"}}function YB($,Q){return $ instanceof f5&&$.code==="hub_command_timeout"&&(Q===void 0||$.command===Q)}function XB($){let Q=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Q)return Q;let Z=wJ($.toString());return Z?JB.get(Z):void 0}function qq($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function wJ($){if(!qq($))return;let Q=new URL(P2($));return Q.search="",Q.hash="",Q.toString()}function PJ($){let Q=wJ($);return!!Q&&WB.has(Q)}function N2($,Q){let Z=wJ($);if(Z){if(WB.add(Z),Q?.trim())JB.set(Z,Q)}return $}class f1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new x0("hub_connection_closed",NJ);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.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 $=new URL(this.currentUrl),Q=this.options.authToken?.trim()||XB($);$.hash="";let J=new(Kq())($.toString(),Q?[`${Dq}${Q}`]:void 0);this.socket=J;let W=!1;this.connectPromise=new Promise((Y,X)=>{let j=!1,V=setTimeout(()=>{if(j)return;j=!0,W=!0,this.lastCloseError=new x0("hub_connect_timeout",`Timed out connecting to hub after ${$B}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{J.close()}catch{}X(this.lastCloseError)},$B);J.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(V),Y()}),J.addEventListener("error",(B)=>{if(j)return;j=!0,clearTimeout(V),this.lastCloseError=Fq(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),J.addEventListener("close",(B)=>{if(j)return;if(j=!0,clearTimeout(V),!W)this.lastCloseError=tV(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),J.addEventListener("message",(Y)=>{this.handleFrame(JSON.parse(ZB(Y)))}),J.addEventListener("close",(Y)=>{if(this.socket!==J)return;if(!W)this.lastCloseError=tV(Y),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.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 Y of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Y));this.reconnectAttempt=0}subscribe($,Q){let Z=Q?.sessionId?.trim()||void 0,J={listener:$,sessionId:Z};return this.listeners.add(J),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(J))return;this.adjustSubscriptionCount(Z,-1)}}async command($,Q,Z,J){let W=0,Y=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,Q,Z,J)}catch(X){if(!Y||W>=1||!await this.recoverLocalHubTransport(X))throw X;W+=1}}async commandOnce($,Q,Z,J){await this.connect();let W=Vq("hubreq_"),Y=Gq($,J?.timeoutMs),X=new Promise((V,B)=>{let H=Y===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;B(new f5($,"hub_command_timeout",`Hub command ${$} timed out after ${Y}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.`))},Y);this.pendingReplies.set(W,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Z,timeoutMs:Y,payload:Q}})}catch(V){throw this.pendingReplies.delete(W),V}let j=await X;if(!j.ok){if(j.error?.code===S8){let V=Z??(typeof Q?.sessionId==="string"?Q.sessionId:void 0);throw new z$(V,j.error.message)}throw new f5($,j.error?.code,j.error?.message??`Hub command ${$} failed`)}return j}async recoverLocalHubTransport($){if(!PJ(this.currentUrl)||!Oq($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Q=await a8({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Q)return!1;return this.currentUrl=Q,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 $=Math.min(Lq*2**this.reconnectAttempt,zq),Q=Math.round($*(1-QB)+Math.random()*$*QB);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Q)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!PJ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await a8({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new x0("hub_connection_closed",NJ),this.sawSocketClose=!1;for(let Q of this.pendingReplies.values())Q.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.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($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new x0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,Q){this.sendFrame({kind:$,clientId:this.clientId,...Q?{sessionId:Q}:{}})}adjustSubscriptionCount($,Q){let Z=this.subscriptionKeyForSessionId($),J=(this.subscriptionCounts.get(Z)??0)+Q;if(J<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Q<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,J),Q>0&&J===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??eV}subscriptionSessionIdFromKey($){return $===eV?void 0:$}handleFrame($){switch($.kind){case"reply":{let Q=$.envelope.requestId;if(!Q)return;let Z=this.pendingReplies.get(Q);if(!Z)return;this.pendingReplies.delete(Q),Z.resolve($.envelope);return}case"event":for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==$.envelope.sessionId?.trim())continue;Q.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function P2($){let Q=new URL($);if(Q.protocol==="http:")Q.protocol="ws:";else if(Q.protocol==="https:")Q.protocol="wss:";return Q.toString()}async function r1($,Q){let Z=new f1({url:$,authToken:Q?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function CJ($,Q){let Z=P2($),J=await w$(Z,{authToken:Q?.authToken});if(!J)return{status:"unreachable",url:Z};if(!Bq(J).compatible)return{status:"protocol_mismatch",url:Z};if(Q?.verifyConnection===!0&&!await r1(Z,{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,authToken:Q.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function Mq($){let Q=Date.now()+fq;while(Date.now()<Q){let Z=await A0($.discoveryPath);if(Z?.url){let J=await CJ(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(J.status==="compatible")return N2(J.url,Z.authToken)}await new Promise((J)=>setTimeout(J,Uq))}return}async function Eq($){let Q=Date.now()+_q;while(Date.now()<Q){if(!(await w$($).catch(()=>{return}))?.url)return!0;await new Promise((J)=>setTimeout(J,Tq))}return!1}function Nq($,Q){try{return P2($)===P2(Q)}catch{return!1}}function Pq($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let J=Z;if(J.status==="running"||J.status==="idle"||J.status==="pending")return!0;return Array.isArray(J.participants)&&J.participants.length>0})}async function Cq($,Q,Z){let J=new f1({url:$,authToken:Q,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let W=await J.command("session.list",{limit:500},void 0,{timeoutMs:Rq});return!Pq(W.payload)}catch{return!1}finally{await J.dispose().catch(()=>{return})}}async function SJ($={}){if($.endpoint?.trim()){let W=await CJ($.endpoint);return W.status==="compatible"?W.url:void 0}let Q=U5(),Z=await A0(Q.discoveryPath);if(!Z?.url)return;let J=await CJ(Z.url,{authToken:Z.authToken});if(J.status==="compatible")return N2(J.url,Z.authToken);if(J.status==="protocol_mismatch")await n0(Q.discoveryPath).catch(()=>{return});return}async function a8($={}){let Q=await SJ($);if(Q&&await r1(Q,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return Q;if($.endpoint?.trim())return;let Z=U5();return await F5($.workspaceRoot??process.cwd()),await Mq(Z)}async function EJ($,Q){let Z=new URL($),J=Q?.trim()||XB(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:J?{authorization:`Bearer ${J}`}:void 0})).ok}async function wq($=U5()){let Q=await A0($.discoveryPath);if(!Q?.url)return!1;try{if(await EJ(Q.url,Q.authToken))return!0}catch{}return!1}async function jB($){if(!PJ($.url))return;let Q=U5(),Z=await A0(Q.discoveryPath);if(!Z?.url||!Nq(Z.url,$.url))return;if(!await Cq(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await wq())return;if(!await Eq(Z.url))return;return await n0(Q.discoveryPath).catch(()=>{return}),await a8({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as VB,createSessionId as BB,HUB_CHECKPOINT_CAPABILITY as hq,HUB_COMPACTION_CAPABILITY as kq,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Iq,HUB_HOOK_CAPABILITY_PREFIX as xq,HUB_MISTAKE_LIMIT_CAPABILITY as gq,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as mq,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as vq,isHubToolExecutorName as cq}from"@cline/shared";function Sq($){return $?JSON.parse(JSON.stringify($)):void 0}function yq($){return $?JSON.parse(JSON.stringify($)):void 0}function bq($){let Q=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,J=(Array.isArray(Q?.history)?Q.history:[]).filter((X)=>!!X&&typeof X==="object"&&!Array.isArray(X)).flatMap((X)=>{let j=typeof X.ref==="string"?X.ref.trim():"",V=Number(X.createdAt),B=Number(X.runCount);if(!j||!Number.isFinite(V)||!Number.isInteger(B))return[];return[{ref:j,createdAt:V,runCount:B,...X.kind==="stash"||X.kind==="commit"?{kind:X.kind}:{}}]}),W=J.at(-1),Y=$?.checkpointEnabled===!0?!0:void 0;if(!Y&&J.length===0)return;return{...Y?{enabled:Y}:{},...W?{latest:W}:{},history:J}}function i1($){let{session:Q}=$,Z=Sq(Q.metadata);return{version:1,sessionId:Q.sessionId,source:Q.source,status:Q.status,createdAt:Q.startedAt,updatedAt:Q.updatedAt,endedAt:Q.endedAt??null,exitCode:Q.exitCode??null,interactive:Q.interactive,workspace:{cwd:Q.cwd,root:Q.workspaceRoot},model:{providerId:Q.provider,modelId:Q.model},capabilities:{enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams},lineage:{...Q.parentSessionId?{parentSessionId:Q.parentSessionId}:{},...Q.parentAgentId?{parentAgentId:Q.parentAgentId}:{},...Q.agentId?{agentId:Q.agentId}:{},...Q.conversationId?{conversationId:Q.conversationId}:{},isSubagent:Q.isSubagent},...Q.teamName?{team:{name:Q.teamName}}:{},...Q.prompt?{prompt:Q.prompt}:{},...Z?{metadata:Z}:{},...Q.messagesPath?{artifacts:{messagesPath:Q.messagesPath}}:{},...$.messages?{messages:yq($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let J=bq(Z);return J?{checkpoint:J}:{}})()}}function yJ($){return{sessionId:$.sessionId,parentSessionId:$.lineage.parentSessionId,agentId:$.lineage.agentId,parentAgentId:$.lineage.parentAgentId,conversationId:$.lineage.conversationId,isSubagent:$.lineage.isSubagent,source:$.source,startedAt:$.createdAt,endedAt:$.endedAt??void 0,exitCode:$.exitCode??void 0,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspaceRoot:$.workspace.root,teamName:$.team?.name,enableTools:$.capabilities.enableTools,enableSpawn:$.capabilities.enableSpawn,enableTeams:$.capabilities.enableTeams,prompt:$.prompt,metadata:$.metadata,updatedAt:$.updatedAt,messagesPath:$.artifacts?.messagesPath}}function C2($){if(!$)return;return JSON.parse(JSON.stringify($))}var uq=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function HB($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function GB($){if(!$)return;let{userInstructionService:Q,...Z}=$;return JSON.parse(JSON.stringify(Z))}function KB($){let Q=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof Q.agentId==="string"?Q.agentId:"",conversationId:typeof Q.conversationId==="string"?Q.conversationId:"",iteration:typeof Q.iteration==="number"?Q.iteration:0,metadata:Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0}}function b$($,Q,Z){$.manifest.push(Q),$.handlers.set(Q.capabilityName,Z)}function AB($,Q){let Z={manifest:[],handlers:new Map};for(let W of Object.keys(Q.toolExecutors??{}).filter(cq)){let Y=Q.toolExecutors?.[W];if(typeof Y!=="function")continue;b$(Z,{kind:"toolExecutor",executor:W,capabilityName:`${mq}${W}`},async({payload:X,abortSignal:j})=>{let V=Array.isArray(X.args)?[...X.args]:[],B={...KB(X.context),signal:j};return{result:await Y(...V,B)}})}for(let W of $?.extraTools??[])b$(Z,{kind:"tool",name:W.name,description:W.description,inputSchema:C2(W.inputSchema)??{},...W.lifecycle?{lifecycle:C2(W.lifecycle)}:{},capabilityName:`${Iq}${W.name}`},async({payload:Y,abortSignal:X,progress:j})=>{let V={...KB(Y.context),signal:X};return{result:await W.execute(Y.input,{...V,emitUpdate:(H)=>{j({update:H})}})}});let J=$?.hooks;if(J)for(let W of uq){let Y=J[W];if(typeof Y!=="function")continue;b$(Z,{kind:"hook",name:W,capabilityName:`${xq}${W}`},async({payload:X})=>({control:await Y(X.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;b$(Z,{kind:"compaction",capabilityName:kq,config:HB($.compaction)},async({payload:Y})=>({result:await W(Y.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;b$(Z,{kind:"checkpoint",capabilityName:hq,config:HB($.checkpoint)},async({payload:Y})=>({result:await W(Y.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;b$(Z,{kind:"mistakeLimit",capabilityName:gq},async({payload:Y})=>({result:await W(Y.context)}))}if($?.userInstructionService){let W=$.userInstructionService;b$(Z,{kind:"userInstructionService",capabilityName:vq},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Z}function DB($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let Q=$.message;if(typeof Q==="string"&&Q.trim())return Q.trim()}return}function dq($){return DB($)??"Capability request was cancelled."}function lq($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function pq($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function rq($){if(!$||typeof $!=="object"||Array.isArray($))return;let Q=$,Z=typeof Q.inputTokens==="number"?Q.inputTokens:void 0,J=typeof Q.outputTokens==="number"?Q.outputTokens:void 0;if(Z===void 0||J===void 0)return;return{inputTokens:Z,outputTokens:J,cacheReadTokens:typeof Q.cacheReadTokens==="number"?Q.cacheReadTokens:0,cacheWriteTokens:typeof Q.cacheWriteTokens==="number"?Q.cacheWriteTokens:0,totalCost:typeof Q.totalCost==="number"?Q.totalCost:0}}function FB($){if(!$)return;return{inputTokens:typeof $.inputTokens==="number"?$.inputTokens:0,outputTokens:typeof $.outputTokens==="number"?$.outputTokens:0,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function bJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function n1($,Q){return bJ($?.[Q])??0}function iq($){let Q=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Z=$?.totals&&typeof $.totals==="object"?$.totals:void 0,J=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=J?.teamRole==="teammate"||J?.teamRole==="lead"?J.teamRole:void 0;return{event:{type:"usage",agentId:typeof J?.agentId==="string"?J.agentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,inputTokens:n1(Q,"inputTokens"),outputTokens:n1(Q,"outputTokens"),cacheReadTokens:n1(Q,"cacheReadTokens"),cacheWriteTokens:n1(Q,"cacheWriteTokens"),cost:bJ(Q?.totalCost),totalInputTokens:n1(Z,"inputTokens"),totalOutputTokens:n1(Z,"outputTokens"),totalCacheReadTokens:n1(Z,"cacheReadTokens"),totalCacheWriteTokens:n1(Z,"cacheWriteTokens"),totalCost:bJ(Z?.totalCost)},teamAgentId:typeof J?.teamAgentId==="string"?J.teamAgentId:void 0,teamRole:W}}function nq($){let Q=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Z=$?.reason??Q?.finishReason,J=pq(Z)?Z:Z==="failed"?"error":"completed",W=rq($?.usage??Q?.usage);return{type:"done",reason:J,text:typeof $?.text==="string"?$.text:typeof Q?.text==="string"?Q.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof Q?.iterations==="number"?Q.iterations:0,usage:W}}function D5($,Q){return $.error?.message??`hub command failed: ${Q}`}function s8($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function RB($){let Q=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof Q?.agentId==="string"?Q.agentId:void 0),parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,isSubagent:typeof Q?.isSubagent==="boolean"?Q.isSubagent:!1,source:typeof Q?.source==="string"?Q.source:_0.CORE,pid:typeof Q?.pid==="number"?Q.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:s8($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:s8($.status)==="completed"?0:s8($.status)==="failed"?1:void 0,status:s8($.status),interactive:Q?.interactive===!0,provider:typeof Q?.provider==="string"?Q.provider:"hub",model:typeof Q?.model==="string"?Q.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof Q?.teamName==="string"?Q.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??Q?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??Q?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??Q?.enableTeams===!0,prompt:typeof Q?.prompt==="string"?Q.prompt:void 0,metadata:Q,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,hookPath:typeof Q?.hookPath==="string"?Q.hookPath:void 0}}function a1($){if(!$||typeof $!=="object"||Array.isArray($))return;let Q=$;return Q.version===1&&typeof Q.sessionId==="string"?JSON.parse(JSON.stringify(Q)):void 0}function aq($){let Q=a1($?.snapshot);if(Q)return yJ(Q);let Z=$?.session;return Z?RB(Z):void 0}function fB($,Q,Z){let J=Z?.workspaceRoot?.trim()||Q.config.workspaceRoot||Q.config.cwd;return E0.parse({version:1,session_id:$,source:Q.source??_0.CORE,pid:process.pid,started_at:new Date(Z?.createdAt??Date.now()).toISOString(),status:s8(Z?.status),interactive:Q.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Z?.cwd?.trim()||Q.config.cwd,workspace_root:J,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,metadata:Q.sessionMetadata&&Object.keys(Q.sessionMetadata).length>0?Q.sessionMetadata:void 0})}function UB($,Q){return E0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??Q.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class h${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new l8;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,Q){this.clientContext=Q,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd},this.defaultCapabilities=T0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Z)=>this.requestPendingPromptsList(Z),update:(Z)=>this.requestPendingPromptUpdate(Z),delete:(Z)=>this.requestPendingPromptDelete(Z)},this.client=this.createClient($.url)}createClient($){return new f1({...this.clientOptions,url:$})}async replaceClient($){let Q=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(Q.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!YB($,"session.create"))return!1;let Q=await jB({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!Q)return!1;return await this.replaceClient(Q),!0}registerPlannedSession($,Q,Z){if(this.sessionCapabilities.set($,Q),Z.size>0)this.sessionClientContributionHandlers.set($,Z);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let Q=this.resolveCapabilities($),Z=AB($.localRuntime,Q),J=$.config.sessionId?.trim()||BB(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:C2({...$.config,sessionId:J}),metadata:{...$.sessionMetadata??{},source:$.source??_0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Z.manifest.length>0?{clientContributions:Z.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:C2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(J,Q,Z.handlers);let Y;try{Y=await W()}catch(B){if(this.cleanupPlannedSession(J),await this.recoverLocalHubStartupDeadlock(B)){this.registerPlannedSession(J,Q,Z.handlers);try{Y=await W()}catch(H){throw this.cleanupPlannedSession(J),H}}else throw B}let X=a1(Y.payload?.snapshot),j=Y.payload?.session,V=(X?.sessionId??j?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(J),Error("Hub runtime did not return a session id.");if(V!==J)this.cleanupPlannedSession(J),this.registerPlannedSession(V,Q,Z.handlers);return{sessionId:V,manifest:X?UB(X,$):fB(V,$,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let Q=$.sessionId.trim();if(!Q)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.start)throw Error("start is required when restore.messages is true");let J=$.start,W=J?this.resolveCapabilities(J):void 0,Y=J?AB(J.localRuntime,W??{}):{manifest:[],handlers:new Map},X=J?J.config.sessionId?.trim()||BB():void 0;if(X&&W)this.sessionCapabilities.set(X,W);if(X&&Y.handlers.size>0)this.sessionClientContributionHandlers.set(X,Y.handlers),this.ensureSessionSubscription(X);let j;try{j=await this.client.command("session.restore",{sessionId:Q,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...J?{workspaceRoot:J.config.workspaceRoot?.trim()||J.config.cwd,cwd:J.config.cwd??$.cwd,sessionConfig:C2({...J.config,sessionId:X}),metadata:{...J.sessionMetadata??{},source:J.source??_0.CORE,provider:J.config.providerId,model:J.config.modelId,enableTools:J.config.enableTools,enableSpawn:J.config.enableSpawnAgent,enableTeams:J.config.enableAgentTeams,teamName:J.config.teamName,prompt:J.prompt,interactive:J.interactive===!0},runtimeOptions:{...Y.manifest.length>0?{clientContributions:Y.manifest}:{},...J.localRuntime?.configExtensions?{configExtensions:J.localRuntime.configExtensions}:{}},toolPolicies:C2(J.toolPolicies)}:{}},Q)}catch(A){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw A}if(!j.ok){let A=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error(A)}let V=a1(j.payload?.snapshot),B=j.payload?.session,H=(V?.sessionId??B?.sessionId)?.trim();if(Z&&!H){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error("Hub checkpoint restore returned no session id")}if(H&&X&&H!==X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&Y.handlers.size>0)this.sessionClientContributionHandlers.set(H,Y.handlers);if(H)this.ensureSessionSubscription(H);let G=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,K=j.payload?.checkpoint;if(!K)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:V?UB(V,J??{}):fB(H,J??{},B),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:G,checkpoint:K}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let Q=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(Q.payload?.prompts)?Q.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let Q=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(Q.payload?.prompts)?Q.payload.prompts:[],prompt:Q.payload?.prompt,updated:Q.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let Q=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(Q.payload?.prompts)?Q.payload.prompts:[],prompt:Q.payload?.prompt,removed:Q.payload?.removed===!0}}async getAccumulatedUsage($){let Q=await this.client.command("session.get",{includeSnapshot:!0},$),Z=a1(Q.payload?.snapshot);if(Z){let X=Z.usage?{...Z.usage}:void 0,j=Z.aggregateUsage?{...Z.aggregateUsage}:void 0;return X||j?{usage:X,aggregateUsage:j}:void 0}let J=Q.payload?.session,W=FB(J?.usage),Y=FB(J?.aggregateUsage);return W||Y?{usage:W,aggregateUsage:Y}:void 0}async abort($,Q){await this.client.command("run.abort",{sessionId:$,reason:DB(Q)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,Q]of this.sessionSubscriptions){Q();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let Q;try{Q=await this.client.command("session.get",void 0,$)}catch(Z){if(O$(Z))return;throw Z}return aq(Q.payload)}async listSessions($=100){let Q=await this.client.command("session.list",{limit:$}),Z=Array.isArray(Q.payload?.snapshots)?Q.payload.snapshots.flatMap((W)=>{let Y=a1(W);return Y?[yJ(Y)]:[]}):[];if(Z.length>0)return Z;return(Q.payload?.sessions??[]).map(RB)}async listSettings($){let Q=await this.client.command("settings.list",GB($));if(!Q.ok)throw Error(D5(Q,"settings.list"));return Q.payload?.snapshot}async toggleSetting($){let Q=await this.client.command("settings.toggle",GB($));if(!Q.ok)throw Error(D5(Q,"settings.toggle"));return{snapshot:Q.payload?.snapshot,changedTypes:Array.isArray(Q.payload?.changedTypes)?Q.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,Q){let Z={...Q.metadata??{}};if(typeof Q.prompt==="string")Z.prompt=Q.prompt;if(typeof Q.title==="string")Z.title=Q.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Z})).ok}}async readSessionMessages($){let Q=$.trim();if(!Q)return[];let Z=await this.client.command("session.messages",{sessionId:Q},Q);if(!Z.ok)throw VB(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(D5(Z,"session.messages")),severity:Z.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:Q,errorCode:Z.error?.code,runtimeAddress:this.runtimeAddress}}),Error(D5(Z,"session.messages"));let J=Z.payload?.messages;return Array.isArray(J)?J:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,Q){return this.events.subscribe($,Q)}ensureSessionSubscription($){let Q=$.trim();if(!Q||this.sessionSubscriptions.has(Q))return;let Z=this.client.subscribe((J)=>{this.handleHubEvent(J)},{sessionId:Q});this.sessionSubscriptions.set(Q,typeof Z==="function"?Z:()=>{})}disposeSessionSubscription($){let Q=$.trim();if(!Q)return;this.sessionSubscriptions.get(Q)?.(),this.sessionSubscriptions.delete(Q),this.agentDoneEmittedForCurrentRunBySession.delete(Q)}resolveCapabilities($){return T0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:nq($.payload)}})}handleHubEvent($){let Q=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Z,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Z,$)});return}if(!Q)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(Q);let Z=a1($.payload?.snapshot),J=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:Q,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:Q,status:J?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"";if(!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_start",contentType:"text",text:Z}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"",J=$.payload?.redacted===!0;if(!Z&&!J)return;this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_start",contentType:"reasoning",reasoning:Z,redacted:J}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:Q,payload:$.payload});return}case"usage.updated":{let Z=iq($.payload);this.events.emit({type:"agent_event",payload:{sessionId:Q,event:Z.event,teamAgentId:Z.teamAgentId,teamRole:Z.teamRole}});return}case"tool.started":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z&&this.pendingApprovalToolCallIds.delete(Z))return;this.emitToolCallContentStart({sessionId:Q,toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z)this.pendingApprovalToolCallIds.delete(Z);this.events.emit({type:"agent_event",payload:{sessionId:Q,event:{type:"content_end",contentType:"tool",toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Z=a1($.payload?.snapshot),J=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:Q,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:Q,status:J?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:Q,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Z=$.payload?.prompt;if(!Z)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:Q,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Z=a1($.payload?.snapshot),J=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:Q,payload:{...$.payload,reason:J}}),Z?.interactive===!0&&Y0(Z.status))return;this.events.emit({type:"ended",payload:{sessionId:Q,reason:J,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,Q,Z){try{VB(this.telemetry,{component:"core",operation:$,error:Q,severity:"warn",handled:!0,context:{event:Z.event,sessionId:Z.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let Q=$.sessionId?.trim();if(!Q)return;let Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Z&&Z!==this.client.getClientId())return;let J=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!J)return;let Y=this.sessionClientContributionHandlers.get(Q)?.get(W);if(!Y){await this.client.command("capability.respond",{requestId:J,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${Q}.`},Q).catch(()=>{});return}let X=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(J,j);let V=(B)=>{this.client.command("capability.progress",{requestId:J,payload:B},Q).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let B=await Y({payload:X,abortSignal:j.signal,progress:V});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:J,ok:!0,payload:B},Q)}catch(B){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:J,ok:!1,error:B instanceof Error?B.message:String(B)},Q)}finally{this.activeCapabilityAbortControllers.delete(J)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let Q=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!Q)return;let Z=this.activeCapabilityAbortControllers.get(Q);if(!Z)return;Z.abort(dq($.payload.error))}async handleApprovalRequested($){let Q=$.sessionId?.trim();if(!Q)return;let Z=this.sessionCapabilities.get(Q)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Z)return;let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",Y=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!J||!W||!Y)return;let X=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},j=lq($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:Q,toolCallId:W,toolName:Y,toolInput:j});let V=await Promise.resolve(Z({sessionId:Q,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:Q,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:Y,input:j,policy:X})).catch((B)=>({approved:!1,reason:B instanceof Error?B.message:`Tool approval request failed: ${String(B)}`}));await this.client.command("approval.respond",{approvalId:J,approved:V.approved,reason:V.reason},Q).catch(()=>{})}}class R5 extends h${constructor($){super({url:P2($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as sq,mkdirSync as oq}from"node:fs";import{join as tq}from"node:path";import{asBool as o8,asOptionalString as $1,asString as U1,ensureSessionSchema as eq,loadSqliteDb as $M,nowIso as _5,toBoolInt as t8}from"@cline/shared/db";import{resolveDbDataDir as QM}from"@cline/shared/storage";class s1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??QM()}init(){this.getRawDb()}ensureSessionsDir(){if(!sq(this.sessionsDirPath))oq(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return tq(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=$M(this.sessionDbPath());return eq($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,Q=[]){return this.getRawDb().prepare($).run(...Q)}queryOne($,Q=[]){return this.getRawDb().prepare($).get(...Q)??void 0}queryAll($,Q=[]){return this.getRawDb().prepare($).all(...Q)}create($){let Q=_5();this.run(`INSERT OR REPLACE INTO sessions (
459
459
  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.52-nightly.1782444026",
4
+ "version": "0.0.52",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/cline/cline",
@@ -48,9 +48,9 @@
48
48
  "test:watch": "vitest --config vitest.config.ts"
49
49
  },
50
50
  "dependencies": {
51
- "@cline/agents": "0.0.52-nightly.1782444026",
52
- "@cline/shared": "0.0.52-nightly.1782444026",
53
- "@cline/llms": "0.0.52-nightly.1782444026",
51
+ "@cline/agents": "0.0.52",
52
+ "@cline/shared": "0.0.52",
53
+ "@cline/llms": "0.0.52",
54
54
  "@modelcontextprotocol/sdk": "^1.29.0",
55
55
  "@opentelemetry/api": "^1.9.0",
56
56
  "@opentelemetry/api-logs": "^0.214.0",