@sctg/cline-core 3.89.2-beta.20260620150721 → 3.89.2-beta.20260620160351

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.
@@ -506,7 +506,7 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
506
506
  updated_at = ?
507
507
  WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,J,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,J){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(J,T0(),$)}attachReportPathToRun($,J){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(J,T0(),$)}}class YJ{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new XJ({dbPath:$.dbPath});let J=$.specs;this.reconciler=new w3({store:this.store,specs:J}),this.materializer=new QJ({store:this.store}),this.eventIngress=new U3({store:this.store,logger:$.logger}),this.runner=new ZJ({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:J,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new C3({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Q)=>{let Z=$.logger;if(Z)if(Z.error)Z.error("cron.watcher.failed",{error:Q});else Z.log("cron.watcher.failed",{error:Q})}})}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 cA={};w(cA,{manifestToSessionRecord:()=>eQ,listSessionHistoryFromBackend:()=>I3,listSessionHistory:()=>$Z,hydrateSessionHistory:()=>vA});import{readdir as mq,readFile as xA}from"node:fs/promises";import{join as gA}from"node:path";import{formatDisplayUserInput as vq,normalizeUserInput as cq}from"@sctg/cline-shared";import{resolveSessionDataDir as mA}from"@sctg/cline-shared/storage";import{existsSync as Iq}from"node:fs";import{readFile as xq}from"node:fs/promises";import{formatDisplayUserInput as bA}from"@sctg/cline-shared";class VJ{listeners=new Set;subscribe($,J){let Q={listener:$,sessionId:J?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let J=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J)continue;Q.listener($)}}get size(){return this.listeners.size}}async function M1($){let J=$?.trim();if(!J||!Iq(J))return[];try{let Q=(await xq(J,"utf8")).trim();if(!Q)return[];let Z=JSON.parse(Q);if(Array.isArray(Z))return hA(Z);if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let W=Z.messages;if(Array.isArray(W))return hA(W)}return[]}catch{return[]}}function gq($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:bA($.content)};return{...$,content:$.content.map((J)=>{if(J.type!=="text"||typeof J.text!=="string")return J;return{...J,text:bA(J.text)}})}}function hA($){return $.map(gq)}function b3($){return $?{...$}:void 0}async function kA($,J){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await J.queueSpawnRequest($);let Z=await J.upsertSubagentSessionFromHook($);if(!Z)return;await J.appendSubagentHookAudit(Z,$),await J.applySubagentStatus(Z,$)}function HJ($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function s0($){let J=HJ($);if(!J)return;return J.toLowerCase()==="unknown"?void 0:J}function tQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function uq($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function k3($){let J=$??200;return Number.isFinite(J)?Math.max(0,Math.floor(J)):200}function dq($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function lq($){return $.isSubagent!==!0&&!HJ($.parentSessionId)}function pq($){let J=$.match(/\d{13,}/g);if(!J||J.length===0)return 0;let Q=0;for(let Z of J){let W=Number.parseInt(Z,10);if(Number.isFinite(W)&&W>Q)Q=W}return Q}function eQ($){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 rq($){let J=k3($);if(J===0)return[];let Q=mA(),W=(await mq(Q,{withFileTypes:!0}).catch(()=>[])).filter((f)=>f.isDirectory()).map((f)=>({entry:f,recency:pq(f.name.trim())})).sort((f,X)=>X.recency-f.recency||X.entry.name.localeCompare(f.entry.name));return(await Promise.all(W.map(async({entry:f})=>{let X=f.name.trim();if(!X)return;let Y=gA(Q,X,`${X}.json`),V=await xA(Y,"utf8").catch(()=>{return});if(!V)return;let H;try{H=JSON.parse(V)}catch{return}let A=S0.safeParse(H);if(!A.success)return;return eQ(A.data)}))).filter((f)=>Boolean(f)).sort((f,X)=>X.startedAt.localeCompare(f.startedAt)).slice(0,J)}async function iq($,J,Q){let Z=k3(J);if(Z===0)return await $.listSessions(0),[];let W=Q.includeSubagents?Z:dq(Z),j=await $.listSessions(W);return(Q.includeSubagents?j:j.filter(lq)).slice(0,Z)}function nq($){if(typeof $==="string")return $.trim();let J=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let Z=Q;if(Z.type!=="text")continue;let W=Z.text?.trim();if(W)J.push(W)}return J.join(`
508
508
  `).trim()}function IA($){return $.replace(/\s+/g," ").trim()}function aq($,J){if($.length<=J)return $;return`${$.slice(0,Math.max(0,J-3)).trimEnd()}...`}function sq($){for(let J of["user","assistant"])for(let Q of $){if(Q.role!==J)continue;let Z=IA(nq(Q.content));if(!Z)continue;let W=J==="user"?IA(vq(Z)):Z,j=cq(W.split(`
509
- `)[0]??W);return aq(j,50)}return}function oq($){let J=0;for(let Q of $)J+=tQ(Q.metrics?.cost)??0;return J}function tq($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=s0(W.modelInfo?.provider);if(!Q)Q=s0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function eq($){return s0($?.provider)??s0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function $P($){return s0($?.model)??s0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function h3($,J){let Q=uq($.metadata),Z=HJ(J?.title)??HJ(Q?.title),W=tQ(J?.totalCost)??tQ(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:s0(J?.provider)??s0($.provider)??eq(Q)??"",model:s0(J?.model)??s0($.model)??$P(Q)??"",metadata:j}}function JP($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function QP($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!JP(Q)}async function ZP($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return QP(Q,Z)?{...Q,status:"idle"}:Q}))}async function vA($,J){return await Promise.all(J.map(async(Q)=>{let Z=h3(Q),W=Boolean(HJ(Z.metadata?.title)),j=Boolean(s0(Z.provider)),f=Boolean(s0(Z.model)),X=tQ(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=tq(V),A=oq(V);return h3(Q,{title:W?void 0:sq(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||A<=0?void 0:A})}))}async function $Z($,J={}){let Q=k3(J.limit),Z=J.includeSubagents===!0,W=await iq($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await rq(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await ZP($,X);if(J.hydrate===!1)return Y.map((V)=>h3(V));return await vA($,Y)}async function WP($){let J=$.trim();if(!J)return;let Q=gA(mA(),J,`${J}.json`),Z=await xA(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=S0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function I3($,J={}){let Q=new Map;return await $Z({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map(B4)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await WP(W);return await M1(j)}},J)}var $K={};w($K,{resolveSessionBackend:()=>RW,createRuntimeHost:()=>i8});import{captureSdkError as tB}from"@sctg/cline-shared";import{createSessionId as tP,isHubProtocolCompatible as eP,resolveClineBuildEnv as $N,resolveHubCommandTimeoutMs as JN}from"@sctg/cline-shared";import{spawn as CP}from"node:child_process";import{closeSync as SP,mkdirSync as yP,openSync as EP}from"node:fs";import{basename as bP,dirname as hP,join as kP}from"node:path";import{fileURLToPath as IP}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as xP,isHubDaemonProcess as JB,isHubProtocolCompatible as gP,resolveClineBuildEnv as QB,withResolvedClineBuildEnv as mP}from"@sctg/cline-shared";import{createHash as jP,randomBytes as fP}from"node:crypto";import{existsSync as XP}from"node:fs";import{chmod as YP,mkdir as x3,readFile as rA,rm as g3,writeFile as iA}from"node:fs/promises";import{dirname as nA,join as m3}from"node:path";import{resolveClineDataDir as L2,resolveClineDir as aA}from"@sctg/cline-shared/storage";var dA="3.89.2-beta.20260620150721";var AJ={name:"@sctg/cline-core",description:"Cline Core SDK for Node Runtime",version:dA,repository:{type:"git",url:"https://github.com/TEA-ching/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:{"@sctg/cline-agents":"workspace:*","@sctg/cline-shared":"workspace:*","@sctg/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","markdown-docx":"^1.6.0",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 VP="CLINE_HUB_DISCOVERY_PATH",HP="CLINE_HUB_BUILD_ID",lA=30000,AP=15000,BP=100;function KP($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function GP($){return jP("sha256").update($).digest("hex").slice(0,12)}function FP($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function JZ(){return fP(32).toString("hex")}function DP($){return new Promise((J)=>setTimeout(J,$))}function UP($){return`${$}.lock`}async function RP($){try{let J=JSON.parse(await rA(m3($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function pA($){await g3($,{recursive:!0,force:!0}).catch(()=>{return})}function QZ(){return process.env[HP]?.trim()||String(AJ.version)}function d$($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${GP($)}`,Q=process.env[VP]?.trim()||m3(L2(),"locks","hub","owners",`${KP(J)}.json`);return{ownerId:J,discoveryPath:Q}}function sA($=`hub-${Date.now().toString(36)}`){return d$($)}async function G0($){try{let J=JSON.parse(await rA($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,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((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function ZZ($,J){await x3(nA($),{recursive:!0}),await g3($,{force:!0}).catch(()=>{return}),await iA($,`${JSON.stringify(J,null,2)}
509
+ `)[0]??W);return aq(j,50)}return}function oq($){let J=0;for(let Q of $)J+=tQ(Q.metrics?.cost)??0;return J}function tq($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=s0(W.modelInfo?.provider);if(!Q)Q=s0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function eq($){return s0($?.provider)??s0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function $P($){return s0($?.model)??s0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function h3($,J){let Q=uq($.metadata),Z=HJ(J?.title)??HJ(Q?.title),W=tQ(J?.totalCost)??tQ(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:s0(J?.provider)??s0($.provider)??eq(Q)??"",model:s0(J?.model)??s0($.model)??$P(Q)??"",metadata:j}}function JP($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function QP($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!JP(Q)}async function ZP($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return QP(Q,Z)?{...Q,status:"idle"}:Q}))}async function vA($,J){return await Promise.all(J.map(async(Q)=>{let Z=h3(Q),W=Boolean(HJ(Z.metadata?.title)),j=Boolean(s0(Z.provider)),f=Boolean(s0(Z.model)),X=tQ(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=tq(V),A=oq(V);return h3(Q,{title:W?void 0:sq(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||A<=0?void 0:A})}))}async function $Z($,J={}){let Q=k3(J.limit),Z=J.includeSubagents===!0,W=await iq($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await rq(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await ZP($,X);if(J.hydrate===!1)return Y.map((V)=>h3(V));return await vA($,Y)}async function WP($){let J=$.trim();if(!J)return;let Q=gA(mA(),J,`${J}.json`),Z=await xA(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=S0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function I3($,J={}){let Q=new Map;return await $Z({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map(B4)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await WP(W);return await M1(j)}},J)}var $K={};w($K,{resolveSessionBackend:()=>RW,createRuntimeHost:()=>i8});import{captureSdkError as tB}from"@sctg/cline-shared";import{createSessionId as tP,isHubProtocolCompatible as eP,resolveClineBuildEnv as $N,resolveHubCommandTimeoutMs as JN}from"@sctg/cline-shared";import{spawn as CP}from"node:child_process";import{closeSync as SP,mkdirSync as yP,openSync as EP}from"node:fs";import{basename as bP,dirname as hP,join as kP}from"node:path";import{fileURLToPath as IP}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as xP,isHubDaemonProcess as JB,isHubProtocolCompatible as gP,resolveClineBuildEnv as QB,withResolvedClineBuildEnv as mP}from"@sctg/cline-shared";import{createHash as jP,randomBytes as fP}from"node:crypto";import{existsSync as XP}from"node:fs";import{chmod as YP,mkdir as x3,readFile as rA,rm as g3,writeFile as iA}from"node:fs/promises";import{dirname as nA,join as m3}from"node:path";import{resolveClineDataDir as L2,resolveClineDir as aA}from"@sctg/cline-shared/storage";var dA="3.89.2-beta.20260620160351";var AJ={name:"@sctg/cline-core",description:"Cline Core SDK for Node Runtime",version:dA,repository:{type:"git",url:"https://github.com/TEA-ching/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:{"@sctg/cline-agents":"workspace:*","@sctg/cline-shared":"workspace:*","@sctg/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","markdown-docx":"^1.6.0",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 VP="CLINE_HUB_DISCOVERY_PATH",HP="CLINE_HUB_BUILD_ID",lA=30000,AP=15000,BP=100;function KP($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function GP($){return jP("sha256").update($).digest("hex").slice(0,12)}function FP($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function JZ(){return fP(32).toString("hex")}function DP($){return new Promise((J)=>setTimeout(J,$))}function UP($){return`${$}.lock`}async function RP($){try{let J=JSON.parse(await rA(m3($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function pA($){await g3($,{recursive:!0,force:!0}).catch(()=>{return})}function QZ(){return process.env[HP]?.trim()||String(AJ.version)}function d$($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${GP($)}`,Q=process.env[VP]?.trim()||m3(L2(),"locks","hub","owners",`${KP(J)}.json`);return{ownerId:J,discoveryPath:Q}}function sA($=`hub-${Date.now().toString(36)}`){return d$($)}async function G0($){try{let J=JSON.parse(await rA($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,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((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function ZZ($,J){await x3(nA($),{recursive:!0}),await g3($,{force:!0}).catch(()=>{return}),await iA($,`${JSON.stringify(J,null,2)}
510
510
  `,{encoding:"utf8",mode:384}),await YP($,384)}async function E0($){await g3($,{force:!0}).catch(()=>{return})}async function WZ($,J){let Q=UP($);await x3(nA(Q),{recursive:!0});let Z=Date.now()+AP;while(!0)try{await x3(Q,{recursive:!1}),await iA(m3(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
511
511
  `,"utf8");try{return await J()}finally{await pA(Q)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let f=await RP(Q),X=f?Date.now()-Date.parse(f.acquiredAt):lA+1;if(!f||!FP(f.pid)||X>lA){await pA(Q);continue}if(Date.now()>=Z)throw Error(`Timed out waiting for hub startup lock ${Q}`);await DP(BP)}}async function l$($,J){try{let Q=await fetch(J?.authToken?v3($):jZ($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function A$($,J,Q="/hub"){return new URL(`ws://${$}:${J}${Q}`).toString()}function jZ($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function v3($){let J=new URL(jZ($));return J.pathname="/status",J.toString()}function oA($){return XP($)}import{CLINE_HUB_DEV_PORT as LP,CLINE_HUB_PORT as TP,resolveClineBuildEnv as OP}from"@sctg/cline-shared";var _P="CLINE_HUB_HOST",MP="CLINE_HUB_PORT",zP="CLINE_HUB_PATHNAME",c3="127.0.0.1",u3=TP,d3="/hub";function tA($){return OP($)==="development"?LP:u3}function l3($={}){return($.env??process.env)[_P]?.trim()||c3}function k8($={}){let Q=($.env??process.env)[MP]?.trim();if(!Q)return tA($);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return tA($);return Z}function p3($={}){return($.env??process.env)[zP]?.trim()||d3}function o0($={},J={}){return{host:$.host??l3(J),port:$.port??k8(J),pathname:$.pathname??p3(J)}}import{join as qP}from"node:path";var PP="shared:cline",NP="CLINE_HUB_DISCOVERY_PATH",wP="hub-production";function eA($){let J=g$($.trim());return d$(`workspace:${J||$.trim()}`)}function b0($=PP){return d$($)}function t0(){return{ownerId:wP,discoveryPath:process.env[NP]?.trim()||qP(L2(),"locks","hub","production.json")}}var vP=8000,cP=200,uP=3000,dP=100,lP=[100,250,500,1000,2000],pP="--cline-hub-daemon";function rP($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function iP(){try{let $=kP(L2(),"logs","hub-daemon.log");return yP(hP($),{recursive:!0}),{fd:EP($,"a"),logPath:$}}catch{return}}function ZB(){return QB()==="production"?t0():b0()}function T2($){return gP($).compatible}function $B($,J,Q){if(!J||J.url!==Q)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function O2($,J){try{return await l$($,{authToken:J})}catch{return}}async function nP($,J){let Q=Date.now()+J;while(Date.now()<Q){if(!(await O2($))?.url)return!0;await new Promise((W)=>setTimeout(W,dP))}return!1}async function fZ($,J){if(await KJ($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await nP($.url,uP);return await E0(J).catch(()=>{return}),Q}async function BJ($,J){if(T2($))return!0;return fZ($,J)}async function WB($){if(QB()!=="production")return;let J=b0();if(J.discoveryPath===$.discoveryPath)return;let Q=await G0(J.discoveryPath);if(Q?.url)await fZ(Q,J.discoveryPath);else await E0(J.discoveryPath).catch(()=>{return})}function aP(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return IP(new URL(`./entry.${$}`,import.meta.url))}function sP($,J){let Q=aP(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let W=bP(Z).toLowerCase().includes("bun"),j=Q.startsWith("/$bunfs/"),f=W&&Q.toLowerCase().endsWith(".ts"),X=j?[pP]:[...f?["--conditions=development"]:[],Q];return{launcher:Z,args:[...X,"--cwd",$,...rP(J)],cwd:$,env:{...mP(process.env),CLINE_NO_INTERACTIVE:"1",[xP]:"1"}}}function oP($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function r3($,J={}){if(JB())return;let Q=sP($,J),Z=iP();try{CP(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)SP(Z.fd)}}async function I8($,J={}){for(let Q=0;;Q++)try{r3($,J);return}catch(Z){let W=lP[Q];if(!oP(Z)||W===void 0)throw Z;await new Promise((j)=>setTimeout(j,W))}}function XZ($,J={}){if(JB())return;let Q=ZB(),Z=o0(J),W=A$(Z.host,Z.port,Z.pathname),j=J.allowPortFallback===!0&&Z.port!==0;WB(Q).catch(()=>{return}).then(()=>G0(Q.discoveryPath)).then(async(f)=>{let X=!1;if(f?.url)if(!f.authToken){if(X=!0,!await fZ(f,Q.discoveryPath)&&!j)return}else{let H=await O2(f.url,f.authToken);if(H?.url&&T2(H)&&await R$(H.url,{authToken:f.authToken}))return;if(H?.url)await BJ({...H,authToken:f.authToken},Q.discoveryPath);else await E0(Q.discoveryPath).catch(()=>{return})}let Y=await O2(W);if(Y?.url){if(T2(Y)){if(!j||!X)return}else if(!await BJ({...Y,authToken:void 0},Q.discoveryPath)&&!j)return}let V=j?{...Z,port:0}:Z;await I8($,V)}).catch(()=>{})}async function jB($,J={}){let Q=ZB(),Z=J.host!==void 0||J.port!==void 0||J.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=o0(J),j=A$(W.host,W.port,W.pathname),f=(K)=>{if(!Z)z1(K.url,K.authToken);return K};await WB(Q).catch(()=>{return});let X=await G0(Q.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await fZ(X,Q.discoveryPath);else{let G=await O2(X.url,K);if(G?.url&&T2(G)&&await R$(G.url,{authToken:K}))return f({url:G.url,authToken:K});if(G?.url)await BJ({...G,authToken:K},Q.discoveryPath);else await E0(Q.discoveryPath).catch(()=>{return})}}let V=await O2(j);if(V?.url){let K=$B(V,X,j);if(T2(V))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" 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 BJ(K,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let A=J.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await I8($,A);let B=Date.now()+vP;while(Date.now()<B){let K=await G0(Q.discoveryPath);if(K?.url&&K.authToken){let R=await O2(K.url,K.authToken);if(R?.url&&T2(R)&&await R$(R.url,{authToken:K.authToken}))return f({url:R.url,authToken:K.authToken})}let G=await O2(j);if(G?.url&&!T2(G)){let R=$B(G,K,j);if(!await BJ(R,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} 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,cP))}throw Error("Timed out waiting for detached hub startup.")}function YZ(){return $N()==="production"?t0():b0()}function QN(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function HB($){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((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return HB($.data);return String($)}function ZN($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function fB($){let J=$,Q=ZN(J.reason);return new P0("hub_connection_closed",J.code||Q?`Hub connection closed (code=${J.code??0}${Q?`, reason=${Q}`:""})`:i3,{closeCode:J.code,closeReason:Q||void 0})}function WN($,J){if($ instanceof P0)return $;if($ instanceof Error)return new P0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new P0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new P0("hub_connect_failed",Q);let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new P0("hub_connect_failed",Z?`Failed to connect to hub at ${J.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var jN=8000,fN=200,XB="*",YB=8000,XN="cline-hub-auth.",AB=new Map,BB=new Set,YN=3000,VN=3000,HN=100,i3="Hub connection closed",AN=250,BN=5000,VB=0.5;class P0 extends Error{code;details;constructor($,J,Q){super(J);this.code=$;this.details=Q;this.name="HubTransportError"}}function s3($){return $ instanceof P0}class x8 extends Error{command;code;constructor($,J,Q){super(Q);this.command=$;this.code=J;this.name="HubCommandError"}}function VZ($,J){return $ instanceof x8&&$.code==="hub_command_timeout"&&(J===void 0||$.command===J)}function KB($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=o3($.toString());return Q?AB.get(Q):void 0}function KN($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function o3($){if(!KN($))return;let J=new URL(q1($));return J.search="",J.hash="",J.toString()}function n3($){let J=o3($);return!!J&&BB.has(J)}function z1($,J){let Q=o3($);if(Q){if(BB.add(Q),J?.trim())AB.set(Q,J)}return $}class B${options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new P0("hub_connection_closed",i3);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),J=this.options.authToken?.trim()||KB($);$.hash="";let Z=new(QN())($.toString(),J?[`${XN}${J}`]:void 0);this.socket=Z;let W=!1;this.connectPromise=new Promise((j,f)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,W=!0,this.lastCloseError=new P0("hub_connect_timeout",`Timed out connecting to hub after ${YB}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Z.close()}catch{}f(this.lastCloseError)},YB);Z.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),j()}),Z.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=WN(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)}),Z.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!W)this.lastCloseError=fB(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)})}),Z.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(HB(j)))}),Z.addEventListener("close",(j)=>{if(this.socket!==Z)return;if(!W)this.lastCloseError=fB(j),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await 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 j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,J){let Q=J?.sessionId?.trim()||void 0,Z={listener:$,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command($,J,Q,Z){let W=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Q,Z)}catch(f){if(!j||W>=1||!await this.recoverLocalHubTransport(f))throw f;W+=1}}async commandOnce($,J,Q,Z){await this.connect();let W=tP("hubreq_"),j=JN($,Z?.timeoutMs),f=new Promise((Y,V)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;V(new x8($,"hub_command_timeout",`Hub command ${$} timed out after ${j}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.`))},j);this.pendingReplies.set(W,{resolve:(A)=>{if(H)clearTimeout(H);Y(A)},reject:(A)=>{if(H)clearTimeout(H);V(A)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Q,timeoutMs:j,payload:J}})}catch(Y){throw this.pendingReplies.delete(W),Y}let X=await f;if(!X.ok){if(X.error?.code===F2){let Y=Q??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new c$(Y,X.error.message)}throw new x8($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!n3(this.currentUrl)||!s3($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await _2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,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(AN*2**this.reconnectAttempt,BN),J=Math.round($*(1-VB)+Math.random()*$*VB);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!n3(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await _2({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 P0("hub_connection_closed",i3),this.sawSocketClose=!1;for(let J of this.pendingReplies.values())J.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 P0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{}})}adjustSubscriptionCount($,J){let Q=this.subscriptionKeyForSessionId($),Z=(this.subscriptionCounts.get(Q)??0)+J;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,Z),J>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??XB}subscriptionSessionIdFromKey($){return $===XB?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Q=this.pendingReplies.get(J);if(!Q)return;this.pendingReplies.delete(J),Q.resolve($.envelope);return}case"event":for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$.envelope.sessionId?.trim())continue;J.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function q1($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function R$($,J){let Q=new B$({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function a3($,J){let Q=q1($),Z=await l$(Q,{authToken:J?.authToken});if(!Z)return{status:"unreachable",url:Q};if(!eP(Z).compatible)return{status:"protocol_mismatch",url:Q};if(J?.verifyConnection===!0&&!await R$(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function GN($){let J=Date.now()+jN;while(Date.now()<J){let Q=await G0($.discoveryPath);if(Q?.url){let Z=await a3(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(Z.status==="compatible")return z1(Z.url,Q.authToken)}await new Promise((Z)=>setTimeout(Z,fN))}return}async function FN($){let J=Date.now()+VN;while(Date.now()<J){if(!(await l$($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,HN))}return!1}function DN($,J){try{return q1($)===q1(J)}catch{return!1}}function UN($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let Z=Q;if(Z.status==="running"||Z.status==="idle"||Z.status==="pending")return!0;return Array.isArray(Z.participants)&&Z.participants.length>0})}async function RN($,J,Q){let Z=new B$({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let W=await Z.command("session.list",{limit:500},void 0,{timeoutMs:YN});return!UN(W.payload)}catch{return!1}finally{await Z.dispose().catch(()=>{return})}}async function GJ($={}){if($.endpoint?.trim()){let W=await a3($.endpoint);return W.status==="compatible"?W.url:void 0}let J=YZ(),Q=await G0(J.discoveryPath);if(!Q?.url)return;let Z=await a3(Q.url,{authToken:Q.authToken});if(Z.status==="compatible")return z1(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await E0(J.discoveryPath).catch(()=>{return});return}async function _2($={}){let J=await GJ($);if(J&&await R$(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;let Q=YZ();return await I8($.workspaceRoot??process.cwd()),await GN(Q)}async function KJ($,J){let Q=new URL($),Z=J?.trim()||KB(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}async function t3($=YZ()){let J=await G0($.discoveryPath);if(!J?.url)return!1;try{if(await KJ(J.url,J.authToken))return!0}catch{}return!1}async function HZ($){if(!n3($.url))return;let J=YZ(),Q=await G0(J.discoveryPath);if(!Q?.url||!DN(Q.url,$.url))return;if(!await RN(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await t3())return;if(!await FN(Q.url))return;return await E0(J.discoveryPath).catch(()=>{return}),await _2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var PB={};w(PB,{HubRuntimeHost:()=>p$});import{captureSdkError as FB,createSessionId as DB,HUB_CHECKPOINT_CAPABILITY as _N,HUB_COMPACTION_CAPABILITY as MN,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as zN,HUB_HOOK_CAPABILITY_PREFIX as qN,HUB_MISTAKE_LIMIT_CAPABILITY as PN,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as NN,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as wN,isHubToolExecutorName as CN}from"@sctg/cline-shared";var GB={};w(GB,{createCoreSessionSnapshot:()=>L$,coreSessionSnapshotToRecord:()=>AZ});function LN($){return $?JSON.parse(JSON.stringify($)):void 0}function TN($){return $?JSON.parse(JSON.stringify($)):void 0}function ON($){let J=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Z=(Array.isArray(J?.history)?J.history:[]).filter((f)=>!!f&&typeof f==="object"&&!Array.isArray(f)).flatMap((f)=>{let X=typeof f.ref==="string"?f.ref.trim():"",Y=Number(f.createdAt),V=Number(f.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(V))return[];return[{ref:X,createdAt:Y,runCount:V,...f.kind==="stash"||f.kind==="commit"?{kind:f.kind}:{}}]}),W=Z.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Z.length===0)return;return{...j?{enabled:j}:{},...W?{latest:W}:{},history:Z}}function L$($){let{session:J}=$,Q=LN(J.metadata);return{version:1,sessionId:J.sessionId,source:J.source,status:J.status,createdAt:J.startedAt,updatedAt:J.updatedAt,endedAt:J.endedAt??null,exitCode:J.exitCode??null,interactive:J.interactive,workspace:{cwd:J.cwd,root:J.workspaceRoot},model:{providerId:J.provider,modelId:J.model},capabilities:{enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams},lineage:{...J.parentSessionId?{parentSessionId:J.parentSessionId}:{},...J.parentAgentId?{parentAgentId:J.parentAgentId}:{},...J.agentId?{agentId:J.agentId}:{},...J.conversationId?{conversationId:J.conversationId}:{},isSubagent:J.isSubagent},...J.teamName?{team:{name:J.teamName}}:{},...J.prompt?{prompt:J.prompt}:{},...Q?{metadata:Q}:{},...J.messagesPath?{artifacts:{messagesPath:J.messagesPath}}:{},...$.messages?{messages:TN($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Z=ON(Q);return Z?{checkpoint:Z}:{}})()}}function AZ($){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 g8($){if(!$)return;return JSON.parse(JSON.stringify($))}var SN=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function UB($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function RB($){if(!$)return;let{userInstructionService:J,...Q}=$;return JSON.parse(JSON.stringify(Q))}function LB($){let J=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof J.agentId==="string"?J.agentId:"",conversationId:typeof J.conversationId==="string"?J.conversationId:"",iteration:typeof J.iteration==="number"?J.iteration:0,metadata:J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}}function M2($,J,Q){$.manifest.push(J),$.handlers.set(J.capabilityName,Q)}function TB($,J){let Q={manifest:[],handlers:new Map};for(let W of Object.keys(J.toolExecutors??{}).filter(CN)){let j=J.toolExecutors?.[W];if(typeof j!=="function")continue;M2(Q,{kind:"toolExecutor",executor:W,capabilityName:`${NN}${W}`},async({payload:f,abortSignal:X})=>{let Y=Array.isArray(f.args)?[...f.args]:[],V={...LB(f.context),signal:X};return{result:await j(...Y,V)}})}for(let W of $?.extraTools??[])M2(Q,{kind:"tool",name:W.name,description:W.description,inputSchema:g8(W.inputSchema)??{},...W.lifecycle?{lifecycle:g8(W.lifecycle)}:{},capabilityName:`${zN}${W.name}`},async({payload:j,abortSignal:f,progress:X})=>{let Y={...LB(j.context),signal:f};return{result:await W.execute(j.input,{...Y,emitUpdate:(H)=>{X({update:H})}})}});let Z=$?.hooks;if(Z)for(let W of SN){let j=Z[W];if(typeof j!=="function")continue;M2(Q,{kind:"hook",name:W,capabilityName:`${qN}${W}`},async({payload:f})=>({control:await j(f.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;M2(Q,{kind:"compaction",capabilityName:MN,config:UB($.compaction)},async({payload:j})=>({result:await W(j.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;M2(Q,{kind:"checkpoint",capabilityName:_N,config:UB($.checkpoint)},async({payload:j})=>({result:await W(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;M2(Q,{kind:"mistakeLimit",capabilityName:PN},async({payload:j})=>({result:await W(j.context)}))}if($?.userInstructionService){let W=$.userInstructionService;M2(Q,{kind:"userInstructionService",capabilityName:wN},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Q}function zB($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let J=$.message;if(typeof J==="string"&&J.trim())return J.trim()}return}function yN($){return zB($)??"Capability request was cancelled."}function EN($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function bN($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function hN($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=typeof J.inputTokens==="number"?J.inputTokens:void 0,Z=typeof J.outputTokens==="number"?J.outputTokens:void 0;if(Q===void 0||Z===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:typeof J.cacheReadTokens==="number"?J.cacheReadTokens:0,cacheWriteTokens:typeof J.cacheWriteTokens==="number"?J.cacheWriteTokens:0,totalCost:typeof J.totalCost==="number"?J.totalCost:0}}function OB($){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 e3($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function P1($,J){return e3($?.[J])??0}function kN($){let J=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Z=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=Z?.teamRole==="teammate"||Z?.teamRole==="lead"?Z.teamRole:void 0;return{event:{type:"usage",agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,inputTokens:P1(J,"inputTokens"),outputTokens:P1(J,"outputTokens"),cacheReadTokens:P1(J,"cacheReadTokens"),cacheWriteTokens:P1(J,"cacheWriteTokens"),cost:e3(J?.totalCost),totalInputTokens:P1(Q,"inputTokens"),totalOutputTokens:P1(Q,"outputTokens"),totalCacheReadTokens:P1(Q,"cacheReadTokens"),totalCacheWriteTokens:P1(Q,"cacheWriteTokens"),totalCost:e3(Q?.totalCost)},teamAgentId:typeof Z?.teamAgentId==="string"?Z.teamAgentId:void 0,teamRole:W}}function IN($){let J=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??J?.finishReason,Z=bN(Q)?Q:Q==="failed"?"error":"completed",W=hN($?.usage??J?.usage);return{type:"done",reason:Z,text:typeof $?.text==="string"?$.text:typeof J?.text==="string"?J.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof J?.iterations==="number"?J.iterations:0,usage:W}}function BZ($,J){return $.error?.message??`hub command failed: ${J}`}function FJ($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function qB($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof J?.agentId==="string"?J.agentId:void 0),parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,isSubagent:typeof J?.isSubagent==="boolean"?J.isSubagent:!1,source:typeof J?.source==="string"?J.source:D0.CORE,pid:typeof J?.pid==="number"?J.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:FJ($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:FJ($.status)==="completed"?0:FJ($.status)==="failed"?1:void 0,status:FJ($.status),interactive:J?.interactive===!0,provider:typeof J?.provider==="string"?J.provider:"hub",model:typeof J?.model==="string"?J.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof J?.teamName==="string"?J.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??J?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??J?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??J?.enableTeams===!0,prompt:typeof J?.prompt==="string"?J.prompt:void 0,metadata:J,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,hookPath:typeof J?.hookPath==="string"?J.hookPath:void 0}}function N1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;return J.version===1&&typeof J.sessionId==="string"?JSON.parse(JSON.stringify(J)):void 0}function xN($){let J=N1($?.snapshot);if(J)return AZ(J);let Q=$?.session;return Q?qB(Q):void 0}function _B($,J,Q){let Z=Q?.workspaceRoot?.trim()||J.config.workspaceRoot||J.config.cwd;return S0.parse({version:1,session_id:$,source:J.source??D0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:FJ(Q?.status),interactive:J.interactive===!0,provider:J.config.providerId,model:J.config.modelId,cwd:Q?.cwd?.trim()||J.config.cwd,workspace_root:Z,team_name:J.config.teamName,enable_tools:J.config.enableTools,enable_spawn:J.config.enableSpawnAgent,enable_teams:J.config.enableAgentTeams,prompt:J.prompt?.trim()||void 0,metadata:J.sessionMetadata&&Object.keys(J.sessionMetadata).length>0?J.sessionMetadata:void 0})}function MB($,J){return S0.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??J.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class p${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new VJ;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,J){this.clientContext=J,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd},this.defaultCapabilities=L0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new B$({...this.clientOptions,url:$})}async replaceClient($){let J=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(J.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!VZ($,"session.create"))return!1;let J=await HZ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!J)return!1;return await this.replaceClient(J),!0}registerPlannedSession($,J,Q){if(this.sessionCapabilities.set($,J),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let J=this.resolveCapabilities($),Q=TB($.localRuntime,J),Z=$.config.sessionId?.trim()||DB(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:g8({...$.config,sessionId:Z}),metadata:{...$.sessionMetadata??{},source:$.source??D0.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:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:g8($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Z,J,Q.handlers);let j;try{j=await W()}catch(V){if(this.cleanupPlannedSession(Z),await this.recoverLocalHubStartupDeadlock(V)){this.registerPlannedSession(Z,J,Q.handlers);try{j=await W()}catch(H){throw this.cleanupPlannedSession(Z),H}}else throw V}let f=N1(j.payload?.snapshot),X=j.payload?.session,Y=(f?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Z),Error("Hub runtime did not return a session id.");if(Y!==Z)this.cleanupPlannedSession(Z),this.registerPlannedSession(Y,J,Q.handlers);return{sessionId:Y,manifest:f?MB(f,$):_B(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let Z=$.start,W=Z?this.resolveCapabilities(Z):void 0,j=Z?TB(Z.localRuntime,W??{}):{manifest:[],handlers:new Map},f=Z?Z.config.sessionId?.trim()||DB():void 0;if(f&&W)this.sessionCapabilities.set(f,W);if(f&&j.handlers.size>0)this.sessionClientContributionHandlers.set(f,j.handlers),this.ensureSessionSubscription(f);let X;try{X=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.config.workspaceRoot?.trim()||Z.config.cwd,cwd:Z.config.cwd??$.cwd,sessionConfig:g8({...Z.config,sessionId:f}),metadata:{...Z.sessionMetadata??{},source:Z.source??D0.CORE,provider:Z.config.providerId,model:Z.config.modelId,enableTools:Z.config.enableTools,enableSpawn:Z.config.enableSpawnAgent,enableTeams:Z.config.enableAgentTeams,teamName:Z.config.teamName,prompt:Z.prompt,interactive:Z.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Z.localRuntime?.configExtensions?{configExtensions:Z.localRuntime.configExtensions}:{}},toolPolicies:g8(Z.toolPolicies)}:{}},J)}catch(K){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error(K)}let Y=N1(X.payload?.snapshot),V=X.payload?.session,H=(Y?.sessionId??V?.sessionId)?.trim();if(Q&&!H){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error("Hub checkpoint restore returned no session id")}if(H&&f&&H!==f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&j.handlers.size>0)this.sessionClientContributionHandlers.set(H,j.handlers);if(H)this.ensureSessionSubscription(H);let A=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,B=X.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:Y?MB(Y,Z??{}):_B(H,Z??{},V),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:A,checkpoint:B}}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 J=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(J.payload?.prompts)?J.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,updated:J.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,removed:J.payload?.removed===!0}}async getAccumulatedUsage($){let J=await this.client.command("session.get",{includeSnapshot:!0},$),Q=N1(J.payload?.snapshot);if(Q){let f=Q.usage?{...Q.usage}:void 0,X=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return f||X?{usage:f,aggregateUsage:X}:void 0}let Z=J.payload?.session,W=OB(Z?.usage),j=OB(Z?.aggregateUsage);return W||j?{usage:W,aggregateUsage:j}:void 0}async abort($,J){await this.client.command("run.abort",{sessionId:$,reason:zB(J)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,J]of this.sessionSubscriptions){J();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 J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(u$(Q))return;throw Q}return xN(J.payload)}async listSessions($=100){let J=await this.client.command("session.list",{limit:$}),Q=Array.isArray(J.payload?.snapshots)?J.payload.snapshots.flatMap((W)=>{let j=N1(W);return j?[AZ(j)]:[]}):[];if(Q.length>0)return Q;return(J.payload?.sessions??[]).map(qB)}async listSettings($){let J=await this.client.command("settings.list",RB($));if(!J.ok)throw Error(BZ(J,"settings.list"));return J.payload?.snapshot}async toggleSetting($){let J=await this.client.command("settings.toggle",RB($));if(!J.ok)throw Error(BZ(J,"settings.toggle"));return{snapshot:J.payload?.snapshot,changedTypes:Array.isArray(J.payload?.changedTypes)?J.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,J){let Q={...J.metadata??{}};if(typeof J.prompt==="string")Q.prompt=J.prompt;if(typeof J.title==="string")Q.title=J.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw FB(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(BZ(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:J,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(BZ(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,J){return this.events.subscribe($,J)}ensureSessionSubscription($){let J=$.trim();if(!J||this.sessionSubscriptions.has(J))return;let Q=this.client.subscribe((Z)=>{this.handleHubEvent(Z)},{sessionId:J});this.sessionSubscriptions.set(J,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let J=$.trim();if(!J)return;this.sessionSubscriptions.get(J)?.(),this.sessionSubscriptions.delete(J),this.agentDoneEmittedForCurrentRunBySession.delete(J)}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:IN($.payload)}})}handleHubEvent($){let J=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!J)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(J);let Q=N1($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,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 Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",Z=$.payload?.redacted===!0;if(!Q&&!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:Z}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:J,payload:$.payload});return}case"usage.updated":{let Q=kN($.payload);this.events.emit({type:"agent_event",payload:{sessionId:J,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:J,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"tool",toolCallId:Q,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 Q=N1($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:J,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:J,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=N1($.payload?.snapshot),Z=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:J,payload:{...$.payload,reason:Z}}),Q?.interactive===!0&&f0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:J,reason:Z,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,J,Q){try{FB(this.telemetry,{component:"core",operation:$,error:J,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let J=$.sessionId?.trim();if(!J)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let Z=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Z)return;let j=this.sessionClientContributionHandlers.get(J)?.get(W);if(!j){await this.client.command("capability.respond",{requestId:Z,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${J}.`},J).catch(()=>{});return}let f=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Z,X);let Y=(V)=>{this.client.command("capability.progress",{requestId:Z,payload:V},J).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let V=await j({payload:f,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!0,payload:V},J)}catch(V){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!1,error:V instanceof Error?V.message:String(V)},J)}finally{this.activeCapabilityAbortControllers.delete(Z)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let J=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!J)return;let Q=this.activeCapabilityAbortControllers.get(J);if(!Q)return;Q.abort(yN($.payload.error))}async handleApprovalRequested($){let J=$.sessionId?.trim();if(!J)return;let Q=this.sessionCapabilities.get(J)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let Z=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Z||!W||!j)return;let f=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=EN($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:J,toolCallId:W,toolName:j,toolInput:X});let Y=await Promise.resolve(Q({sessionId:J,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:J,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:j,input:X,policy:f})).catch((V)=>({approved:!1,reason:V instanceof Error?V.message:`Tool approval request failed: ${String(V)}`}));await this.client.command("approval.respond",{approvalId:Z,approved:Y.approved,reason:Y.reason},J).catch(()=>{})}}var NB={};w(NB,{RemoteRuntimeHost:()=>m8});class m8 extends p${constructor($){super({url:q1($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var wB={};w(wB,{SqliteSessionStore:()=>O$});import{existsSync as gN,mkdirSync as mN}from"node:fs";import{join as vN}from"node:path";import{asBool as DJ,asOptionalString as T$,asString as r$,ensureSessionSchema as cN,loadSqliteDb as uN,nowIso as KZ,toBoolInt as UJ}from"@sctg/cline-shared/db";import{resolveDbDataDir as dN}from"@sctg/cline-shared/storage";class O${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??dN()}init(){this.getRawDb()}ensureSessionsDir(){if(!gN(this.sessionsDirPath))mN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return vN(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=uN(this.sessionDbPath());return cN($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}create($){let J=KZ();this.run(`INSERT OR REPLACE INTO sessions (
512
512
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
package/dist/hub/index.js CHANGED
@@ -274,7 +274,7 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
274
274
  error = ?,
275
275
  scheduled_for = COALESCE(?, scheduled_for),
276
276
  updated_at = ?
277
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,J,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,J){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(J,D0(),$)}attachReportPathToRun($,J){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(J,D0(),$)}}function nJ($){return $?new Date($).getTime():void 0}function MD($){let J=$.metadata?{...$.metadata}:void 0;if(J)delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions;return J}function iJ($){let J=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof J?.__hubScheduleCwd==="string"?J.__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:nJ($.nextRunAt),lastRunAt:nJ($.lastRunAt),createdBy:typeof J?.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:J?.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0,metadata:MD($)}}function zD($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function _9($,J){return{executionId:$.runId,scheduleId:J,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:nJ($.startedAt),endedAt:nJ($.completedAt),status:zD($.status),errorMessage:$.error}}class u2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new _6({dbPath:$.dbPath}),this.materializer=new F6({store:this.store}),this.runner=new R6({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(R9($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return iJ(this.store.createHubSchedule($))}getSchedule($){let J=this.store.getHubSchedule($);return J?iJ(J):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((J)=>iJ(J))}updateSchedule($,J){if(J.cronPattern!==void 0)R9(J.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let Z=J.workspaceRoot!==void 0?J.workspaceRoot.trim():Q.workspaceRoot;if((J.enabled??Q.enabled)&&!Z)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...J,scheduleId:$});return j?iJ(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;await this.runner.tick();let Q=this.store.getRun(J.runId)??J;return _9(Q,$)}triggerScheduleNowDetached($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;return this.runner.tick().catch(()=>{return}),_9(J,$)}listScheduleExecutions($){let J=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:J?.specId,limit:$.limit};return this.store.listRuns(Q).map((W)=>{let j=J??this.store.getSpec(W.specId);if(!j||j.source!=="hub-schedule")return;return _9(W,j.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let J=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(J.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,Z=0,W=0,j;for(let f of J){if(f.status==="success"||f.status==="completed")Q+=1;if(!j&&f.status!=="success"&&f.status!=="completed")j=f;if(f.startedAt&&f.endedAt)W+=f.endedAt-f.startedAt,Z+=1}return{totalRuns:J.length,successRate:Q/J.length,avgDurationSeconds:Z>0?W/Z/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let J=this.store.getSpec($.specId);if(!J||J.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:J.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:J.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+J.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let J={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(J).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,Z)=>String(Q.nextRunAt).localeCompare(String(Z.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:Z})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:Z}))}}R5();import{createSessionId as BR,isHubProtocolCompatible as KR,resolveClineBuildEnv as GR,resolveHubCommandTimeoutMs as FR}from"@sctg/cline-shared";var xf={};w(xf,{splitCoreSessionConfig:()=>E6,isSessionNotFoundError:()=>I$,SessionNotFoundError:()=>k$,SESSION_NOT_FOUND_ERROR_CODE:()=>g1});var g1="session_not_found";class k$ extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function I$($){return $ instanceof k$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function E6($){let{hooks:J,logger:Q,telemetry:Z,extensionContext:W,extraTools:j,extensions:f,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:V,compaction:H,...A}=$,B={};if(J)B.hooks=J;if(Q)B.logger=Q;if(Z)B.telemetry=Z;if(W)B.extensionContext=W;if(j)B.extraTools=j;if(f)B.extensions=f;if(X)B.onTeamEvent=X;if(Y)B.onConsecutiveMistakeLimitReached=Y;if(V?.createCheckpoint)B.checkpoint=V;if(H?.compact)B.compaction=H;let K=Object.keys(B).length>0?B:void 0;return{config:{...A,...V?{checkpoint:{enabled:V.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...K?{localRuntime:K}:{}}}import{spawn as dU}from"node:child_process";import{closeSync as lU,mkdirSync as pU,openSync as rU}from"node:fs";import{basename as iU,dirname as nU,join as aU}from"node:path";import{fileURLToPath as sU}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as oU,isHubDaemonProcess as tf,isHubProtocolCompatible as tU,resolveClineBuildEnv as ef,withResolvedClineBuildEnv as eU}from"@sctg/cline-shared";import{createHash as LU,randomBytes as TU}from"node:crypto";import{existsSync as OU}from"node:fs";import{chmod as _U,mkdir as N9,readFile as uf,rm as w9,writeFile as df}from"node:fs/promises";import{dirname as lf,join as C9}from"node:path";import{resolveClineDataDir as m1,resolveClineDir as pf}from"@sctg/cline-shared/storage";var mf="3.89.2-beta.20260620150721";var b6={name:"@sctg/cline-core",description:"Cline Core SDK for Node Runtime",version:mf,repository:{type:"git",url:"https://github.com/TEA-ching/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:{"@sctg/cline-agents":"workspace:*","@sctg/cline-shared":"workspace:*","@sctg/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","markdown-docx":"^1.6.0",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 MU="CLINE_HUB_DISCOVERY_PATH",zU="CLINE_HUB_BUILD_ID",vf=30000,qU=15000,PU=100;function NU($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function wU($){return LU("sha256").update($).digest("hex").slice(0,12)}function CU($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function L5(){return TU(32).toString("hex")}function SU($){return new Promise((J)=>setTimeout(J,$))}function yU($){return`${$}.lock`}async function EU($){try{let J=JSON.parse(await uf(C9($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function cf($){await w9($,{recursive:!0,force:!0}).catch(()=>{return})}function T5(){return process.env[zU]?.trim()||String(b6.version)}function x$($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${wU($)}`,Q=process.env[MU]?.trim()||C9(m1(),"locks","hub","owners",`${NU(J)}.json`);return{ownerId:J,discoveryPath:Q}}function rf($=`hub-${Date.now().toString(36)}`){return x$($)}async function Y0($){try{let J=JSON.parse(await uf($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,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((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function O5($,J){await N9(lf($),{recursive:!0}),await w9($,{force:!0}).catch(()=>{return}),await df($,`${JSON.stringify(J,null,2)}
277
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,J,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,J){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(J,D0(),$)}attachReportPathToRun($,J){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(J,D0(),$)}}function nJ($){return $?new Date($).getTime():void 0}function MD($){let J=$.metadata?{...$.metadata}:void 0;if(J)delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions;return J}function iJ($){let J=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof J?.__hubScheduleCwd==="string"?J.__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:nJ($.nextRunAt),lastRunAt:nJ($.lastRunAt),createdBy:typeof J?.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:J?.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0,metadata:MD($)}}function zD($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function _9($,J){return{executionId:$.runId,scheduleId:J,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:nJ($.startedAt),endedAt:nJ($.completedAt),status:zD($.status),errorMessage:$.error}}class u2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new _6({dbPath:$.dbPath}),this.materializer=new F6({store:this.store}),this.runner=new R6({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(R9($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return iJ(this.store.createHubSchedule($))}getSchedule($){let J=this.store.getHubSchedule($);return J?iJ(J):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((J)=>iJ(J))}updateSchedule($,J){if(J.cronPattern!==void 0)R9(J.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let Z=J.workspaceRoot!==void 0?J.workspaceRoot.trim():Q.workspaceRoot;if((J.enabled??Q.enabled)&&!Z)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...J,scheduleId:$});return j?iJ(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;await this.runner.tick();let Q=this.store.getRun(J.runId)??J;return _9(Q,$)}triggerScheduleNowDetached($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;return this.runner.tick().catch(()=>{return}),_9(J,$)}listScheduleExecutions($){let J=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:J?.specId,limit:$.limit};return this.store.listRuns(Q).map((W)=>{let j=J??this.store.getSpec(W.specId);if(!j||j.source!=="hub-schedule")return;return _9(W,j.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let J=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(J.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,Z=0,W=0,j;for(let f of J){if(f.status==="success"||f.status==="completed")Q+=1;if(!j&&f.status!=="success"&&f.status!=="completed")j=f;if(f.startedAt&&f.endedAt)W+=f.endedAt-f.startedAt,Z+=1}return{totalRuns:J.length,successRate:Q/J.length,avgDurationSeconds:Z>0?W/Z/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let J=this.store.getSpec($.specId);if(!J||J.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:J.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:J.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+J.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let J={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(J).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,Z)=>String(Q.nextRunAt).localeCompare(String(Z.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:Z})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:Z}))}}R5();import{createSessionId as BR,isHubProtocolCompatible as KR,resolveClineBuildEnv as GR,resolveHubCommandTimeoutMs as FR}from"@sctg/cline-shared";var xf={};w(xf,{splitCoreSessionConfig:()=>E6,isSessionNotFoundError:()=>I$,SessionNotFoundError:()=>k$,SESSION_NOT_FOUND_ERROR_CODE:()=>g1});var g1="session_not_found";class k$ extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function I$($){return $ instanceof k$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function E6($){let{hooks:J,logger:Q,telemetry:Z,extensionContext:W,extraTools:j,extensions:f,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:V,compaction:H,...A}=$,B={};if(J)B.hooks=J;if(Q)B.logger=Q;if(Z)B.telemetry=Z;if(W)B.extensionContext=W;if(j)B.extraTools=j;if(f)B.extensions=f;if(X)B.onTeamEvent=X;if(Y)B.onConsecutiveMistakeLimitReached=Y;if(V?.createCheckpoint)B.checkpoint=V;if(H?.compact)B.compaction=H;let K=Object.keys(B).length>0?B:void 0;return{config:{...A,...V?{checkpoint:{enabled:V.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...K?{localRuntime:K}:{}}}import{spawn as dU}from"node:child_process";import{closeSync as lU,mkdirSync as pU,openSync as rU}from"node:fs";import{basename as iU,dirname as nU,join as aU}from"node:path";import{fileURLToPath as sU}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as oU,isHubDaemonProcess as tf,isHubProtocolCompatible as tU,resolveClineBuildEnv as ef,withResolvedClineBuildEnv as eU}from"@sctg/cline-shared";import{createHash as LU,randomBytes as TU}from"node:crypto";import{existsSync as OU}from"node:fs";import{chmod as _U,mkdir as N9,readFile as uf,rm as w9,writeFile as df}from"node:fs/promises";import{dirname as lf,join as C9}from"node:path";import{resolveClineDataDir as m1,resolveClineDir as pf}from"@sctg/cline-shared/storage";var mf="3.89.2-beta.20260620160351";var b6={name:"@sctg/cline-core",description:"Cline Core SDK for Node Runtime",version:mf,repository:{type:"git",url:"https://github.com/TEA-ching/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:{"@sctg/cline-agents":"workspace:*","@sctg/cline-shared":"workspace:*","@sctg/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","markdown-docx":"^1.6.0",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 MU="CLINE_HUB_DISCOVERY_PATH",zU="CLINE_HUB_BUILD_ID",vf=30000,qU=15000,PU=100;function NU($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function wU($){return LU("sha256").update($).digest("hex").slice(0,12)}function CU($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function L5(){return TU(32).toString("hex")}function SU($){return new Promise((J)=>setTimeout(J,$))}function yU($){return`${$}.lock`}async function EU($){try{let J=JSON.parse(await uf(C9($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function cf($){await w9($,{recursive:!0,force:!0}).catch(()=>{return})}function T5(){return process.env[zU]?.trim()||String(b6.version)}function x$($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${wU($)}`,Q=process.env[MU]?.trim()||C9(m1(),"locks","hub","owners",`${NU(J)}.json`);return{ownerId:J,discoveryPath:Q}}function rf($=`hub-${Date.now().toString(36)}`){return x$($)}async function Y0($){try{let J=JSON.parse(await uf($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,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((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function O5($,J){await N9(lf($),{recursive:!0}),await w9($,{force:!0}).catch(()=>{return}),await df($,`${JSON.stringify(J,null,2)}
278
278
  `,{encoding:"utf8",mode:384}),await _U($,384)}async function y0($){await w9($,{force:!0}).catch(()=>{return})}async function _5($,J){let Q=yU($);await N9(lf(Q),{recursive:!0});let Z=Date.now()+qU;while(!0)try{await N9(Q,{recursive:!1}),await df(C9(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
279
279
  `,"utf8");try{return await J()}finally{await cf(Q)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let f=await EU(Q),X=f?Date.now()-Date.parse(f.acquiredAt):vf+1;if(!f||!CU(f.pid)||X>vf){await cf(Q);continue}if(Date.now()>=Z)throw Error(`Timed out waiting for hub startup lock ${Q}`);await SU(PU)}}async function g$($,J){try{let Q=await fetch(J?.authToken?S9($):M5($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function Z$($,J,Q="/hub"){return new URL(`ws://${$}:${J}${Q}`).toString()}function M5($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function S9($){let J=new URL(M5($));return J.pathname="/status",J.toString()}function nf($){return OU($)}import{CLINE_HUB_DEV_PORT as bU,CLINE_HUB_PORT as hU,resolveClineBuildEnv as kU}from"@sctg/cline-shared";var IU="CLINE_HUB_HOST",xU="CLINE_HUB_PORT",gU="CLINE_HUB_PATHNAME",y9="127.0.0.1",E9=hU,b9="/hub";function af($){return kU($)==="development"?bU:E9}function h9($={}){return($.env??process.env)[IU]?.trim()||y9}function a2($={}){let Q=($.env??process.env)[xU]?.trim();if(!Q)return af($);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return af($);return Z}function k9($={}){return($.env??process.env)[gU]?.trim()||b9}function K$($={},J={}){return{host:$.host??h9(J),port:$.port??a2(J),pathname:$.pathname??k9(J)}}import{join as mU}from"node:path";var vU="shared:cline",cU="CLINE_HUB_DISCOVERY_PATH",uU="hub-production";function sf($){let J=N$($.trim());return x$(`workspace:${J||$.trim()}`)}function W$($=vU){return x$($)}function G$(){return{ownerId:uU,discoveryPath:process.env[cU]?.trim()||mU(m1(),"locks","hub","production.json")}}var $R=8000,JR=200,QR=3000,ZR=100,WR=[100,250,500,1000,2000],jR="--cline-hub-daemon";function fR($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function XR(){try{let $=aU(m1(),"logs","hub-daemon.log");return pU(nU($),{recursive:!0}),{fd:rU($,"a"),logPath:$}}catch{return}}function $X(){return ef()==="production"?G$():W$()}function v1($){return tU($).compatible}function of($,J,Q){if(!J||J.url!==Q)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function c1($,J){try{return await g$($,{authToken:J})}catch{return}}async function YR($,J){let Q=Date.now()+J;while(Date.now()<Q){if(!(await c1($))?.url)return!0;await new Promise((W)=>setTimeout(W,ZR))}return!1}async function z5($,J){if(await k6($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await YR($.url,QR);return await y0(J).catch(()=>{return}),Q}async function h6($,J){if(v1($))return!0;return z5($,J)}async function JX($){if(ef()!=="production")return;let J=W$();if(J.discoveryPath===$.discoveryPath)return;let Q=await Y0(J.discoveryPath);if(Q?.url)await z5(Q,J.discoveryPath);else await y0(J.discoveryPath).catch(()=>{return})}function VR(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return sU(new URL(`./entry.${$}`,import.meta.url))}function HR($,J){let Q=VR(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let W=iU(Z).toLowerCase().includes("bun"),j=Q.startsWith("/$bunfs/"),f=W&&Q.toLowerCase().endsWith(".ts"),X=j?[jR]:[...f?["--conditions=development"]:[],Q];return{launcher:Z,args:[...X,"--cwd",$,...fR(J)],cwd:$,env:{...eU(process.env),CLINE_NO_INTERACTIVE:"1",[oU]:"1"}}}function AR($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function I9($,J={}){if(tf())return;let Q=HR($,J),Z=XR();try{dU(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)lU(Z.fd)}}async function s2($,J={}){for(let Q=0;;Q++)try{I9($,J);return}catch(Z){let W=WR[Q];if(!AR(Z)||W===void 0)throw Z;await new Promise((j)=>setTimeout(j,W))}}function q5($,J={}){if(tf())return;let Q=$X(),Z=K$(J),W=Z$(Z.host,Z.port,Z.pathname),j=J.allowPortFallback===!0&&Z.port!==0;JX(Q).catch(()=>{return}).then(()=>Y0(Q.discoveryPath)).then(async(f)=>{let X=!1;if(f?.url)if(!f.authToken){if(X=!0,!await z5(f,Q.discoveryPath)&&!j)return}else{let H=await c1(f.url,f.authToken);if(H?.url&&v1(H)&&await F$(H.url,{authToken:f.authToken}))return;if(H?.url)await h6({...H,authToken:f.authToken},Q.discoveryPath);else await y0(Q.discoveryPath).catch(()=>{return})}let Y=await c1(W);if(Y?.url){if(v1(Y)){if(!j||!X)return}else if(!await h6({...Y,authToken:void 0},Q.discoveryPath)&&!j)return}let V=j?{...Z,port:0}:Z;await s2($,V)}).catch(()=>{})}async function QX($,J={}){let Q=$X(),Z=J.host!==void 0||J.port!==void 0||J.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=K$(J),j=Z$(W.host,W.port,W.pathname),f=(K)=>{if(!Z)Z1(K.url,K.authToken);return K};await JX(Q).catch(()=>{return});let X=await Y0(Q.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await z5(X,Q.discoveryPath);else{let G=await c1(X.url,K);if(G?.url&&v1(G)&&await F$(G.url,{authToken:K}))return f({url:G.url,authToken:K});if(G?.url)await h6({...G,authToken:K},Q.discoveryPath);else await y0(Q.discoveryPath).catch(()=>{return})}}let V=await c1(j);if(V?.url){let K=of(V,X,j);if(v1(V))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" 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 h6(K,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let A=J.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await s2($,A);let B=Date.now()+$R;while(Date.now()<B){let K=await Y0(Q.discoveryPath);if(K?.url&&K.authToken){let R=await c1(K.url,K.authToken);if(R?.url&&v1(R)&&await F$(R.url,{authToken:K.authToken}))return f({url:R.url,authToken:K.authToken})}let G=await c1(j);if(G?.url&&!v1(G)){let R=of(G,K,j);if(!await h6(R,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} 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,JR))}throw Error("Timed out waiting for detached hub startup.")}function P5(){return GR()==="production"?G$():W$()}function DR(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function XX($){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((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return XX($.data);return String($)}function UR($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function ZX($){let J=$,Q=UR(J.reason);return new q0("hub_connection_closed",J.code||Q?`Hub connection closed (code=${J.code??0}${Q?`, reason=${Q}`:""})`:x9,{closeCode:J.code,closeReason:Q||void 0})}function RR($,J){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 Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new q0("hub_connect_failed",Q);let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new q0("hub_connect_failed",Z?`Failed to connect to hub at ${J.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var LR=8000,TR=200,WX="*",jX=8000,OR="cline-hub-auth.",YX=new Map,VX=new Set,_R=3000,MR=3000,zR=100,x9="Hub connection closed",qR=250,PR=5000,fX=0.5;class q0 extends Error{code;details;constructor($,J,Q){super(J);this.code=$;this.details=Q;this.name="HubTransportError"}}function v9($){return $ instanceof q0}class o2 extends Error{command;code;constructor($,J,Q){super(Q);this.command=$;this.code=J;this.name="HubCommandError"}}function N5($,J){return $ instanceof o2&&$.code==="hub_command_timeout"&&(J===void 0||$.command===J)}function HX($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=c9($.toString());return Q?YX.get(Q):void 0}function NR($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function c9($){if(!NR($))return;let J=new URL(W1($));return J.search="",J.hash="",J.toString()}function g9($){let J=c9($);return!!J&&VX.has(J)}function Z1($,J){let Q=c9($);if(Q){if(VX.add(Q),J?.trim())YX.set(Q,J)}return $}class j${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",x9);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),J=this.options.authToken?.trim()||HX($);$.hash="";let Z=new(DR())($.toString(),J?[`${OR}${J}`]:void 0);this.socket=Z;let W=!1;this.connectPromise=new Promise((j,f)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,W=!0,this.lastCloseError=new q0("hub_connect_timeout",`Timed out connecting to hub after ${jX}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Z.close()}catch{}f(this.lastCloseError)},jX);Z.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),j()}),Z.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=RR(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)}),Z.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!W)this.lastCloseError=ZX(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)})}),Z.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(XX(j)))}),Z.addEventListener("close",(j)=>{if(this.socket!==Z)return;if(!W)this.lastCloseError=ZX(j),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await 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 j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,J){let Q=J?.sessionId?.trim()||void 0,Z={listener:$,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command($,J,Q,Z){let W=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Q,Z)}catch(f){if(!j||W>=1||!await this.recoverLocalHubTransport(f))throw f;W+=1}}async commandOnce($,J,Q,Z){await this.connect();let W=BR("hubreq_"),j=FR($,Z?.timeoutMs),f=new Promise((Y,V)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;V(new o2($,"hub_command_timeout",`Hub command ${$} timed out after ${j}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.`))},j);this.pendingReplies.set(W,{resolve:(A)=>{if(H)clearTimeout(H);Y(A)},reject:(A)=>{if(H)clearTimeout(H);V(A)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Q,timeoutMs:j,payload:J}})}catch(Y){throw this.pendingReplies.delete(W),Y}let X=await f;if(!X.ok){if(X.error?.code===g1){let Y=Q??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new k$(Y,X.error.message)}throw new o2($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!g9(this.currentUrl)||!v9($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await u1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,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(qR*2**this.reconnectAttempt,PR),J=Math.round($*(1-fX)+Math.random()*$*fX);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!g9(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await u1({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",x9),this.sawSocketClose=!1;for(let J of this.pendingReplies.values())J.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($,J){this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{}})}adjustSubscriptionCount($,J){let Q=this.subscriptionKeyForSessionId($),Z=(this.subscriptionCounts.get(Q)??0)+J;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,Z),J>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??WX}subscriptionSessionIdFromKey($){return $===WX?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Q=this.pendingReplies.get(J);if(!Q)return;this.pendingReplies.delete(J),Q.resolve($.envelope);return}case"event":for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$.envelope.sessionId?.trim())continue;J.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function W1($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function F$($,J){let Q=new j$({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function m9($,J){let Q=W1($),Z=await g$(Q,{authToken:J?.authToken});if(!Z)return{status:"unreachable",url:Q};if(!KR(Z).compatible)return{status:"protocol_mismatch",url:Q};if(J?.verifyConnection===!0&&!await F$(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function wR($){let J=Date.now()+LR;while(Date.now()<J){let Q=await Y0($.discoveryPath);if(Q?.url){let Z=await m9(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(Z.status==="compatible")return Z1(Z.url,Q.authToken)}await new Promise((Z)=>setTimeout(Z,TR))}return}async function CR($){let J=Date.now()+MR;while(Date.now()<J){if(!(await g$($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,zR))}return!1}function SR($,J){try{return W1($)===W1(J)}catch{return!1}}function yR($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let Z=Q;if(Z.status==="running"||Z.status==="idle"||Z.status==="pending")return!0;return Array.isArray(Z.participants)&&Z.participants.length>0})}async function ER($,J,Q){let Z=new j$({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let W=await Z.command("session.list",{limit:500},void 0,{timeoutMs:_R});return!yR(W.payload)}catch{return!1}finally{await Z.dispose().catch(()=>{return})}}async function I6($={}){if($.endpoint?.trim()){let W=await m9($.endpoint);return W.status==="compatible"?W.url:void 0}let J=P5(),Q=await Y0(J.discoveryPath);if(!Q?.url)return;let Z=await m9(Q.url,{authToken:Q.authToken});if(Z.status==="compatible")return Z1(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await y0(J.discoveryPath).catch(()=>{return});return}async function u1($={}){let J=await I6($);if(J&&await F$(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;let Q=P5();return await s2($.workspaceRoot??process.cwd()),await wR(Q)}async function k6($,J){let Q=new URL($),Z=J?.trim()||HX(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}async function u9($=P5()){let J=await Y0($.discoveryPath);if(!J?.url)return!1;try{if(await k6(J.url,J.authToken))return!0}catch{}return!1}async function w5($){if(!g9($.url))return;let J=P5(),Q=await Y0(J.discoveryPath);if(!Q?.url||!SR(Q.url,$.url))return;if(!await ER(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await u9())return;if(!await CR(Q.url))return;return await y0(J.discoveryPath).catch(()=>{return}),await u1({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as bR}from"@sctg/cline-shared";function hR($,J){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Q?`Failed to connect to hub at ${J} (${Q} event before socket open).`:`Failed to connect to hub at ${J}.`)}var kR="cline-hub-auth.";function IR($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function xR($,J){let Q=new URL($),Z=new URL(J);return Q.search="",Q.hash="",Z.search="",Z.hash="",Q.toString()===Z.toString()}function AX(){return bR()==="production"?G$():W$()}async function gR($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=AX(),Z=await Y0(Q.discoveryPath);if(Z?.url&&xR($.toString(),Z.url))return Z.authToken;return}async function d9($={}){let J=K$($);if(!IR($)){let Q=AX(),Z=await Y0(Q.discoveryPath);if(Z?.url)return Z.url}return Z$(J.host,J.port,J.pathname)}async function C5($){return await new Promise((J,Q)=>{(async()=>{let Z=new URL($),W=await gR(Z);Z.hash="";let j=new WebSocket(Z.toString(),W?[`${kR}${W}`]:void 0),f=new Map,X=0;j.addEventListener("open",()=>{J({send(Y){let V=Y.requestId??`hub-client-${++X}`;return new Promise((H,A)=>{f.set(V,{resolve:H,reject:A});let B={kind:"command",envelope:{...Y,requestId:V}};j.send(JSON.stringify(B))})},close(){j.close()}})}),j.addEventListener("message",(Y)=>{let V=JSON.parse(String(Y.data));if(V.kind==="reply"&&V.envelope.requestId){let H=f.get(V.envelope.requestId);if(H)f.delete(V.envelope.requestId),H.resolve(V.envelope)}}),j.addEventListener("close",()=>{for(let Y of f.values())Y.reject(Error("Hub connection closed"));f.clear()}),j.addEventListener("error",(Y)=>{Q(hR(Y,$))})})().catch(Q)})}async function BX($){try{return(await C5($)).close(),!0}catch{return!1}}async function KX($,J){let Q=await d9($),Z=await C5(Q);try{return await Z.send({version:J.version??"v1",clientId:J.clientId??"hub-client",...J})}finally{Z.close()}}function l9($){return $?JSON.parse(JSON.stringify($)):{}}function S5($){let J=$?.session&&typeof $.session==="object"?$.session:void 0;if(!J)return;let Q=J.metadata&&typeof J.metadata==="object"?l9(J.metadata):void 0;return{sessionId:typeof J.sessionId==="string"?J.sessionId:"",parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,metadata:Q}}function GX($,J){return $.error?.message??`hub command failed: ${J}`}function mR($){let J=l9($);if(typeof J.error==="string"&&J.error.trim())return{...J,error:J.error.trim()};let Q=J.result&&typeof J.result==="object"?J.result:void 0;if(typeof Q?.text==="string"&&Q.text.trim())return{...J,error:Q.text.trim()};let Z=Q?.error&&typeof Q.error==="object"?Q.error:void 0;if(typeof Z?.message==="string"&&Z.message.trim())return{...J,error:Z.message.trim()};return J}function FX($){let J=$?.sessionId;return typeof J==="string"&&J.trim()?J.trim():void 0}function vR($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))throw Error("hub checkpoint restore returned no checkpoint");let Q=J;if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Q}function cR($){let J=l9($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||FX(J)||"",eventType:"schedule.execution.completed",payload:J};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||FX(J)||"",eventType:"schedule.execution.failed",payload:J};let Q=$.sessionId?.trim();if(!Q)return;switch($.event){case"iteration.started":return{sessionId:Q,eventType:"runtime.chat.iteration_start",payload:J};case"iteration.finished":return{sessionId:Q,eventType:"runtime.chat.iteration_end",payload:J};case"assistant.delta":return{sessionId:Q,eventType:"runtime.chat.text_delta",payload:J};case"usage.updated":return{sessionId:Q,eventType:"runtime.chat.usage",payload:J};case"tool.started":return{sessionId:Q,eventType:"runtime.chat.tool_call_start",payload:J};case"tool.finished":return{sessionId:Q,eventType:"runtime.chat.tool_call_end",payload:J};case"approval.requested":return{sessionId:Q,eventType:"approval.requested",payload:J};case"run.aborted":return{sessionId:Q,eventType:"runtime.chat.aborted",payload:J};case"run.failed":return{sessionId:Q,eventType:"runtime.chat.failed",payload:mR($.payload)};case"run.completed":return{sessionId:Q,eventType:"runtime.chat.completed",payload:J};default:return}}class p9{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new j$({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 J=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}),Q=S5(J.payload);if(!Q?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Q.sessionId,startResult:{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}}}async sendRuntimeSession($,J,Q){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:J.prompt,mode:J.config.mode,attachments:J.attachments,delivery:J.delivery,timeoutSeconds:J.config.timeoutSeconds},$,Q)).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 J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(I$(Q))return;throw Q}return S5(J.payload)}async readMessages($){let J=$.trim();if(!J)return[];await this.ensureMetadataApplied();let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw Error(GX(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async restore($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Z=$.config,W=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,sessionConfig:{providerId:Z.provider,modelId:Z.model,apiKey:Z.apiKey,cwd:Z.cwd??Z.workspaceRoot,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Z.mode??"act",rules:Z.rules,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},metadata:{source:Z.source??"cli",provider:Z.provider,model:Z.model,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,prompt:void 0,interactive:Z.interactive!==!1},runtimeOptions:{mode:Z.mode,systemPrompt:Z.systemPrompt,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,autoApproveTools:Z.autoApproveTools,configExtensions:Z.configExtensions},modelSelection:{provider:Z.provider,model:Z.model,apiKey:Z.apiKey},toolPolicies:Z.toolPolicies}:{}},J);if(!W.ok)throw Error(GX(W,"session.restore"));let j=S5(W.payload);if(Q&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let f=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,X=vR(W.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...f?{messages:f}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let J=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(J.payload?.sessions)?J.payload?.sessions:[]).map((Z)=>S5({session:Z})).filter((Z)=>Boolean(Z?.sessionId))}async deleteSession($,J=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:J})).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($,J){let Q=new Set(($.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),Z=this.client.subscribe((W)=>{let j=cR(W);if(!j)return;if(Q.size>0&&!Q.has(j.sessionId))return;J.onEvent?.(j)});return this.ensureMetadataApplied().catch((W)=>{J.onError?.(W instanceof Error?W:Error(String(W)))}),Z}streamTeamProgress($,J){let Q=this.client.subscribe((Z)=>{if(Z.event!=="team.progress"||!Z.payload)return;J.onProjection?.(Z.payload)});return this.ensureMetadataApplied().catch((Z)=>{J.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list");return Array.isArray(J.payload?.schedules)?J.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,J){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...J})).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($,J){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list_executions",{scheduleId:$,limit:J});return Array.isArray(Q.payload?.executions)?Q.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 J=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(J.payload?.upcoming)?J.payload?.upcoming:[]}}class r9{client;constructor($){this.client=new j$({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 J=await this.client.command("session.list",{limit:$});return Array.isArray(J.payload?.sessions)?J.payload.sessions:[]}subscribeUI($){return this.client.subscribe((J)=>{switch(J.event){case"ui.notify":$.onNotify?.(J.payload);break;case"ui.show_window":$.onShowWindow?.(J.payload);break;case"hub.client.registered":$.onClientRegistered?.(J.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(J.payload??{});break;case"session.created":$.onSessionCreated?.(J.payload??{});break;case"session.updated":$.onSessionUpdated?.(J.payload??{});break;case"session.detached":$.onSessionDetached?.(J.payload??{});break}})}}import{normalizeProviderId as bb}from"@sctg/cline-llms";var SG={};w(SG,{LocalRuntimeHost:()=>z$});import{readdirSync as zb}from"node:fs";import{homedir as qb}from"node:os";import{isAbsolute as Pb,join as gj,resolve as mj}from"node:path";import{captureSdkError as E2,createSessionId as Nb,isLikelyAuthError as wb,normalizeUserInput as Cb}from"@sctg/cline-shared";import{setHomeDirIfUnset as Sb}from"@sctg/cline-shared/storage";var lX={};w(lX,{saveProviderOAuthCredentials:()=>p1,resolveProviderApiKeyFromSettings:()=>W7,loginAndSaveProviderOAuthCredentials:()=>l6,isOAuthProvider:()=>l1,getProviderOAuthCredentialsFromSettings:()=>p6,getProviderAuthStorageId:()=>Z7,getProviderAuthHandler:()=>W0,getPersistedProviderApiKey:()=>Z8,formatProviderOAuthApiKey:()=>j7});import{getClineEnvironmentConfig as uX}from"@sctg/cline-shared";M0();var qX={};w(qX,{startClineDeviceAuth:()=>t9,refreshClineToken:()=>h5,loginClineOAuth:()=>x6,getValidClineCredentials:()=>g6,completeClineDeviceAuth:()=>e9});import{getClineEnvironmentConfig as i9}from"@sctg/cline-shared";var DX={};w(DX,{startLocalOAuthServer:()=>f$});function uR(){let $;return{promise:new Promise((Q)=>{$=Q}),resolve:$}}async function f$($){let J=await import("node:http"),Q=$.host??"127.0.0.1",Z=$.timeoutMs??300000,W=$.successHtml??dR,j=uR(),f=!1,X=null,Y=null,V=null,H=(K)=>{if(f)return;f=!0,j.resolve(K)},A=()=>{if(X)clearTimeout(X),X=null;let K=V;if(V=null,Y)Y.close(),Y=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:Q,port:K})).catch(()=>{})},B=async()=>{return X=setTimeout(()=>{A(),H(null)},Z),j.promise};for(let K of $.ports){let G=J.createServer((U,L)=>{try{let D=new URL(U.url||"",`http://${Q}:${K}`);if(D.pathname!==$.callbackPath){L.statusCode=404,L.end("Not found");return}let O={url:D,code:D.searchParams.get("code")??void 0,state:D.searchParams.get("state")??void 0,provider:D.searchParams.get("provider")??void 0,error:D.searchParams.get("error")??void 0};if(O.error){L.statusCode=400,L.end(`Authentication failed: ${O.error}`),A(),H(O);return}if(!O.code){L.statusCode=400,L.end("Missing authorization code");return}if($.expectedState&&O.state!==$.expectedState){L.statusCode=400,L.end("State mismatch");return}L.statusCode=200,L.setHeader("Content-Type","text/html; charset=utf-8"),L.end(W),A(),H(O)}catch{L.statusCode=500,L.end("Internal error")}}),R=await new Promise((U)=>{let L=(D)=>{G.off("error",L),U({bound:!1,error:D})};G.once("error",L),G.listen(K,Q,()=>{G.off("error",L),Y=G,U({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw A(),R.error}if(R.bound){V=K;let U=`http://${Q}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Q,port:K,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:B,cancelWait:()=>{A(),H(null)},close:()=>{A(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var dR=`<!DOCTYPE html>
280
280
  <html lang="en">
package/dist/index.js CHANGED
@@ -463,7 +463,7 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
463
463
  `)[0]?.trim())}function v$($){if(!$)return;let J={...$},Q=N1(typeof J.title==="string"?J.title:void 0);if(Q)J.title=Q;else delete J.title;return Object.keys(J).length>0?J:void 0}function u8($){let J=v$($.metadata)??{},Q=$.title!==void 0?N1($.title):j9($.prompt);if(Q)J.title=Q;return Object.keys(J).length>0?J:void 0}function f9($){let J=v8($);if(J)return{agent:"teammate",sessionId:J.rootSessionId,taskType:"team"};let Q=QJ($);if(Q)return{agent:"subagent",sessionId:Q.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function X9($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:ZJ($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function VY($,J,Q){pO(iO($),{recursive:!0}),rO($,`${JSON.stringify(X9({updatedAt:J,context:Q,messages:[]}),null,2)}
464
464
  `,"utf8")}function HY($,J){return N0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:J?.endedAt??$.endedAt??void 0,exit_code:J?.exitCode??$.exitCode??void 0,status:J?.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:J?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function AY($,J,Q){let Z=0;while(!0){let W=await $();if(W===void 0)return{updated:!1};let j=await J(W);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Z+=1,Z>=Q)return j;continue}return j}}import{existsSync as oO}from"node:fs";import{readFile as tO}from"node:fs/promises";import{formatDisplayUserInput as BY}from"@sctg/cline-shared";class d8{listeners=new Set;subscribe($,J){let Q={listener:$,sessionId:J?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let J=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J)continue;Q.listener($)}}get size(){return this.listeners.size}}async function c$($){let J=$?.trim();if(!J||!oO(J))return[];try{let Q=(await tO(J,"utf8")).trim();if(!Q)return[];let Z=JSON.parse(Q);if(Array.isArray(Z))return KY(Z);if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let W=Z.messages;if(Array.isArray(W))return KY(W)}return[]}catch{return[]}}function eO($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:BY($.content)};return{...$,content:$.content.map((J)=>{if(J.type!=="text"||typeof J.text!=="string")return J;return{...J,text:BY(J.text)}})}}function KY($){return $.map(eO)}function Y9($){return $?{...$}:void 0}async function GY($,J){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await J.queueSpawnRequest($);let Z=await J.upsertSubagentSessionFromHook($);if(!Z)return;await J.appendSubagentHookAudit(Z,$),await J.applySubagentStatus(Z,$)}function l8($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function v0($){let J=l8($);if(!J)return;return J.toLowerCase()==="unknown"?void 0:J}function jJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Z_($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function H9($){let J=$??200;return Number.isFinite(J)?Math.max(0,Math.floor(J)):200}function W_($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function j_($){return $.isSubagent!==!0&&!l8($.parentSessionId)}function f_($){let J=$.match(/\d{13,}/g);if(!J||J.length===0)return 0;let Q=0;for(let Z of J){let W=Number.parseInt(Z,10);if(Number.isFinite(W)&&W>Q)Q=W}return Q}function A9($){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 X_($){let J=H9($);if(J===0)return[];let Q=RY(),W=(await $_(Q,{withFileTypes:!0}).catch(()=>[])).filter((f)=>f.isDirectory()).map((f)=>({entry:f,recency:f_(f.name.trim())})).sort((f,X)=>X.recency-f.recency||X.entry.name.localeCompare(f.entry.name));return(await Promise.all(W.map(async({entry:f})=>{let X=f.name.trim();if(!X)return;let Y=UY(Q,X,`${X}.json`),V=await DY(Y,"utf8").catch(()=>{return});if(!V)return;let H;try{H=JSON.parse(V)}catch{return}let A=N0.safeParse(H);if(!A.success)return;return A9(A.data)}))).filter((f)=>Boolean(f)).sort((f,X)=>X.startedAt.localeCompare(f.startedAt)).slice(0,J)}async function Y_($,J,Q){let Z=H9(J);if(Z===0)return await $.listSessions(0),[];let W=Q.includeSubagents?Z:W_(Z),j=await $.listSessions(W);return(Q.includeSubagents?j:j.filter(j_)).slice(0,Z)}function V_($){if(typeof $==="string")return $.trim();let J=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let Z=Q;if(Z.type!=="text")continue;let W=Z.text?.trim();if(W)J.push(W)}return J.join(`
465
465
  `).trim()}function FY($){return $.replace(/\s+/g," ").trim()}function H_($,J){if($.length<=J)return $;return`${$.slice(0,Math.max(0,J-3)).trimEnd()}...`}function A_($){for(let J of["user","assistant"])for(let Q of $){if(Q.role!==J)continue;let Z=FY(V_(Q.content));if(!Z)continue;let W=J==="user"?FY(J_(Z)):Z,j=Q_(W.split(`
466
- `)[0]??W);return H_(j,50)}return}function B_($){let J=0;for(let Q of $)J+=jJ(Q.metrics?.cost)??0;return J}function K_($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=v0(W.modelInfo?.provider);if(!Q)Q=v0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function G_($){return v0($?.provider)??v0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function F_($){return v0($?.model)??v0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function V9($,J){let Q=Z_($.metadata),Z=l8(J?.title)??l8(Q?.title),W=jJ(J?.totalCost)??jJ(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:v0(J?.provider)??v0($.provider)??G_(Q)??"",model:v0(J?.model)??v0($.model)??F_(Q)??"",metadata:j}}function D_($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function U_($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!D_(Q)}async function R_($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return U_(Q,Z)?{...Q,status:"idle"}:Q}))}async function L_($,J){return await Promise.all(J.map(async(Q)=>{let Z=V9(Q),W=Boolean(l8(Z.metadata?.title)),j=Boolean(v0(Z.provider)),f=Boolean(v0(Z.model)),X=jJ(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=K_(V),A=B_(V);return V9(Q,{title:W?void 0:A_(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||A<=0?void 0:A})}))}async function B9($,J={}){let Q=H9(J.limit),Z=J.includeSubagents===!0,W=await Y_($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await X_(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await R_($,X);if(J.hydrate===!1)return Y.map((V)=>V9(V));return await L_($,Y)}async function T_($){let J=$.trim();if(!J)return;let Q=UY(RY(),J,`${J}.json`),Z=await DY(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=N0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function O_($,J={}){let Q=new Map;return await B9({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map(c8)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await T_(W);return await c$(j)}},J)}import{captureSdkError as eH}from"@sctg/cline-shared";import{createSessionId as _M,isHubProtocolCompatible as MM,resolveClineBuildEnv as zM,resolveHubCommandTimeoutMs as qM}from"@sctg/cline-shared";import{spawn as t_}from"node:child_process";import{closeSync as e_,mkdirSync as $M,openSync as JM}from"node:fs";import{basename as QM,dirname as ZM,join as WM}from"node:path";import{fileURLToPath as jM}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fM,isHubDaemonProcess as bY,isHubProtocolCompatible as XM,resolveClineBuildEnv as hY,withResolvedClineBuildEnv as YM}from"@sctg/cline-shared";import{createHash as __,randomBytes as M_}from"node:crypto";import{existsSync as z_}from"node:fs";import{chmod as q_,mkdir as K9,readFile as MY,rm as G9,writeFile as zY}from"node:fs/promises";import{dirname as qY,join as F9}from"node:path";import{resolveClineDataDir as r8,resolveClineDir as lm}from"@sctg/cline-shared/storage";var TY="3.89.2-beta.20260620150721";var p8={name:"@sctg/cline-core",description:"Cline Core SDK for Node Runtime",version:TY,repository:{type:"git",url:"https://github.com/TEA-ching/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:{"@sctg/cline-agents":"workspace:*","@sctg/cline-shared":"workspace:*","@sctg/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","markdown-docx":"^1.6.0",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 P_="CLINE_HUB_DISCOVERY_PATH",N_="CLINE_HUB_BUILD_ID",OY=30000,w_=15000,C_=100;function S_($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function y_($){return __("sha256").update($).digest("hex").slice(0,12)}function E_($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function PY(){return M_(32).toString("hex")}function b_($){return new Promise((J)=>setTimeout(J,$))}function h_($){return`${$}.lock`}async function k_($){try{let J=JSON.parse(await MY(F9($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function _Y($){await G9($,{recursive:!0,force:!0}).catch(()=>{return})}function NY(){return process.env[N_]?.trim()||String(p8.version)}function w1($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${y_($)}`,Q=process.env[P_]?.trim()||F9(r8(),"locks","hub","owners",`${S_(J)}.json`);return{ownerId:J,discoveryPath:Q}}function rm($=`hub-${Date.now().toString(36)}`){return w1($)}async function B0($){try{let J=JSON.parse(await MY($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,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((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function wY($,J){await K9(qY($),{recursive:!0}),await G9($,{force:!0}).catch(()=>{return}),await zY($,`${JSON.stringify(J,null,2)}
466
+ `)[0]??W);return H_(j,50)}return}function B_($){let J=0;for(let Q of $)J+=jJ(Q.metrics?.cost)??0;return J}function K_($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=v0(W.modelInfo?.provider);if(!Q)Q=v0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function G_($){return v0($?.provider)??v0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function F_($){return v0($?.model)??v0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function V9($,J){let Q=Z_($.metadata),Z=l8(J?.title)??l8(Q?.title),W=jJ(J?.totalCost)??jJ(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:v0(J?.provider)??v0($.provider)??G_(Q)??"",model:v0(J?.model)??v0($.model)??F_(Q)??"",metadata:j}}function D_($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function U_($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!D_(Q)}async function R_($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return U_(Q,Z)?{...Q,status:"idle"}:Q}))}async function L_($,J){return await Promise.all(J.map(async(Q)=>{let Z=V9(Q),W=Boolean(l8(Z.metadata?.title)),j=Boolean(v0(Z.provider)),f=Boolean(v0(Z.model)),X=jJ(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=K_(V),A=B_(V);return V9(Q,{title:W?void 0:A_(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||A<=0?void 0:A})}))}async function B9($,J={}){let Q=H9(J.limit),Z=J.includeSubagents===!0,W=await Y_($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await X_(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await R_($,X);if(J.hydrate===!1)return Y.map((V)=>V9(V));return await L_($,Y)}async function T_($){let J=$.trim();if(!J)return;let Q=UY(RY(),J,`${J}.json`),Z=await DY(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=N0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function O_($,J={}){let Q=new Map;return await B9({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map(c8)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await T_(W);return await c$(j)}},J)}import{captureSdkError as eH}from"@sctg/cline-shared";import{createSessionId as _M,isHubProtocolCompatible as MM,resolveClineBuildEnv as zM,resolveHubCommandTimeoutMs as qM}from"@sctg/cline-shared";import{spawn as t_}from"node:child_process";import{closeSync as e_,mkdirSync as $M,openSync as JM}from"node:fs";import{basename as QM,dirname as ZM,join as WM}from"node:path";import{fileURLToPath as jM}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as fM,isHubDaemonProcess as bY,isHubProtocolCompatible as XM,resolveClineBuildEnv as hY,withResolvedClineBuildEnv as YM}from"@sctg/cline-shared";import{createHash as __,randomBytes as M_}from"node:crypto";import{existsSync as z_}from"node:fs";import{chmod as q_,mkdir as K9,readFile as MY,rm as G9,writeFile as zY}from"node:fs/promises";import{dirname as qY,join as F9}from"node:path";import{resolveClineDataDir as r8,resolveClineDir as lm}from"@sctg/cline-shared/storage";var TY="3.89.2-beta.20260620160351";var p8={name:"@sctg/cline-core",description:"Cline Core SDK for Node Runtime",version:TY,repository:{type:"git",url:"https://github.com/TEA-ching/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:{"@sctg/cline-agents":"workspace:*","@sctg/cline-shared":"workspace:*","@sctg/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","markdown-docx":"^1.6.0",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 P_="CLINE_HUB_DISCOVERY_PATH",N_="CLINE_HUB_BUILD_ID",OY=30000,w_=15000,C_=100;function S_($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function y_($){return __("sha256").update($).digest("hex").slice(0,12)}function E_($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function PY(){return M_(32).toString("hex")}function b_($){return new Promise((J)=>setTimeout(J,$))}function h_($){return`${$}.lock`}async function k_($){try{let J=JSON.parse(await MY(F9($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function _Y($){await G9($,{recursive:!0,force:!0}).catch(()=>{return})}function NY(){return process.env[N_]?.trim()||String(p8.version)}function w1($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${y_($)}`,Q=process.env[P_]?.trim()||F9(r8(),"locks","hub","owners",`${S_(J)}.json`);return{ownerId:J,discoveryPath:Q}}function rm($=`hub-${Date.now().toString(36)}`){return w1($)}async function B0($){try{let J=JSON.parse(await MY($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,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((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function wY($,J){await K9(qY($),{recursive:!0}),await G9($,{force:!0}).catch(()=>{return}),await zY($,`${JSON.stringify(J,null,2)}
467
467
  `,{encoding:"utf8",mode:384}),await q_($,384)}async function $$($){await G9($,{force:!0}).catch(()=>{return})}async function CY($,J){let Q=h_($);await K9(qY(Q),{recursive:!0});let Z=Date.now()+w_;while(!0)try{await K9(Q,{recursive:!1}),await zY(F9(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
468
468
  `,"utf8");try{return await J()}finally{await _Y(Q)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let f=await k_(Q),X=f?Date.now()-Date.parse(f.acquiredAt):OY+1;if(!f||!E_(f.pid)||X>OY){await _Y(Q);continue}if(Date.now()>=Z)throw Error(`Timed out waiting for hub startup lock ${Q}`);await b_(C_)}}async function C1($,J){try{let Q=await fetch(J?.authToken?I_($):SY($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function G$($,J,Q="/hub"){return new URL(`ws://${$}:${J}${Q}`).toString()}function SY($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function I_($){let J=new URL(SY($));return J.pathname="/status",J.toString()}function im($){return z_($)}import{CLINE_HUB_DEV_PORT as x_,CLINE_HUB_PORT as g_,resolveClineBuildEnv as m_}from"@sctg/cline-shared";var v_="CLINE_HUB_HOST",c_="CLINE_HUB_PORT",u_="CLINE_HUB_PATHNAME",d_="127.0.0.1",l_=g_,p_="/hub";function yY($){return m_($)==="development"?x_:l_}function r_($={}){return($.env??process.env)[v_]?.trim()||d_}function fJ($={}){let Q=($.env??process.env)[c_]?.trim();if(!Q)return yY($);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return yY($);return Z}function i_($={}){return($.env??process.env)[u_]?.trim()||p_}function u$($={},J={}){return{host:$.host??r_(J),port:$.port??fJ(J),pathname:$.pathname??i_(J)}}import{join as n_}from"node:path";var a_="shared:cline",s_="CLINE_HUB_DISCOVERY_PATH",o_="hub-production";function $v($){let J=M1($.trim());return w1(`workspace:${J||$.trim()}`)}function F$($=a_){return w1($)}function d$(){return{ownerId:o_,discoveryPath:process.env[s_]?.trim()||n_(r8(),"locks","hub","production.json")}}var VM=8000,HM=200,AM=3000,BM=100,KM=[100,250,500,1000,2000],GM="--cline-hub-daemon";function FM($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function DM(){try{let $=WM(r8(),"logs","hub-daemon.log");return $M(ZM($),{recursive:!0}),{fd:JM($,"a"),logPath:$}}catch{return}}function kY(){return hY()==="production"?d$():F$()}function S1($){return XM($).compatible}function EY($,J,Q){if(!J||J.url!==Q)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function y1($,J){try{return await C1($,{authToken:J})}catch{return}}async function UM($,J){let Q=Date.now()+J;while(Date.now()<Q){if(!(await y1($))?.url)return!0;await new Promise((W)=>setTimeout(W,BM))}return!1}async function XJ($,J){if(await D9($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await UM($.url,AM);return await $$(J).catch(()=>{return}),Q}async function i8($,J){if(S1($))return!0;return XJ($,J)}async function IY($){if(hY()!=="production")return;let J=F$();if(J.discoveryPath===$.discoveryPath)return;let Q=await B0(J.discoveryPath);if(Q?.url)await XJ(Q,J.discoveryPath);else await $$(J.discoveryPath).catch(()=>{return})}function RM(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return jM(new URL(`./entry.${$}`,import.meta.url))}function LM($,J){let Q=RM(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let W=QM(Z).toLowerCase().includes("bun"),j=Q.startsWith("/$bunfs/"),f=W&&Q.toLowerCase().endsWith(".ts"),X=j?[GM]:[...f?["--conditions=development"]:[],Q];return{launcher:Z,args:[...X,"--cwd",$,...FM(J)],cwd:$,env:{...YM(process.env),CLINE_NO_INTERACTIVE:"1",[fM]:"1"}}}function TM($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function OM($,J={}){if(bY())return;let Q=LM($,J),Z=DM();try{t_(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)e_(Z.fd)}}async function YJ($,J={}){for(let Q=0;;Q++)try{OM($,J);return}catch(Z){let W=KM[Q];if(!TM(Z)||W===void 0)throw Z;await new Promise((j)=>setTimeout(j,W))}}function xY($,J={}){if(bY())return;let Q=kY(),Z=u$(J),W=G$(Z.host,Z.port,Z.pathname),j=J.allowPortFallback===!0&&Z.port!==0;IY(Q).catch(()=>{return}).then(()=>B0(Q.discoveryPath)).then(async(f)=>{let X=!1;if(f?.url)if(!f.authToken){if(X=!0,!await XJ(f,Q.discoveryPath)&&!j)return}else{let H=await y1(f.url,f.authToken);if(H?.url&&S1(H)&&await l$(H.url,{authToken:f.authToken}))return;if(H?.url)await i8({...H,authToken:f.authToken},Q.discoveryPath);else await $$(Q.discoveryPath).catch(()=>{return})}let Y=await y1(W);if(Y?.url){if(S1(Y)){if(!j||!X)return}else if(!await i8({...Y,authToken:void 0},Q.discoveryPath)&&!j)return}let V=j?{...Z,port:0}:Z;await YJ($,V)}).catch(()=>{})}async function Av($,J={}){let Q=kY(),Z=J.host!==void 0||J.port!==void 0||J.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=u$(J),j=G$(W.host,W.port,W.pathname),f=(K)=>{if(!Z)z2(K.url,K.authToken);return K};await IY(Q).catch(()=>{return});let X=await B0(Q.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await XJ(X,Q.discoveryPath);else{let G=await y1(X.url,K);if(G?.url&&S1(G)&&await l$(G.url,{authToken:K}))return f({url:G.url,authToken:K});if(G?.url)await i8({...G,authToken:K},Q.discoveryPath);else await $$(Q.discoveryPath).catch(()=>{return})}}let V=await y1(j);if(V?.url){let K=EY(V,X,j);if(S1(V))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" 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 i8(K,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let A=J.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await YJ($,A);let B=Date.now()+VM;while(Date.now()<B){let K=await B0(Q.discoveryPath);if(K?.url&&K.authToken){let R=await y1(K.url,K.authToken);if(R?.url&&S1(R)&&await l$(R.url,{authToken:K.authToken}))return f({url:R.url,authToken:K.authToken})}let G=await y1(j);if(G?.url&&!S1(G)){let R=EY(G,K,j);if(!await i8(R,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} 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,HM))}throw Error("Timed out waiting for detached hub startup.")}function HJ(){return zM()==="production"?d$():F$()}function PM(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function uY($){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((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return uY($.data);return String($)}function NM($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function gY($){let J=$,Q=NM(J.reason);return new c0("hub_connection_closed",J.code||Q?`Hub connection closed (code=${J.code??0}${Q?`, reason=${Q}`:""})`:U9,{closeCode:J.code,closeReason:Q||void 0})}function wM($,J){if($ instanceof c0)return $;if($ instanceof Error)return new c0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new c0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new c0("hub_connect_failed",Q);let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new c0("hub_connect_failed",Z?`Failed to connect to hub at ${J.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var CM=8000,SM=200,mY="*",vY=8000,yM="cline-hub-auth.",dY=new Map,lY=new Set,EM=3000,bM=3000,hM=100,U9="Hub connection closed",kM=250,IM=5000,cY=0.5;class c0 extends Error{code;details;constructor($,J,Q){super(J);this.code=$;this.details=Q;this.name="HubTransportError"}}function xM($){return $ instanceof c0}class VJ extends Error{command;code;constructor($,J,Q){super(Q);this.command=$;this.code=J;this.name="HubCommandError"}}function pY($,J){return $ instanceof VJ&&$.code==="hub_command_timeout"&&(J===void 0||$.command===J)}function rY($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=T9($.toString());return Q?dY.get(Q):void 0}function gM($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function T9($){if(!gM($))return;let J=new URL(q2($));return J.search="",J.hash="",J.toString()}function R9($){let J=T9($);return!!J&&lY.has(J)}function z2($,J){let Q=T9($);if(Q){if(lY.add(Q),J?.trim())dY.set(Q,J)}return $}class D${options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new c0("hub_connection_closed",U9);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),J=this.options.authToken?.trim()||rY($);$.hash="";let Z=new(PM())($.toString(),J?[`${yM}${J}`]:void 0);this.socket=Z;let W=!1;this.connectPromise=new Promise((j,f)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,W=!0,this.lastCloseError=new c0("hub_connect_timeout",`Timed out connecting to hub after ${vY}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Z.close()}catch{}f(this.lastCloseError)},vY);Z.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),j()}),Z.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=wM(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)}),Z.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!W)this.lastCloseError=gY(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)})}),Z.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(uY(j)))}),Z.addEventListener("close",(j)=>{if(this.socket!==Z)return;if(!W)this.lastCloseError=gY(j),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await 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 j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,J){let Q=J?.sessionId?.trim()||void 0,Z={listener:$,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command($,J,Q,Z){let W=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Q,Z)}catch(f){if(!j||W>=1||!await this.recoverLocalHubTransport(f))throw f;W+=1}}async commandOnce($,J,Q,Z){await this.connect();let W=_M("hubreq_"),j=qM($,Z?.timeoutMs),f=new Promise((Y,V)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;V(new VJ($,"hub_command_timeout",`Hub command ${$} timed out after ${j}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.`))},j);this.pendingReplies.set(W,{resolve:(A)=>{if(H)clearTimeout(H);Y(A)},reject:(A)=>{if(H)clearTimeout(H);V(A)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Q,timeoutMs:j,payload:J}})}catch(Y){throw this.pendingReplies.delete(W),Y}let X=await f;if(!X.ok){if(X.error?.code===S8){let Y=Q??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new O1(Y,X.error.message)}throw new VJ($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!R9(this.currentUrl)||!xM($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await n8({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,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(kM*2**this.reconnectAttempt,IM),J=Math.round($*(1-cY)+Math.random()*$*cY);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!R9(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await n8({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 c0("hub_connection_closed",U9),this.sawSocketClose=!1;for(let J of this.pendingReplies.values())J.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 c0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{}})}adjustSubscriptionCount($,J){let Q=this.subscriptionKeyForSessionId($),Z=(this.subscriptionCounts.get(Q)??0)+J;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,Z),J>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??mY}subscriptionSessionIdFromKey($){return $===mY?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Q=this.pendingReplies.get(J);if(!Q)return;this.pendingReplies.delete(J),Q.resolve($.envelope);return}case"event":for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$.envelope.sessionId?.trim())continue;J.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function q2($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function l$($,J){let Q=new D$({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function L9($,J){let Q=q2($),Z=await C1(Q,{authToken:J?.authToken});if(!Z)return{status:"unreachable",url:Q};if(!MM(Z).compatible)return{status:"protocol_mismatch",url:Q};if(J?.verifyConnection===!0&&!await l$(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function mM($){let J=Date.now()+CM;while(Date.now()<J){let Q=await B0($.discoveryPath);if(Q?.url){let Z=await L9(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(Z.status==="compatible")return z2(Z.url,Q.authToken)}await new Promise((Z)=>setTimeout(Z,SM))}return}async function vM($){let J=Date.now()+bM;while(Date.now()<J){if(!(await C1($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,hM))}return!1}function cM($,J){try{return q2($)===q2(J)}catch{return!1}}function uM($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let Z=Q;if(Z.status==="running"||Z.status==="idle"||Z.status==="pending")return!0;return Array.isArray(Z.participants)&&Z.participants.length>0})}async function dM($,J,Q){let Z=new D$({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let W=await Z.command("session.list",{limit:500},void 0,{timeoutMs:EM});return!uM(W.payload)}catch{return!1}finally{await Z.dispose().catch(()=>{return})}}async function O9($={}){if($.endpoint?.trim()){let W=await L9($.endpoint);return W.status==="compatible"?W.url:void 0}let J=HJ(),Q=await B0(J.discoveryPath);if(!Q?.url)return;let Z=await L9(Q.url,{authToken:Q.authToken});if(Z.status==="compatible")return z2(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await $$(J.discoveryPath).catch(()=>{return});return}async function n8($={}){let J=await O9($);if(J&&await l$(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;let Q=HJ();return await YJ($.workspaceRoot??process.cwd()),await mM(Q)}async function D9($,J){let Q=new URL($),Z=J?.trim()||rY(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}async function lM($=HJ()){let J=await B0($.discoveryPath);if(!J?.url)return!1;try{if(await D9(J.url,J.authToken))return!0}catch{}return!1}async function iY($){if(!R9($.url))return;let J=HJ(),Q=await B0(J.discoveryPath);if(!Q?.url||!cM(Q.url,$.url))return;if(!await dM(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await lM())return;if(!await vM(Q.url))return;return await $$(J.discoveryPath).catch(()=>{return}),await n8({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as nY,createSessionId as aY,HUB_CHECKPOINT_CAPABILITY as nM,HUB_COMPACTION_CAPABILITY as aM,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as sM,HUB_HOOK_CAPABILITY_PREFIX as oM,HUB_MISTAKE_LIMIT_CAPABILITY as tM,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as eM,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as $z,isHubToolExecutorName as Jz}from"@sctg/cline-shared";function pM($){return $?JSON.parse(JSON.stringify($)):void 0}function rM($){return $?JSON.parse(JSON.stringify($)):void 0}function iM($){let J=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Z=(Array.isArray(J?.history)?J.history:[]).filter((f)=>!!f&&typeof f==="object"&&!Array.isArray(f)).flatMap((f)=>{let X=typeof f.ref==="string"?f.ref.trim():"",Y=Number(f.createdAt),V=Number(f.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(V))return[];return[{ref:X,createdAt:Y,runCount:V,...f.kind==="stash"||f.kind==="commit"?{kind:f.kind}:{}}]}),W=Z.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Z.length===0)return;return{...j?{enabled:j}:{},...W?{latest:W}:{},history:Z}}function p$($){let{session:J}=$,Q=pM(J.metadata);return{version:1,sessionId:J.sessionId,source:J.source,status:J.status,createdAt:J.startedAt,updatedAt:J.updatedAt,endedAt:J.endedAt??null,exitCode:J.exitCode??null,interactive:J.interactive,workspace:{cwd:J.cwd,root:J.workspaceRoot},model:{providerId:J.provider,modelId:J.model},capabilities:{enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams},lineage:{...J.parentSessionId?{parentSessionId:J.parentSessionId}:{},...J.parentAgentId?{parentAgentId:J.parentAgentId}:{},...J.agentId?{agentId:J.agentId}:{},...J.conversationId?{conversationId:J.conversationId}:{},isSubagent:J.isSubagent},...J.teamName?{team:{name:J.teamName}}:{},...J.prompt?{prompt:J.prompt}:{},...Q?{metadata:Q}:{},...J.messagesPath?{artifacts:{messagesPath:J.messagesPath}}:{},...$.messages?{messages:rM($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Z=iM(Q);return Z?{checkpoint:Z}:{}})()}}function _9($){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 P2($){if(!$)return;return JSON.parse(JSON.stringify($))}var Qz=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function sY($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function oY($){if(!$)return;let{userInstructionService:J,...Q}=$;return JSON.parse(JSON.stringify(Q))}function tY($){let J=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof J.agentId==="string"?J.agentId:"",conversationId:typeof J.conversationId==="string"?J.conversationId:"",iteration:typeof J.iteration==="number"?J.iteration:0,metadata:J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}}function E1($,J,Q){$.manifest.push(J),$.handlers.set(J.capabilityName,Q)}function eY($,J){let Q={manifest:[],handlers:new Map};for(let W of Object.keys(J.toolExecutors??{}).filter(Jz)){let j=J.toolExecutors?.[W];if(typeof j!=="function")continue;E1(Q,{kind:"toolExecutor",executor:W,capabilityName:`${eM}${W}`},async({payload:f,abortSignal:X})=>{let Y=Array.isArray(f.args)?[...f.args]:[],V={...tY(f.context),signal:X};return{result:await j(...Y,V)}})}for(let W of $?.extraTools??[])E1(Q,{kind:"tool",name:W.name,description:W.description,inputSchema:P2(W.inputSchema)??{},...W.lifecycle?{lifecycle:P2(W.lifecycle)}:{},capabilityName:`${sM}${W.name}`},async({payload:j,abortSignal:f,progress:X})=>{let Y={...tY(j.context),signal:f};return{result:await W.execute(j.input,{...Y,emitUpdate:(H)=>{X({update:H})}})}});let Z=$?.hooks;if(Z)for(let W of Qz){let j=Z[W];if(typeof j!=="function")continue;E1(Q,{kind:"hook",name:W,capabilityName:`${oM}${W}`},async({payload:f})=>({control:await j(f.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;E1(Q,{kind:"compaction",capabilityName:aM,config:sY($.compaction)},async({payload:j})=>({result:await W(j.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;E1(Q,{kind:"checkpoint",capabilityName:nM,config:sY($.checkpoint)},async({payload:j})=>({result:await W(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;E1(Q,{kind:"mistakeLimit",capabilityName:tM},async({payload:j})=>({result:await W(j.context)}))}if($?.userInstructionService){let W=$.userInstructionService;E1(Q,{kind:"userInstructionService",capabilityName:$z},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Q}function ZV($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let J=$.message;if(typeof J==="string"&&J.trim())return J.trim()}return}function Zz($){return ZV($)??"Capability request was cancelled."}function Wz($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function jz($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function fz($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=typeof J.inputTokens==="number"?J.inputTokens:void 0,Z=typeof J.outputTokens==="number"?J.outputTokens:void 0;if(Q===void 0||Z===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:typeof J.cacheReadTokens==="number"?J.cacheReadTokens:0,cacheWriteTokens:typeof J.cacheWriteTokens==="number"?J.cacheWriteTokens:0,totalCost:typeof J.totalCost==="number"?J.totalCost:0}}function $V($){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 M9($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function r$($,J){return M9($?.[J])??0}function Xz($){let J=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Z=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=Z?.teamRole==="teammate"||Z?.teamRole==="lead"?Z.teamRole:void 0;return{event:{type:"usage",agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,inputTokens:r$(J,"inputTokens"),outputTokens:r$(J,"outputTokens"),cacheReadTokens:r$(J,"cacheReadTokens"),cacheWriteTokens:r$(J,"cacheWriteTokens"),cost:M9(J?.totalCost),totalInputTokens:r$(Q,"inputTokens"),totalOutputTokens:r$(Q,"outputTokens"),totalCacheReadTokens:r$(Q,"cacheReadTokens"),totalCacheWriteTokens:r$(Q,"cacheWriteTokens"),totalCost:M9(Q?.totalCost)},teamAgentId:typeof Z?.teamAgentId==="string"?Z.teamAgentId:void 0,teamRole:W}}function Yz($){let J=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??J?.finishReason,Z=jz(Q)?Q:Q==="failed"?"error":"completed",W=fz($?.usage??J?.usage);return{type:"done",reason:Z,text:typeof $?.text==="string"?$.text:typeof J?.text==="string"?J.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof J?.iterations==="number"?J.iterations:0,usage:W}}function AJ($,J){return $.error?.message??`hub command failed: ${J}`}function a8($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function WV($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof J?.agentId==="string"?J.agentId:void 0),parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,isSubagent:typeof J?.isSubagent==="boolean"?J.isSubagent:!1,source:typeof J?.source==="string"?J.source:T0.CORE,pid:typeof J?.pid==="number"?J.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:a8($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:a8($.status)==="completed"?0:a8($.status)==="failed"?1:void 0,status:a8($.status),interactive:J?.interactive===!0,provider:typeof J?.provider==="string"?J.provider:"hub",model:typeof J?.model==="string"?J.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof J?.teamName==="string"?J.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??J?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??J?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??J?.enableTeams===!0,prompt:typeof J?.prompt==="string"?J.prompt:void 0,metadata:J,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,hookPath:typeof J?.hookPath==="string"?J.hookPath:void 0}}function i$($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;return J.version===1&&typeof J.sessionId==="string"?JSON.parse(JSON.stringify(J)):void 0}function Vz($){let J=i$($?.snapshot);if(J)return _9(J);let Q=$?.session;return Q?WV(Q):void 0}function JV($,J,Q){let Z=Q?.workspaceRoot?.trim()||J.config.workspaceRoot||J.config.cwd;return N0.parse({version:1,session_id:$,source:J.source??T0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:a8(Q?.status),interactive:J.interactive===!0,provider:J.config.providerId,model:J.config.modelId,cwd:Q?.cwd?.trim()||J.config.cwd,workspace_root:Z,team_name:J.config.teamName,enable_tools:J.config.enableTools,enable_spawn:J.config.enableSpawnAgent,enable_teams:J.config.enableAgentTeams,prompt:J.prompt?.trim()||void 0,metadata:J.sessionMetadata&&Object.keys(J.sessionMetadata).length>0?J.sessionMetadata:void 0})}function QV($,J){return N0.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??J.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class b1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new d8;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,J){this.clientContext=J,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd},this.defaultCapabilities=O0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new D$({...this.clientOptions,url:$})}async replaceClient($){let J=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(J.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!pY($,"session.create"))return!1;let J=await iY({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!J)return!1;return await this.replaceClient(J),!0}registerPlannedSession($,J,Q){if(this.sessionCapabilities.set($,J),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let J=this.resolveCapabilities($),Q=eY($.localRuntime,J),Z=$.config.sessionId?.trim()||aY(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:P2({...$.config,sessionId:Z}),metadata:{...$.sessionMetadata??{},source:$.source??T0.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:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:P2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Z,J,Q.handlers);let j;try{j=await W()}catch(V){if(this.cleanupPlannedSession(Z),await this.recoverLocalHubStartupDeadlock(V)){this.registerPlannedSession(Z,J,Q.handlers);try{j=await W()}catch(H){throw this.cleanupPlannedSession(Z),H}}else throw V}let f=i$(j.payload?.snapshot),X=j.payload?.session,Y=(f?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Z),Error("Hub runtime did not return a session id.");if(Y!==Z)this.cleanupPlannedSession(Z),this.registerPlannedSession(Y,J,Q.handlers);return{sessionId:Y,manifest:f?QV(f,$):JV(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let Z=$.start,W=Z?this.resolveCapabilities(Z):void 0,j=Z?eY(Z.localRuntime,W??{}):{manifest:[],handlers:new Map},f=Z?Z.config.sessionId?.trim()||aY():void 0;if(f&&W)this.sessionCapabilities.set(f,W);if(f&&j.handlers.size>0)this.sessionClientContributionHandlers.set(f,j.handlers),this.ensureSessionSubscription(f);let X;try{X=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.config.workspaceRoot?.trim()||Z.config.cwd,cwd:Z.config.cwd??$.cwd,sessionConfig:P2({...Z.config,sessionId:f}),metadata:{...Z.sessionMetadata??{},source:Z.source??T0.CORE,provider:Z.config.providerId,model:Z.config.modelId,enableTools:Z.config.enableTools,enableSpawn:Z.config.enableSpawnAgent,enableTeams:Z.config.enableAgentTeams,teamName:Z.config.teamName,prompt:Z.prompt,interactive:Z.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Z.localRuntime?.configExtensions?{configExtensions:Z.localRuntime.configExtensions}:{}},toolPolicies:P2(Z.toolPolicies)}:{}},J)}catch(K){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error(K)}let Y=i$(X.payload?.snapshot),V=X.payload?.session,H=(Y?.sessionId??V?.sessionId)?.trim();if(Q&&!H){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error("Hub checkpoint restore returned no session id")}if(H&&f&&H!==f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&j.handlers.size>0)this.sessionClientContributionHandlers.set(H,j.handlers);if(H)this.ensureSessionSubscription(H);let A=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,B=X.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:Y?QV(Y,Z??{}):JV(H,Z??{},V),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:A,checkpoint:B}}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 J=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(J.payload?.prompts)?J.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,updated:J.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,removed:J.payload?.removed===!0}}async getAccumulatedUsage($){let J=await this.client.command("session.get",{includeSnapshot:!0},$),Q=i$(J.payload?.snapshot);if(Q){let f=Q.usage?{...Q.usage}:void 0,X=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return f||X?{usage:f,aggregateUsage:X}:void 0}let Z=J.payload?.session,W=$V(Z?.usage),j=$V(Z?.aggregateUsage);return W||j?{usage:W,aggregateUsage:j}:void 0}async abort($,J){await this.client.command("run.abort",{sessionId:$,reason:ZV(J)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,J]of this.sessionSubscriptions){J();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 J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(_1(Q))return;throw Q}return Vz(J.payload)}async listSessions($=100){let J=await this.client.command("session.list",{limit:$}),Q=Array.isArray(J.payload?.snapshots)?J.payload.snapshots.flatMap((W)=>{let j=i$(W);return j?[_9(j)]:[]}):[];if(Q.length>0)return Q;return(J.payload?.sessions??[]).map(WV)}async listSettings($){let J=await this.client.command("settings.list",oY($));if(!J.ok)throw Error(AJ(J,"settings.list"));return J.payload?.snapshot}async toggleSetting($){let J=await this.client.command("settings.toggle",oY($));if(!J.ok)throw Error(AJ(J,"settings.toggle"));return{snapshot:J.payload?.snapshot,changedTypes:Array.isArray(J.payload?.changedTypes)?J.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,J){let Q={...J.metadata??{}};if(typeof J.prompt==="string")Q.prompt=J.prompt;if(typeof J.title==="string")Q.title=J.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw nY(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(AJ(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:J,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(AJ(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,J){return this.events.subscribe($,J)}ensureSessionSubscription($){let J=$.trim();if(!J||this.sessionSubscriptions.has(J))return;let Q=this.client.subscribe((Z)=>{this.handleHubEvent(Z)},{sessionId:J});this.sessionSubscriptions.set(J,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let J=$.trim();if(!J)return;this.sessionSubscriptions.get(J)?.(),this.sessionSubscriptions.delete(J),this.agentDoneEmittedForCurrentRunBySession.delete(J)}resolveCapabilities($){return O0(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:Yz($.payload)}})}handleHubEvent($){let J=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!J)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(J);let Q=i$($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,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 Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",Z=$.payload?.redacted===!0;if(!Q&&!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:Z}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:J,payload:$.payload});return}case"usage.updated":{let Q=Xz($.payload);this.events.emit({type:"agent_event",payload:{sessionId:J,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:J,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"tool",toolCallId:Q,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 Q=i$($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:J,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:J,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=i$($.payload?.snapshot),Z=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:J,payload:{...$.payload,reason:Z}}),Q?.interactive===!0&&Z0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:J,reason:Z,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,J,Q){try{nY(this.telemetry,{component:"core",operation:$,error:J,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let J=$.sessionId?.trim();if(!J)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let Z=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Z)return;let j=this.sessionClientContributionHandlers.get(J)?.get(W);if(!j){await this.client.command("capability.respond",{requestId:Z,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${J}.`},J).catch(()=>{});return}let f=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Z,X);let Y=(V)=>{this.client.command("capability.progress",{requestId:Z,payload:V},J).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let V=await j({payload:f,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!0,payload:V},J)}catch(V){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!1,error:V instanceof Error?V.message:String(V)},J)}finally{this.activeCapabilityAbortControllers.delete(Z)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let J=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!J)return;let Q=this.activeCapabilityAbortControllers.get(J);if(!Q)return;Q.abort(Zz($.payload.error))}async handleApprovalRequested($){let J=$.sessionId?.trim();if(!J)return;let Q=this.sessionCapabilities.get(J)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let Z=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Z||!W||!j)return;let f=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=Wz($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:J,toolCallId:W,toolName:j,toolInput:X});let Y=await Promise.resolve(Q({sessionId:J,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:J,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:j,input:X,policy:f})).catch((V)=>({approved:!1,reason:V instanceof Error?V.message:`Tool approval request failed: ${String(V)}`}));await this.client.command("approval.respond",{approvalId:Z,approved:Y.approved,reason:Y.reason},J).catch(()=>{})}}class BJ extends b1{constructor($){super({url:q2($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as Hz,mkdirSync as Az}from"node:fs";import{join as Bz}from"node:path";import{asBool as s8,asOptionalString as f$,asString as U$,ensureSessionSchema as Kz,loadSqliteDb as Gz,nowIso as KJ,toBoolInt as o8}from"@sctg/cline-shared/db";import{resolveDbDataDir as Fz}from"@sctg/cline-shared/storage";class n${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??Fz()}init(){this.getRawDb()}ensureSessionsDir(){if(!Hz(this.sessionsDirPath))Az(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return Bz(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=Gz(this.sessionDbPath());return Kz($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}create($){let J=KJ();this.run(`INSERT OR REPLACE INTO sessions (
469
469
  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": "@sctg/cline-core",
3
3
  "description": "Cline Core SDK for Node Runtime",
4
- "version": "3.89.2-beta.20260620150721",
4
+ "version": "3.89.2-beta.20260620160351",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/TEA-ching/cline",
@@ -48,9 +48,9 @@
48
48
  "test:watch": "vitest --config vitest.config.ts"
49
49
  },
50
50
  "dependencies": {
51
- "@sctg/cline-agents": "3.89.2-beta.20260620150721",
52
- "@sctg/cline-shared": "3.89.2-beta.20260620150721",
53
- "@sctg/cline-llms": "3.89.2-beta.20260620150721",
51
+ "@sctg/cline-agents": "3.89.2-beta.20260620160351",
52
+ "@sctg/cline-shared": "3.89.2-beta.20260620160351",
53
+ "@sctg/cline-llms": "3.89.2-beta.20260620160351",
54
54
  "@modelcontextprotocol/sdk": "^1.29.0",
55
55
  "@opentelemetry/api": "^1.9.0",
56
56
  "@opentelemetry/api-logs": "^0.214.0",