@cline/core 0.0.40-nightly.1778642379 → 0.0.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hub/daemon/entry.js +1 -1
- package/dist/hub/index.js +56 -56
- package/dist/index.js +41 -41
- package/package.json +4 -4
package/dist/hub/daemon/entry.js
CHANGED
|
@@ -477,7 +477,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
477
477
|
updated_at = ?
|
|
478
478
|
WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,D0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,D0(),$)}}class A4{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new V4({dbPath:$.dbPath});let f=$.specs;this.reconciler=new k7({store:this.store,specs:f}),this.materializer=new W4({store:this.store}),this.eventIngress=new y7({store:this.store,logger:$.logger}),this.runner=new j4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new I7({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:J});else Q.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){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 lH={};q(lH,{manifestToSessionRecord:()=>SJ,listSessionHistoryFromBackend:()=>d7,listSessionHistory:()=>CJ,hydrateSessionHistory:()=>dH});import{readdir as CL,readFile as vH}from"node:fs/promises";import{join as cH}from"node:path";import{formatDisplayUserInput as EL,normalizeUserInput as hL}from"@cline/shared";import{resolveSessionDataDir as uH}from"@cline/shared/storage";import{existsSync as qL}from"node:fs";import{readFile as wL}from"node:fs/promises";import{formatDisplayUserInput as IH}from"@cline/shared";class B4{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function H1($){let f=$?.trim();if(!f||!qL(f))return[];try{let J=(await wL(f,"utf8")).trim();if(!J)return[];let Q=JSON.parse(J);if(Array.isArray(Q))return xH(Q);if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q.messages;if(Array.isArray(Z))return xH(Z)}return[]}catch{return[]}}function SL($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:IH($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:IH(f.text)}})}}function xH($){return $.map(SL)}function v7($){return $?{...$}:void 0}async function gH($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let Q=await f.upsertSubagentSessionFromHook($);if(!Q)return;await f.appendSubagentHookAudit(Q,$),await f.applySubagentStatus(Q,$)}function K4($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function m0($){let f=K4($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function wJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function bL($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function u7($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function kL($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function IL($){return $.isSubagent!==!0&&!K4($.parentSessionId)}function xL($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let Q of f){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function SJ($){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 gL($){let f=u7($);if(f===0)return[];let J=uH(),Z=(await CL(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:xL(j.name.trim())})).sort((j,X)=>X.recency-j.recency||X.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let X=j.name.trim();if(!X)return;let H=cH(J,X,`${X}.json`),Y=await vH(H,"utf8").catch(()=>{return});if(!Y)return;let V;try{V=JSON.parse(Y)}catch{return}let A=y0.safeParse(V);if(!A.success)return;return SJ(A.data)}))).filter((j)=>Boolean(j)).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function mL($,f,J){let Q=u7(f);if(Q===0)return await $.listSessions(0),[];let Z=J.includeSubagents?Q:kL(Q),W=await $.listSessions(Z);return(J.includeSubagents?W:W.filter(IL)).slice(0,Q)}function vL($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let Q=J;if(Q.type!=="text")continue;let Z=Q.text?.trim();if(Z)f.push(Z)}return f.join(`
|
|
479
479
|
`).trim()}function mH($){return $.replace(/\s+/g," ").trim()}function cL($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function uL($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let Q=mH(vL(J.content));if(!Q)continue;let Z=f==="user"?mH(EL(Q)):Q,W=hL(Z.split(`
|
|
480
|
-
`)[0]??Z);return cL(W,50)}return}function dL($){let f=0;for(let J of $)f+=wJ(J.metrics?.cost)??0;return f}function lL($){let f,J;for(let Q=$.length-1;Q>=0;Q-=1){let Z=$[Q];if(!f)f=m0(Z.modelInfo?.provider);if(!J)J=m0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function pL($){return m0($?.provider)??m0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function rL($){return m0($?.model)??m0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function c7($,f){let J=bL($.metadata),Q=K4(f?.title)??K4(J?.title),Z=wJ(f?.totalCost)??wJ(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:m0(f?.provider)??m0($.provider)??pL(J)??"",model:m0(f?.model)??m0($.model)??rL(J)??"",metadata:W}}async function dH($,f){return await Promise.all(f.map(async(J)=>{let Q=c7(J),Z=Boolean(K4(Q.metadata?.title)),W=Boolean(m0(Q.provider)),j=Boolean(m0(Q.model)),X=wJ(Q.metadata?.totalCost),H=X!==void 0&&X>0;if(Z&&W&&j&&H)return Q;let Y=await $.readSessionMessages(J.sessionId);if(Y.length===0)return Q;let V=lL(Y),A=dL(Y);return c7(J,{title:Z?void 0:uL(Y),provider:W?void 0:V.provider,model:j?void 0:V.model,totalCost:H||A<=0?void 0:A})}))}async function CJ($,f={}){let J=u7(f.limit),Q=f.includeSubagents===!0,Z=await mL($,J,{includeSubagents:Q}),W=f.includeManifestFallback===!0&&Z.length<J?await gL(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let H of[...Z,...W]){if(j.has(H.sessionId))continue;j.set(H.sessionId,H)}let X=W.length===0?Z:Array.from(j.values()).sort((H,Y)=>Y.startedAt.localeCompare(H.startedAt)).slice(0,J);if(f.hydrate===!1)return X.map((H)=>c7(H));return await dH($,X)}async function iL($){let f=$.trim();if(!f)return;let J=cH(uH(),f,`${f}.json`),Q=await vH(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=y0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function d7($,f={}){let J=new Map;return await CJ({listSessions:async(Z)=>{let W=await $.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map($8)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await iL(Z);return await H1(W)}},f)}var iY={};q(iY,{resolveSessionBackend:()=>yQ,createRuntimeHost:()=>Y2});import{captureSdkError as pY}from"@cline/shared";import{createSessionId as xO,resolveHubCommandTimeoutMs as gO}from"@cline/shared";import{spawn as PO}from"node:child_process";import{closeSync as FO,mkdirSync as DO,openSync as RO}from"node:fs";import{basename as UO,dirname as LO,join as OO}from"node:path";import{fileURLToPath as zO}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as _O,isHubDaemonProcess as ZY,withResolvedClineBuildEnv as yO}from"@cline/shared";import{createHash as nL,randomBytes as aL}from"node:crypto";import{existsSync as tL}from"node:fs";import{chmod as sL,mkdir as l7,readFile as tH,rm as p7,writeFile as sH}from"node:fs/promises";import{dirname as oH,join as r7}from"node:path";import{resolveClineDataDir as G4,resolveClineDir as eH}from"@cline/shared/storage";var rH="0.0.
|
|
480
|
+
`)[0]??Z);return cL(W,50)}return}function dL($){let f=0;for(let J of $)f+=wJ(J.metrics?.cost)??0;return f}function lL($){let f,J;for(let Q=$.length-1;Q>=0;Q-=1){let Z=$[Q];if(!f)f=m0(Z.modelInfo?.provider);if(!J)J=m0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function pL($){return m0($?.provider)??m0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function rL($){return m0($?.model)??m0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function c7($,f){let J=bL($.metadata),Q=K4(f?.title)??K4(J?.title),Z=wJ(f?.totalCost)??wJ(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:m0(f?.provider)??m0($.provider)??pL(J)??"",model:m0(f?.model)??m0($.model)??rL(J)??"",metadata:W}}async function dH($,f){return await Promise.all(f.map(async(J)=>{let Q=c7(J),Z=Boolean(K4(Q.metadata?.title)),W=Boolean(m0(Q.provider)),j=Boolean(m0(Q.model)),X=wJ(Q.metadata?.totalCost),H=X!==void 0&&X>0;if(Z&&W&&j&&H)return Q;let Y=await $.readSessionMessages(J.sessionId);if(Y.length===0)return Q;let V=lL(Y),A=dL(Y);return c7(J,{title:Z?void 0:uL(Y),provider:W?void 0:V.provider,model:j?void 0:V.model,totalCost:H||A<=0?void 0:A})}))}async function CJ($,f={}){let J=u7(f.limit),Q=f.includeSubagents===!0,Z=await mL($,J,{includeSubagents:Q}),W=f.includeManifestFallback===!0&&Z.length<J?await gL(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let H of[...Z,...W]){if(j.has(H.sessionId))continue;j.set(H.sessionId,H)}let X=W.length===0?Z:Array.from(j.values()).sort((H,Y)=>Y.startedAt.localeCompare(H.startedAt)).slice(0,J);if(f.hydrate===!1)return X.map((H)=>c7(H));return await dH($,X)}async function iL($){let f=$.trim();if(!f)return;let J=cH(uH(),f,`${f}.json`),Q=await vH(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=y0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function d7($,f={}){let J=new Map;return await CJ({listSessions:async(Z)=>{let W=await $.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map($8)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await iL(Z);return await H1(W)}},f)}var iY={};q(iY,{resolveSessionBackend:()=>yQ,createRuntimeHost:()=>Y2});import{captureSdkError as pY}from"@cline/shared";import{createSessionId as xO,resolveHubCommandTimeoutMs as gO}from"@cline/shared";import{spawn as PO}from"node:child_process";import{closeSync as FO,mkdirSync as DO,openSync as RO}from"node:fs";import{basename as UO,dirname as LO,join as OO}from"node:path";import{fileURLToPath as zO}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as _O,isHubDaemonProcess as ZY,withResolvedClineBuildEnv as yO}from"@cline/shared";import{createHash as nL,randomBytes as aL}from"node:crypto";import{existsSync as tL}from"node:fs";import{chmod as sL,mkdir as l7,readFile as tH,rm as p7,writeFile as sH}from"node:fs/promises";import{dirname as oH,join as r7}from"node:path";import{resolveClineDataDir as G4,resolveClineDir as eH}from"@cline/shared/storage";var rH="0.0.41";var iH={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:rH,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var oL="CLINE_HUB_DISCOVERY_PATH",eL="CLINE_HUB_BUILD_ID",nH=30000,$O=15000,fO=100;function JO($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function QO($){return nL("sha256").update($).digest("hex").slice(0,12)}function ZO($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function EJ(){return aL(32).toString("hex")}function WO($){return new Promise((f)=>setTimeout(f,$))}function jO($){return`${$}.lock`}async function XO($){try{let f=JSON.parse(await tH(r7($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function aH($){await p7($,{recursive:!0,force:!0}).catch(()=>{return})}function Y1(){return process.env[eL]?.trim()||String(iH.version)}function w$($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${QO($)}`,J=process.env[oL]?.trim()||r7(G4(),"locks","hub","owners",`${JO(f)}.json`);return{ownerId:f,discoveryPath:J}}function $Y($=`hub-${Date.now().toString(36)}`){return w$($)}async function A0($){try{let f=JSON.parse(await tH($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function hJ($,f){await l7(oH($),{recursive:!0}),await p7($,{force:!0}).catch(()=>{return}),await sH($,`${JSON.stringify(f,null,2)}
|
|
481
481
|
`,{encoding:"utf8",mode:384}),await sL($,384)}async function v0($){await p7($,{force:!0}).catch(()=>{return})}async function bJ($,f){let J=jO($);await l7(oH(J),{recursive:!0});let Q=Date.now()+$O;while(!0)try{await l7(J,{recursive:!1}),await sH(r7(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
482
482
|
`,"utf8");try{return await f()}finally{await aH(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await XO(J),X=j?Date.now()-Date.parse(j.acquiredAt):nH+1;if(!j||!ZO(j.pid)||X>nH){await aH(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await WO(fO)}}async function R0($){try{let f=await fetch(i7($));if(!f.ok)return;return await f.json()}catch{return}}function t0($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function i7($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function fY($){return tL($)}import{CLINE_HUB_DEV_PORT as HO,CLINE_HUB_PORT as YO,resolveClineBuildEnv as VO}from"@cline/shared";var AO="CLINE_HUB_HOST",BO="CLINE_HUB_PORT",KO="CLINE_HUB_PATHNAME",n7="127.0.0.1",a7=YO,t7="/hub";function JY($){return VO($)==="development"?HO:a7}function s7($={}){return($.env??process.env)[AO]?.trim()||n7}function $2($={}){let J=($.env??process.env)[BO]?.trim();if(!J)return JY($);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return JY($);return Q}function o7($={}){return($.env??process.env)[KO]?.trim()||t7}function c0($={},f={}){return{host:$.host??s7(f),port:$.port??$2(f),pathname:$.pathname??o7(f)}}var GO="shared:cline";function QY($){let f=M$($.trim());return w$(`workspace:${f||$.trim()}`)}function Y0($=GO){return w$($)}var NO=8000,TO=200,MO=3000,qO=100,wO=[100,250,500,1000,2000],SO="--cline-hub-daemon";function CO($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function EO(){try{let $=OO(G4(),"logs","hub-daemon.log");return DO(LO($),{recursive:!0}),{fd:RO($,"a"),logPath:$}}catch{return}}function P4($){let f=$.buildId?.trim();return!!f&&f===Y1()}async function hO($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await R0($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,qO))}return!1}async function F4($,f){if(P4($))return;if(await D4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await hO($.url,MO),await v0(f).catch(()=>{return})}function bO(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return zO(new URL(`./entry.${$}`,import.meta.url))}function kO($,f){let J=bO(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=UO(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),X=W?[SO]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...X,"--cwd",$,...CO(f)],cwd:$,env:{...yO(process.env),CLINE_NO_INTERACTIVE:"1",[_O]:"1"}}}function IO($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function e7($,f={}){if(ZY())return;let J=kO($,f),Q=EO();try{PO(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(Q)FO(Q.fd)}}async function f2($,f={}){for(let J=0;;J++)try{e7($,f);return}catch(Q){let Z=wO[J];if(!IO(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function kJ($,f={}){if(ZY())return;let J=Y0(),Q=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=c0(f),W=t0(Z.host,Z.port,Z.pathname);A0(J.discoveryPath).then(async(j)=>{if(j?.url){let V=await R0(j.url);if(V?.url&&P4(V)&&await W$(V.url,{authToken:j.authToken}))return;if(V?.url)await F4({...V,authToken:j.authToken},J.discoveryPath);else await v0(J.discoveryPath).catch(()=>{return})}let X=await R0(W);if(X?.url)await F4(X,J.discoveryPath);let Y=!Q&&Z.port!==0?{...Z,port:0}:Z;await f2($,Y)}).catch(()=>{})}async function WY($,f={}){let J=Y0(),Q=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=c0(f),j=t0(W.host,W.port,W.pathname),X=(K)=>{if(!Q)V1(K.url,K.authToken);return K},H=await A0(J.discoveryPath);if(H?.url){let K=await R0(H.url);if(K?.url&&P4(K)&&await W$(K.url,{authToken:H.authToken}))return X({url:K.url,authToken:H.authToken});if(K?.url)await F4({...K,authToken:H.authToken},J.discoveryPath);else await v0(J.discoveryPath).catch(()=>{return})}let Y=await R0(j);if(Y?.url)await F4(Y,J.discoveryPath);let A=!Z&&W.port!==0?{...W,port:0}:W;await f2($,A);let B=Date.now()+NO;while(Date.now()<B){let K=await A0(J.discoveryPath);if(K?.url){let R=await R0(K.url);if(R?.url&&P4(R)&&await W$(R.url,{authToken:K.authToken}))return X({url:R.url,authToken:K.authToken})}let G=await R0(j);if(G?.url&&!P4(G))await F4(G,J.discoveryPath);await new Promise((R)=>setTimeout(R,TO))}throw Error("Timed out waiting for detached hub startup.")}function mO(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function VY($){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((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return VY($.data);return String($)}function vO($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function jY($){let f=$,J=vO(f.reason);return new z0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:$Q,{closeCode:f.code,closeReason:J||void 0})}function cO($,f){if($ instanceof z0)return $;if($ instanceof Error)return new z0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new z0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new z0("hub_connect_failed",J);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new z0("hub_connect_failed",Q?`Failed to connect to hub at ${f.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var uO=8000,dO=200,XY="*",HY=8000,lO="cline-hub-auth.",AY=new Map,BY=new Set,pO=3000,rO=3000,iO=100,$Q="Hub connection closed",nO=250,aO=5000,YY=0.5;class z0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function QQ($){return $ instanceof z0}class J2 extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function IJ($,f){return $ instanceof J2&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function KY($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=ZQ($.toString());return J?AY.get(J):void 0}function tO($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function ZQ($){if(!tO($))return;let f=new URL(A1($));return f.search="",f.hash="",f.toString()}function fQ($){let f=ZQ($);return!!f&&BY.has(f)}function V1($,f){let J=ZQ($);if(J){if(BY.add(J),f?.trim())AY.set(J,f)}return $}class s0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new z0("hub_connection_closed",$Q);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),f=this.options.authToken?.trim()||KY($);$.hash="";let Q=new(mO())($.toString(),f?[`${lO}${f}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let X=!1,H=setTimeout(()=>{if(X)return;X=!0,Z=!0,this.lastCloseError=new z0("hub_connect_timeout",`Timed out connecting to hub after ${HY}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},HY);Q.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(H),W()}),Q.addEventListener("error",(Y)=>{if(X)return;X=!0,clearTimeout(H),this.lastCloseError=cO(Y,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(Y)=>{if(X)return;if(X=!0,clearTimeout(H),!Z)this.lastCloseError=jY(Y),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(VY(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=jY(W),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.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 W of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(W));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,Q={listener:$,sessionId:J};return this.listeners.add(Q),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,Q){let Z=0,W=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,Q)}catch(j){if(!W||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,Q){await this.connect();let Z=xO("hubreq_"),W=gO($,Q?.timeoutMs),j=new Promise((H,Y)=>{let V=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;Y(new J2($,"hub_command_timeout",`Hub command ${$} timed out after ${W}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},W);this.pendingReplies.set(Z,{resolve:(A)=>{if(V)clearTimeout(V);H(A)},reject:(A)=>{if(V)clearTimeout(V);Y(A)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:f}})}catch(H){throw this.pendingReplies.delete(Z),H}let X=await j;if(!X.ok)throw new J2($,X.error?.code,X.error?.message??`Hub command ${$} failed`);return X}async recoverLocalHubTransport($){if(!fQ(this.currentUrl)||!QQ($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await t1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,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(nO*2**this.reconnectAttempt,aO),f=Math.round($*(1-YY)+Math.random()*$*YY);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!fQ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await t1({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 z0("hub_connection_closed",$Q),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.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 z0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(J)??0)+f;if(Q<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,Q),f>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??XY}subscriptionSessionIdFromKey($){return $===XY?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function A1($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function W$($,f){let J=new s0({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function JQ($,f){let J=A1($),Q=await R0(J);if(!Q)return{status:"unreachable",url:J};let Z=Y1(),W=Q.buildId?.trim();if(!W||W!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await W$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function sO($){let f=Date.now()+uO;while(Date.now()<f){let J=await A0($.discoveryPath);if(J?.url){let Q=await JQ(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return V1(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,dO))}return}async function oO($){let f=Date.now()+rO;while(Date.now()<f){if(!(await R0($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,iO))}return!1}function eO($,f){try{return A1($)===A1(f)}catch{return!1}}function $z($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let Q=J;if(Q.status==="running"||Q.status==="idle")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function fz($,f,J){let Q=new s0({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await Q.command("session.list",{limit:500},void 0,{timeoutMs:pO});return!$z(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function R4($={}){if($.endpoint?.trim()){let Z=await JQ($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=Y0(),J=await A0(f.discoveryPath);if(!J?.url)return;let Q=await JQ(J.url);if(Q.status==="compatible")return V1(Q.url,J.authToken);if(Q.status==="build_mismatch")await v0(f.discoveryPath).catch(()=>{return});return}async function t1($={}){let f=await R4($);if(f&&await W$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=Y0();return await f2($.workspaceRoot??process.cwd()),await sO(J)}async function D4($,f){let J=new URL($),Q=f?.trim()||KY(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function WQ(){let $=Y0(),f=await A0($.discoveryPath);if(!f?.url)return!1;try{if(await D4(f.url,f.authToken))return!0}catch{}return!1}async function xJ($){if(!fQ($.url))return;let f=Y0(),J=await A0(f.discoveryPath);if(!J?.url||!eO(J.url,$.url))return;if(!await fz(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await WQ())return;if(!await oO(J.url))return;return await v0(f.discoveryPath).catch(()=>{return}),await t1({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var yY={};q(yY,{HubRuntimeHost:()=>S$});import{captureSdkError as Wz,createSessionId as PY,HUB_CHECKPOINT_CAPABILITY as jz,HUB_COMPACTION_CAPABILITY as Xz,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Hz,HUB_HOOK_CAPABILITY_PREFIX as Yz,HUB_MISTAKE_LIMIT_CAPABILITY as Vz,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Az,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Bz,isHubToolExecutorName as Kz}from"@cline/shared";var GY={};q(GY,{createCoreSessionSnapshot:()=>j$,coreSessionSnapshotToRecord:()=>gJ});function Jz($){return $?JSON.parse(JSON.stringify($)):void 0}function Qz($){return $?JSON.parse(JSON.stringify($)):void 0}function Zz($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let X=typeof j.ref==="string"?j.ref.trim():"",H=Number(j.createdAt),Y=Number(j.runCount);if(!X||!Number.isFinite(H)||!Number.isInteger(Y))return[];return[{ref:X,createdAt:H,runCount:Y,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=$?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function j$($){let{session:f}=$,J=Jz(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:Qz($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=Zz(J);return Q?{checkpoint:Q}:{}})()}}function gJ($){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 Q2($){if(!$)return;return JSON.parse(JSON.stringify($))}var Gz=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function FY($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function DY($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function RY($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function s1($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function UY($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(Kz)){let W=f.toolExecutors?.[Z];if(typeof W!=="function")continue;s1(J,{kind:"toolExecutor",executor:Z,capabilityName:`${Az}${Z}`},async({payload:j,abortSignal:X})=>{let H=Array.isArray(j.args)?[...j.args]:[],Y={...RY(j.context),signal:X};return{result:await W(...H,Y)}})}for(let Z of $?.extraTools??[])s1(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:Q2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:Q2(Z.lifecycle)}:{},capabilityName:`${Hz}${Z.name}`},async({payload:W,abortSignal:j,progress:X})=>{let H={...RY(W.context),signal:j};return{result:await Z.execute(W.input,{...H,emitUpdate:(V)=>{X({update:V})}})}});let Q=$?.hooks;if(Q)for(let Z of Gz){let W=Q[Z];if(typeof W!=="function")continue;s1(J,{kind:"hook",name:Z,capabilityName:`${Yz}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;s1(J,{kind:"compaction",capabilityName:Xz,config:FY($.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;s1(J,{kind:"checkpoint",capabilityName:jz,config:FY($.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;s1(J,{kind:"mistakeLimit",capabilityName:Vz},async({payload:W})=>({result:await Z(W.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;s1(J,{kind:"userInstructionService",capabilityName:Bz},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function Pz($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return"Capability request was cancelled."}function Fz($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function Dz($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function Rz($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,Q=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function LY($){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 jQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function B1($,f){return jQ($?.[f])??0}function Uz($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:B1(f,"inputTokens"),outputTokens:B1(f,"outputTokens"),cacheReadTokens:B1(f,"cacheReadTokens"),cacheWriteTokens:B1(f,"cacheWriteTokens"),cost:jQ(f?.totalCost),totalInputTokens:B1(J,"inputTokens"),totalOutputTokens:B1(J,"outputTokens"),totalCacheReadTokens:B1(J,"cacheReadTokens"),totalCacheWriteTokens:B1(J,"cacheWriteTokens"),totalCost:jQ(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function Lz($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,Q=Dz(J)?J:J==="failed"?"error":"completed",Z=Rz($?.usage??f?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function mJ($,f){return $.error?.message??`hub command failed: ${f}`}function U4($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function _Y($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:K0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:U4($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:U4($.status)==="completed"?0:U4($.status)==="failed"?1:void 0,status:U4($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function o1($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function Oz($){let f=o1($?.snapshot);if(f)return gJ(f);let J=$?.session;return J?_Y(J):void 0}function OY($,f,J){let Q=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return y0.parse({version:1,session_id:$,source:f.source??K0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:U4(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:Q,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function zY($,f){return y0.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??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class S${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new B4;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=F0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new s0({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!IJ($,"session.create"))return!1;let f=await xJ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=UY($.localRuntime,f),Q=$.config.sessionId?.trim()||PY(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:Q2({...$.config,sessionId:Q}),metadata:{...$.sessionMetadata??{},source:$.source??K0.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:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:Q2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Q,f,J.handlers);let W;try{W=await Z()}catch(Y){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(Y)){this.registerPlannedSession(Q,f,J.handlers);try{W=await Z()}catch(V){throw this.cleanupPlannedSession(Q),V}}else throw Y}let j=o1(W.payload?.snapshot),X=W.payload?.session,H=(j?.sessionId??X?.sessionId)?.trim();if(!H)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(H!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(H,f,J.handlers);return{sessionId:H,manifest:j?zY(j,$):OY(H,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?UY(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||PY():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&W.handlers.size>0)this.sessionClientContributionHandlers.set(j,W.handlers),this.ensureSessionSubscription(j);let X;try{X=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:Q2({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??K0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...W.manifest.length>0?{clientContributions:W.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:Q2(Q.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let H=o1(X.payload?.snapshot),Y=X.payload?.session,V=(H?.sessionId??Y?.sessionId)?.trim();if(J&&!V){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(V&&j&&V!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(V&&Z)this.sessionCapabilities.set(V,Z);if(V&&W.handlers.size>0)this.sessionClientContributionHandlers.set(V,W.handlers);if(V)this.ensureSessionSubscription(V);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:V,startResult:V?{sessionId:V,manifest:H?zY(H,Q??{}):OY(V,Q??{},Y),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 f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=o1(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,X=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||X?{usage:j,aggregateUsage:X}:void 0}let Q=f.payload?.session,Z=LY(Q?.usage),W=LY(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:typeof f==="string"?f:void 0},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();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 f=await this.client.command("session.get",void 0,$);return Oz(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let W=o1(Z);return W?[gJ(W)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(_Y)}async listSettings($){let f=await this.client.command("settings.list",DY($));if(!f.ok)throw Error(mJ(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",DY($));if(!f.ok)throw Error(mJ(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Wz(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(mJ(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(mJ(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return F0(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:Lz($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($);return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($);return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=o1($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,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 J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=Uz($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,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 J=o1($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:f,reason:J,ts:$.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!W){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Q,X);let H=(Y)=>{this.client.command("capability.progress",{requestId:Q,payload:Y},f)};try{let Y=await W({payload:j,abortSignal:X.signal,progress:H});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:Y},f)}catch(Y){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:Y instanceof Error?Y.message:String(Y)},f)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(Pz($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",W=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!Z||!W)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=Fz($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:W,toolInput:X});let H=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:W,input:X,policy:j})).catch((Y)=>({approved:!1,reason:Y instanceof Error?Y.message:`Tool approval request failed: ${String(Y)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:H.approved,reason:H.reason},f).catch(()=>{})}}var NY={};q(NY,{RemoteRuntimeHost:()=>Z2});class Z2 extends S${constructor($){super({url:A1($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var TY={};q(TY,{SqliteSessionStore:()=>H$});import{existsSync as zz,mkdirSync as _z}from"node:fs";import{join as yz}from"node:path";import{asBool as L4,asOptionalString as X$,asString as C$,ensureSessionSchema as Nz,loadSqliteDb as Tz,nowIso as vJ,toBoolInt as O4}from"@cline/shared/db";import{resolveDbDataDir as Mz}from"@cline/shared/storage";class H${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??Mz()}init(){this.getRawDb()}ensureSessionsDir(){if(!zz(this.sessionsDirPath))_z(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return yz(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=Tz(this.sessionDbPath());return Nz($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=vJ();this.run(`INSERT OR REPLACE INTO sessions (
|
|
483
483
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|